repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/Lsif/GeneratorTest/CompilerInvocationTests.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
Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests
<UseExportProvider>
Public Class CompilerInvocationTests
<Fact>
Public Async Function TestCSharpProject() As Task
' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist.
Dim referencePath = GetType(Object).Assembly.Location
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.cs /target:library /out:Z:\\Output.dll"",
""projectFilePath"": ""Z:\\Project.csproj"",
""sourceRootPath"": ""Z:\\""
}")
Assert.Equal(LanguageNames.CSharp, compilerInvocation.Compilation.Language)
Assert.Equal("Z:\Project.csproj", compilerInvocation.ProjectFilePath)
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind)
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("Z:\SourceFile.cs", syntaxTree.FilePath)
Assert.Equal("DEBUG", Assert.Single(syntaxTree.Options.PreprocessorSymbolNames))
Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References)
Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath)
End Function
<Fact>
Public Async Function TestVisualBasicProject() As Task
' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist.
Dim referencePath = GetType(Object).Assembly.Location
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""vbc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.vb /target:library /out:Z:\\Output.dll"",
""projectFilePath"": ""Z:\\Project.vbproj"",
""sourceRootPath"": ""Z:\\""
}")
Assert.Equal(LanguageNames.VisualBasic, compilerInvocation.Compilation.Language)
Assert.Equal("Z:\Project.vbproj", compilerInvocation.ProjectFilePath)
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind)
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("Z:\SourceFile.vb", syntaxTree.FilePath)
Assert.Contains("DEBUG", syntaxTree.Options.PreprocessorSymbolNames)
Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References)
Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath)
End Function
<Theory>
<CombinatorialData>
Public Async Function TestSourceFilePathMappingWithDriveLetters(<CombinatorialValues("F:", "F:\")> from As String, <CombinatorialValues("T:", "T:\")> [to] As String) As Task
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\SourceFile.cs /target:library /out:F:\\Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": """ + from.Replace("\", "\\") + """,
""to"": """ + [to].Replace("\", "\\") + """
}]
}")
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("T:\SourceFile.cs", syntaxTree.FilePath)
End Function
<Fact>
Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithoutTrailingSlashes() As Task
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\SourceFile.cs /target:library /out:F:\\Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": ""F:\\Directory"",
""to"": ""T:\\Directory""
}]
}")
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath)
End Function
<Fact>
Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithDoubleSlashesInFilePath() As Task
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\\\SourceFile.cs /target:library /out:F:\\Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": ""F:\\Directory"",
""to"": ""T:\\Directory""
}]
}")
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath)
End Function
<Fact>
Public Async Function TestRuleSetPathMapping() As Task
Const RuleSetContents = "<?xml version=""1.0""?>
<RuleSet Name=""Name"" ToolsVersion=""10.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1001"" Action=""Warning"" />
</Rules>
</RuleSet>"
Using ruleSet = New DisposableFile(extension:=".ruleset")
ruleSet.WriteAllText(RuleSetContents)
' We will test that if we redirect the ruleset to the temporary file that we wrote that the values are still read.
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /ruleset:F:\\Ruleset.ruleset /out:Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": ""F:\\Ruleset.ruleset"",
""to"": """ + ruleSet.Path.Replace("\", "\\") + """
}]
}")
Assert.Equal(ReportDiagnostic.Warn, compilerInvocation.Compilation.Options.SpecificDiagnosticOptions("CA1001"))
End Using
End Function
<Fact>
Public Async Function TestSourceGeneratorOutputIncludedInCompilation() As Task
Dim sourceGeneratorLocation = GetType(TestSourceGenerator.HelloWorldGenerator).Assembly.Location
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /analyzer:\""" + sourceGeneratorLocation.Replace("\", "\\") + "\"" /out:Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\""
}")
Dim generatedTrees = compilerInvocation.Compilation.SyntaxTrees
Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedEnglishClassName + ".cs"))
Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedSpanishClassName + ".cs"))
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests
<UseExportProvider>
Public Class CompilerInvocationTests
<Fact>
Public Async Function TestCSharpProject() As Task
' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist.
Dim referencePath = GetType(Object).Assembly.Location
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.cs /target:library /out:Z:\\Output.dll"",
""projectFilePath"": ""Z:\\Project.csproj"",
""sourceRootPath"": ""Z:\\""
}")
Assert.Equal(LanguageNames.CSharp, compilerInvocation.Compilation.Language)
Assert.Equal("Z:\Project.csproj", compilerInvocation.ProjectFilePath)
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind)
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("Z:\SourceFile.cs", syntaxTree.FilePath)
Assert.Equal("DEBUG", Assert.Single(syntaxTree.Options.PreprocessorSymbolNames))
Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References)
Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath)
End Function
<Fact>
Public Async Function TestVisualBasicProject() As Task
' PortableExecutableReference.CreateFromFile implicitly reads the file so the file must exist.
Dim referencePath = GetType(Object).Assembly.Location
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""vbc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /reference:" + referencePath.Replace("\", "\\") + " Z:\\SourceFile.vb /target:library /out:Z:\\Output.dll"",
""projectFilePath"": ""Z:\\Project.vbproj"",
""sourceRootPath"": ""Z:\\""
}")
Assert.Equal(LanguageNames.VisualBasic, compilerInvocation.Compilation.Language)
Assert.Equal("Z:\Project.vbproj", compilerInvocation.ProjectFilePath)
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, compilerInvocation.Compilation.Options.OutputKind)
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("Z:\SourceFile.vb", syntaxTree.FilePath)
Assert.Contains("DEBUG", syntaxTree.Options.PreprocessorSymbolNames)
Dim metadataReference = Assert.Single(compilerInvocation.Compilation.References)
Assert.Equal(referencePath, DirectCast(metadataReference, PortableExecutableReference).FilePath)
End Function
<Theory>
<CombinatorialData>
Public Async Function TestSourceFilePathMappingWithDriveLetters(<CombinatorialValues("F:", "F:\")> from As String, <CombinatorialValues("T:", "T:\")> [to] As String) As Task
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\SourceFile.cs /target:library /out:F:\\Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": """ + from.Replace("\", "\\") + """,
""to"": """ + [to].Replace("\", "\\") + """
}]
}")
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("T:\SourceFile.cs", syntaxTree.FilePath)
End Function
<Fact>
Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithoutTrailingSlashes() As Task
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\SourceFile.cs /target:library /out:F:\\Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": ""F:\\Directory"",
""to"": ""T:\\Directory""
}]
}")
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath)
End Function
<Fact>
Public Async Function TestSourceFilePathMappingWithSubdirectoriesWithDoubleSlashesInFilePath() As Task
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG F:\\Directory\\\\SourceFile.cs /target:library /out:F:\\Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": ""F:\\Directory"",
""to"": ""T:\\Directory""
}]
}")
Dim syntaxTree = Assert.Single(compilerInvocation.Compilation.SyntaxTrees)
Assert.Equal("T:\Directory\SourceFile.cs", syntaxTree.FilePath)
End Function
<Fact>
Public Async Function TestRuleSetPathMapping() As Task
Const RuleSetContents = "<?xml version=""1.0""?>
<RuleSet Name=""Name"" ToolsVersion=""10.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1001"" Action=""Warning"" />
</Rules>
</RuleSet>"
Using ruleSet = New DisposableFile(extension:=".ruleset")
ruleSet.WriteAllText(RuleSetContents)
' We will test that if we redirect the ruleset to the temporary file that we wrote that the values are still read.
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /nowarn:1701,1702 /fullpaths /define:DEBUG /ruleset:F:\\Ruleset.ruleset /out:Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\"",
""pathMappings"": [
{
""from"": ""F:\\Ruleset.ruleset"",
""to"": """ + ruleSet.Path.Replace("\", "\\") + """
}]
}")
Assert.Equal(ReportDiagnostic.Warn, compilerInvocation.Compilation.Options.SpecificDiagnosticOptions("CA1001"))
End Using
End Function
<Fact>
Public Async Function TestSourceGeneratorOutputIncludedInCompilation() As Task
Dim sourceGeneratorLocation = GetType(TestSourceGenerator.HelloWorldGenerator).Assembly.Location
Dim compilerInvocation = Await Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.CompilerInvocation.CreateFromJsonAsync("
{
""tool"": ""csc"",
""arguments"": ""/noconfig /analyzer:\""" + sourceGeneratorLocation.Replace("\", "\\") + "\"" /out:Output.dll"",
""projectFilePath"": ""F:\\Project.csproj"",
""sourceRootPath"": ""F:\\""
}")
Dim generatedTrees = compilerInvocation.Compilation.SyntaxTrees
Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedEnglishClassName + ".cs"))
Assert.Single(generatedTrees, Function(t) t.FilePath.EndsWith(TestSourceGenerator.HelloWorldGenerator.GeneratedSpanishClassName + ".cs"))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/MultiLineLambdaTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class MultiLineLambdaTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithFunctionLambda()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
Dim x = Function()
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
Dim x = Function()
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithFunctionLambdaWithMissingEndFunction()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Function()
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Function()
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithSubLambda()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Sub()
End Function
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Sub()
End Sub
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaWithNoParameterParenthesis()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Sub
End Function
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Sub()
End Sub
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Sub())
End Function
End Class",
beforeCaret:={2, 11},
after:="Class c1
Function goo()
M(Sub()
End Sub)
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaAndStatementInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Sub() Exit Sub)
End Function
End Class",
beforeCaret:={2, 11},
after:="Class c1
Function goo()
M(Sub()
Exit Sub
End Sub)
End Function
End Class",
afterCaret:={3, 10})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithFunctionLambdaInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Function() 1)
End Function
End Class",
beforeCaret:={2, 17},
after:="Class c1
Function goo()
M(Function()
Return 1
End Function)
End Function
End Class",
afterCaret:={3, 17})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyAnonymousType()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = New With {.x = Function(x)
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub s()
Dim x = New With {.x = Function(x)
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifySingleLineLambdaFunc()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function(x) x
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifySingleLineLambdaSub()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim y = Sub(x As Integer) x.ToString()
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyAsDefaultParameterValue()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s(Optional ByVal f As Func(Of String, String) = Function(x As String)
End Class",
beforeCaret:={1, -1},
after:="Class C
Sub s(Optional ByVal f As Func(Of String, String) = Function(x As String)
End Function
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyNestedLambda()
VerifyStatementEndConstructApplied(
before:="Class C
sub s
Dim x = Function (x)
Dim y = function(y)
End Function
End sub
End Class",
beforeCaret:={3, -1},
after:="Class C
sub s
Dim x = Function (x)
Dim y = function(y)
End function
End Function
End sub
End Class",
afterCaret:={4, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyInField()
VerifyStatementEndConstructApplied(
before:="Class C
Dim x = Sub()
End Class",
beforeCaret:={1, -1},
after:="Class C
Dim x = Sub()
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidLambdaSyntax()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Sub(x)
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNotAppliedIfSubLambdaContainsEndSub()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Sub() End Sub
End Sub
End Class",
caret:={2, 21})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNotAppliedIfSyntaxIsFunctionLambdaContainsEndFunction()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function() End Function
End Sub
End Class",
caret:={2, 26})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyLambdaWithImplicitLC()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function(y As Integer) y +
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyLambdaWithMissingParenthesis()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub s()
Dim x = Function()
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySingleLineSubLambdaToMultiLine()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Sub() f()
End Sub
End Class",
beforeCaret:={2, 21},
after:="Class C
Sub s()
Dim x = Sub()
f()
End Sub
End Sub
End Class",
afterCaret:={3, 20})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineSubLambdaToMultiLineWithTrailingTrivia()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Sub() f() ' Invokes f()
End Sub
End Class",
beforeCaret:={2, 21},
after:="Class C
Sub s()
Dim x = Sub()
f() ' Invokes f()
End Sub
End Sub
End Class",
afterCaret:={3, 20})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLine()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function() f()
End Sub
End Class",
beforeCaret:={2, 27},
after:="Class C
Sub s()
Dim x = Function()
Return f()
End Function
End Sub
End Class",
afterCaret:={3, 27})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLineWithTrailingTrivia()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function() 4 ' Returns Constant 4
End Sub
End Class",
beforeCaret:={2, 27},
after:="Class C
Sub s()
Dim x = Function()
Return 4 ' Returns Constant 4
End Function
End Sub
End Class",
afterCaret:={3, 27})
End Sub
<WorkItem(1922, "https://github.com/dotnet/roslyn/issues/1922")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLineInsideXMLTag()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = <xml><%= Function()%></xml>
End Sub
End Class",
beforeCaret:={2, 35},
after:="Class C
Sub s()
Dim x = <xml><%= Function()
End Function %></xml>
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WorkItem(1922, "https://github.com/dotnet/roslyn/issues/1922")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineSubLambdaToMultiLineInsideXMLTag()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = <xml><%= Sub()%></xml>
End Sub
End Class",
beforeCaret:={2, 30},
after:="Class C
Sub s()
Dim x = <xml><%= Sub()
End Sub %></xml>
End Sub
End Class",
afterCaret:={3, -1})
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration
<[UseExportProvider]>
Public Class MultiLineLambdaTests
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithFunctionLambda()
VerifyStatementEndConstructApplied(
before:="Class c1
Sub goo()
Dim x = Function()
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class c1
Sub goo()
Dim x = Function()
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithFunctionLambdaWithMissingEndFunction()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Function()
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Function()
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestApplyWithSubLambda()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Sub()
End Function
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Sub()
End Sub
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaWithNoParameterParenthesis()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
Dim x = Sub
End Function
End Class",
beforeCaret:={2, -1},
after:="Class c1
Function goo()
Dim x = Sub()
End Sub
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Sub())
End Function
End Class",
beforeCaret:={2, 11},
after:="Class c1
Function goo()
M(Sub()
End Sub)
End Function
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithSubLambdaAndStatementInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Sub() Exit Sub)
End Function
End Class",
beforeCaret:={2, 11},
after:="Class c1
Function goo()
M(Sub()
Exit Sub
End Sub)
End Function
End Class",
afterCaret:={3, 10})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(544362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544362")>
Public Sub TestApplyWithFunctionLambdaInsideMethodCall()
VerifyStatementEndConstructApplied(
before:="Class c1
Function goo()
M(Function() 1)
End Function
End Class",
beforeCaret:={2, 17},
after:="Class c1
Function goo()
M(Function()
Return 1
End Function)
End Function
End Class",
afterCaret:={3, 17})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyAnonymousType()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = New With {.x = Function(x)
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub s()
Dim x = New With {.x = Function(x)
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifySingleLineLambdaFunc()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function(x) x
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifySingleLineLambdaSub()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim y = Sub(x As Integer) x.ToString()
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyAsDefaultParameterValue()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s(Optional ByVal f As Func(Of String, String) = Function(x As String)
End Class",
beforeCaret:={1, -1},
after:="Class C
Sub s(Optional ByVal f As Func(Of String, String) = Function(x As String)
End Function
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyNestedLambda()
VerifyStatementEndConstructApplied(
before:="Class C
sub s
Dim x = Function (x)
Dim y = function(y)
End Function
End sub
End Class",
beforeCaret:={3, -1},
after:="Class C
sub s
Dim x = Function (x)
Dim y = function(y)
End function
End Function
End sub
End Class",
afterCaret:={4, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyInField()
VerifyStatementEndConstructApplied(
before:="Class C
Dim x = Sub()
End Class",
beforeCaret:={1, -1},
after:="Class C
Dim x = Sub()
End Sub
End Class",
afterCaret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyInvalidLambdaSyntax()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Sub(x)
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNotAppliedIfSubLambdaContainsEndSub()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Sub() End Sub
End Sub
End Class",
caret:={2, 21})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyNotAppliedIfSyntaxIsFunctionLambdaContainsEndFunction()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function() End Function
End Sub
End Class",
caret:={2, 26})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub VerifyLambdaWithImplicitLC()
VerifyStatementEndConstructNotApplied(
text:="Class C
Sub s()
Dim x = Function(y As Integer) y +
End Sub
End Class",
caret:={2, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifyLambdaWithMissingParenthesis()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function
End Sub
End Class",
beforeCaret:={2, -1},
after:="Class C
Sub s()
Dim x = Function()
End Function
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySingleLineSubLambdaToMultiLine()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Sub() f()
End Sub
End Class",
beforeCaret:={2, 21},
after:="Class C
Sub s()
Dim x = Sub()
f()
End Sub
End Sub
End Class",
afterCaret:={3, 20})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineSubLambdaToMultiLineWithTrailingTrivia()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Sub() f() ' Invokes f()
End Sub
End Class",
beforeCaret:={2, 21},
after:="Class C
Sub s()
Dim x = Sub()
f() ' Invokes f()
End Sub
End Sub
End Class",
afterCaret:={3, 20})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLine()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function() f()
End Sub
End Class",
beforeCaret:={2, 27},
after:="Class C
Sub s()
Dim x = Function()
Return f()
End Function
End Sub
End Class",
afterCaret:={3, 27})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLineWithTrailingTrivia()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = Function() 4 ' Returns Constant 4
End Sub
End Class",
beforeCaret:={2, 27},
after:="Class C
Sub s()
Dim x = Function()
Return 4 ' Returns Constant 4
End Function
End Sub
End Class",
afterCaret:={3, 27})
End Sub
<WorkItem(1922, "https://github.com/dotnet/roslyn/issues/1922")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineFunctionLambdaToMultiLineInsideXMLTag()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = <xml><%= Function()%></xml>
End Sub
End Class",
beforeCaret:={2, 35},
after:="Class C
Sub s()
Dim x = <xml><%= Function()
End Function %></xml>
End Sub
End Class",
afterCaret:={3, -1})
End Sub
<WorkItem(1922, "https://github.com/dotnet/roslyn/issues/1922")>
<WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration), WorkItem(530683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530683")>
Public Sub TestVerifySingleLineSubLambdaToMultiLineInsideXMLTag()
VerifyStatementEndConstructApplied(
before:="Class C
Sub s()
Dim x = <xml><%= Sub()%></xml>
End Sub
End Class",
beforeCaret:={2, 30},
after:="Class C
Sub s()
Dim x = <xml><%= Sub()
End Sub %></xml>
End Sub
End Class",
afterCaret:={3, -1})
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Syntax/SyntaxExtensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Public Module SyntaxExtensions
<Extension()>
Friend Function ReportDocumentationCommentDiagnostics(tree As SyntaxTree) As Boolean
Return tree.Options.DocumentationMode >= DocumentationMode.Diagnose
End Function
<Extension()>
Public Function ToSyntaxTriviaList(sequence As IEnumerable(Of SyntaxTrivia)) As SyntaxTriviaList
Return SyntaxFactory.TriviaList(sequence)
End Function
<Extension()>
Public Function NormalizeWhitespace(Of TNode As SyntaxNode)(node As TNode, useDefaultCasing As Boolean, indentation As String, elasticTrivia As Boolean) As TNode
Return CType(SyntaxNormalizer.Normalize(node, indentation, Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, elasticTrivia, useDefaultCasing), TNode)
End Function
<Extension()>
Public Function NormalizeWhitespace(Of TNode As SyntaxNode)(node As TNode, useDefaultCasing As Boolean, Optional indentation As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultIndentation, Optional eol As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, Optional elasticTrivia As Boolean = False) As TNode
Return CType(SyntaxNormalizer.Normalize(node, indentation, eol, elasticTrivia, useDefaultCasing), TNode)
End Function
<Extension()>
Public Function NormalizeWhitespace(token As SyntaxToken, indentation As String, elasticTrivia As Boolean) As SyntaxToken
Return SyntaxNormalizer.Normalize(token, indentation, Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, elasticTrivia, False)
End Function
<Extension()>
Public Function NormalizeWhitespace(token As SyntaxToken, Optional indentation As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultIndentation, Optional eol As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, Optional elasticTrivia As Boolean = False, Optional useDefaultCasing As Boolean = False) As SyntaxToken
Return SyntaxNormalizer.Normalize(token, indentation, eol, elasticTrivia, useDefaultCasing)
End Function
<Extension()>
Public Function NormalizeWhitespace(trivia As SyntaxTriviaList, Optional indentation As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultIndentation, Optional eol As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, Optional elasticTrivia As Boolean = False, Optional useDefaultCasing As Boolean = False) As SyntaxTriviaList
Return SyntaxNormalizer.Normalize(trivia, indentation, eol, elasticTrivia, useDefaultCasing)
End Function
''' <summary>
''' Returns the TypeSyntax of the given NewExpressionSyntax if specified.
''' </summary>
<Extension()> _
Public Function Type(newExpressionSyntax As NewExpressionSyntax) As TypeSyntax
Select Case newExpressionSyntax.Kind
Case SyntaxKind.ObjectCreationExpression
Return DirectCast(newExpressionSyntax, ObjectCreationExpressionSyntax).Type
Case SyntaxKind.AnonymousObjectCreationExpression
Return Nothing
Case SyntaxKind.ArrayCreationExpression
Return DirectCast(newExpressionSyntax, ArrayCreationExpressionSyntax).Type
Case Else
Throw ExceptionUtilities.UnexpectedValue(newExpressionSyntax.Kind)
End Select
End Function
''' <summary>
''' Returns the TypeSyntax of the given AsClauseSyntax if specified.
''' </summary>
<Extension()> _
Public Function Type(asClauseSyntax As AsClauseSyntax) As TypeSyntax
Select Case asClauseSyntax.Kind
Case SyntaxKind.SimpleAsClause
Return DirectCast(asClauseSyntax, SimpleAsClauseSyntax).Type
Case SyntaxKind.AsNewClause
Return DirectCast(asClauseSyntax, AsNewClauseSyntax).NewExpression.Type
Case Else
Throw ExceptionUtilities.UnexpectedValue(asClauseSyntax.Kind)
End Select
End Function
''' <summary>
''' Returns the AttributeBlockSyntax of the given AsClauseSyntax if specified.
''' </summary>
<Extension()> _
Public Function Attributes(asClauseSyntax As AsClauseSyntax) As SyntaxList(Of AttributeListSyntax)
Select Case asClauseSyntax.Kind
Case SyntaxKind.SimpleAsClause
Return DirectCast(asClauseSyntax, SimpleAsClauseSyntax).AttributeLists
Case SyntaxKind.AsNewClause
Return DirectCast(asClauseSyntax, AsNewClauseSyntax).NewExpression.AttributeLists
Case Else
Throw ExceptionUtilities.UnexpectedValue(asClauseSyntax.Kind)
End Select
End Function
''' <summary>
''' Updates the given SimpleNameSyntax node with the given identifier token.
''' This function is a wrapper that calls WithIdentifier on derived syntax nodes.
''' </summary>
''' <param name="simpleName"></param>
''' <param name="identifier"></param>
''' <returns>The given simple name updated with the given identifier.</returns>
<Extension>
Public Function WithIdentifier(simpleName As SimpleNameSyntax, identifier As SyntaxToken) As SimpleNameSyntax
Return If(simpleName.Kind = SyntaxKind.IdentifierName,
DirectCast(DirectCast(simpleName, IdentifierNameSyntax).WithIdentifier(identifier), SimpleNameSyntax),
DirectCast(DirectCast(simpleName, GenericNameSyntax).WithIdentifier(identifier), SimpleNameSyntax))
End Function
''' <summary>
''' Given an initializer expression infer the name of anonymous property or tuple element.
''' Returns Nothing if unsuccessful
''' </summary>
<Extension>
Public Function TryGetInferredMemberName(syntax As SyntaxNode) As String
If syntax Is Nothing Then
Return Nothing
End If
Dim expr = TryCast(syntax, ExpressionSyntax)
If expr Is Nothing Then
Return Nothing
End If
Dim ignore As XmlNameSyntax = Nothing
Dim nameToken As SyntaxToken = expr.ExtractAnonymousTypeMemberName(ignore)
Return If(nameToken.Kind() = SyntaxKind.IdentifierToken, nameToken.ValueText, Nothing)
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.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Public Module SyntaxExtensions
<Extension()>
Friend Function ReportDocumentationCommentDiagnostics(tree As SyntaxTree) As Boolean
Return tree.Options.DocumentationMode >= DocumentationMode.Diagnose
End Function
<Extension()>
Public Function ToSyntaxTriviaList(sequence As IEnumerable(Of SyntaxTrivia)) As SyntaxTriviaList
Return SyntaxFactory.TriviaList(sequence)
End Function
<Extension()>
Public Function NormalizeWhitespace(Of TNode As SyntaxNode)(node As TNode, useDefaultCasing As Boolean, indentation As String, elasticTrivia As Boolean) As TNode
Return CType(SyntaxNormalizer.Normalize(node, indentation, Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, elasticTrivia, useDefaultCasing), TNode)
End Function
<Extension()>
Public Function NormalizeWhitespace(Of TNode As SyntaxNode)(node As TNode, useDefaultCasing As Boolean, Optional indentation As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultIndentation, Optional eol As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, Optional elasticTrivia As Boolean = False) As TNode
Return CType(SyntaxNormalizer.Normalize(node, indentation, eol, elasticTrivia, useDefaultCasing), TNode)
End Function
<Extension()>
Public Function NormalizeWhitespace(token As SyntaxToken, indentation As String, elasticTrivia As Boolean) As SyntaxToken
Return SyntaxNormalizer.Normalize(token, indentation, Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, elasticTrivia, False)
End Function
<Extension()>
Public Function NormalizeWhitespace(token As SyntaxToken, Optional indentation As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultIndentation, Optional eol As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, Optional elasticTrivia As Boolean = False, Optional useDefaultCasing As Boolean = False) As SyntaxToken
Return SyntaxNormalizer.Normalize(token, indentation, eol, elasticTrivia, useDefaultCasing)
End Function
<Extension()>
Public Function NormalizeWhitespace(trivia As SyntaxTriviaList, Optional indentation As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultIndentation, Optional eol As String = Microsoft.CodeAnalysis.SyntaxNodeExtensions.DefaultEOL, Optional elasticTrivia As Boolean = False, Optional useDefaultCasing As Boolean = False) As SyntaxTriviaList
Return SyntaxNormalizer.Normalize(trivia, indentation, eol, elasticTrivia, useDefaultCasing)
End Function
''' <summary>
''' Returns the TypeSyntax of the given NewExpressionSyntax if specified.
''' </summary>
<Extension()> _
Public Function Type(newExpressionSyntax As NewExpressionSyntax) As TypeSyntax
Select Case newExpressionSyntax.Kind
Case SyntaxKind.ObjectCreationExpression
Return DirectCast(newExpressionSyntax, ObjectCreationExpressionSyntax).Type
Case SyntaxKind.AnonymousObjectCreationExpression
Return Nothing
Case SyntaxKind.ArrayCreationExpression
Return DirectCast(newExpressionSyntax, ArrayCreationExpressionSyntax).Type
Case Else
Throw ExceptionUtilities.UnexpectedValue(newExpressionSyntax.Kind)
End Select
End Function
''' <summary>
''' Returns the TypeSyntax of the given AsClauseSyntax if specified.
''' </summary>
<Extension()> _
Public Function Type(asClauseSyntax As AsClauseSyntax) As TypeSyntax
Select Case asClauseSyntax.Kind
Case SyntaxKind.SimpleAsClause
Return DirectCast(asClauseSyntax, SimpleAsClauseSyntax).Type
Case SyntaxKind.AsNewClause
Return DirectCast(asClauseSyntax, AsNewClauseSyntax).NewExpression.Type
Case Else
Throw ExceptionUtilities.UnexpectedValue(asClauseSyntax.Kind)
End Select
End Function
''' <summary>
''' Returns the AttributeBlockSyntax of the given AsClauseSyntax if specified.
''' </summary>
<Extension()> _
Public Function Attributes(asClauseSyntax As AsClauseSyntax) As SyntaxList(Of AttributeListSyntax)
Select Case asClauseSyntax.Kind
Case SyntaxKind.SimpleAsClause
Return DirectCast(asClauseSyntax, SimpleAsClauseSyntax).AttributeLists
Case SyntaxKind.AsNewClause
Return DirectCast(asClauseSyntax, AsNewClauseSyntax).NewExpression.AttributeLists
Case Else
Throw ExceptionUtilities.UnexpectedValue(asClauseSyntax.Kind)
End Select
End Function
''' <summary>
''' Updates the given SimpleNameSyntax node with the given identifier token.
''' This function is a wrapper that calls WithIdentifier on derived syntax nodes.
''' </summary>
''' <param name="simpleName"></param>
''' <param name="identifier"></param>
''' <returns>The given simple name updated with the given identifier.</returns>
<Extension>
Public Function WithIdentifier(simpleName As SimpleNameSyntax, identifier As SyntaxToken) As SimpleNameSyntax
Return If(simpleName.Kind = SyntaxKind.IdentifierName,
DirectCast(DirectCast(simpleName, IdentifierNameSyntax).WithIdentifier(identifier), SimpleNameSyntax),
DirectCast(DirectCast(simpleName, GenericNameSyntax).WithIdentifier(identifier), SimpleNameSyntax))
End Function
''' <summary>
''' Given an initializer expression infer the name of anonymous property or tuple element.
''' Returns Nothing if unsuccessful
''' </summary>
<Extension>
Public Function TryGetInferredMemberName(syntax As SyntaxNode) As String
If syntax Is Nothing Then
Return Nothing
End If
Dim expr = TryCast(syntax, ExpressionSyntax)
If expr Is Nothing Then
Return Nothing
End If
Dim ignore As XmlNameSyntax = Nothing
Dim nameToken As SyntaxToken = expr.ExtractAnonymousTypeMemberName(ignore)
Return If(nameToken.Kind() = SyntaxKind.IdentifierToken, nameToken.ValueText, Nothing)
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/VisualBasic/Portable/Formatting/VisualBasicNewDocumentFormattingService.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
<ExportLanguageService(GetType(INewDocumentFormattingService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicNewDocumentFormattingService
Inherits AbstractNewDocumentFormattingService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(<ImportMany> providers As IEnumerable(Of Lazy(Of INewDocumentFormattingProvider, LanguageMetadata)))
MyBase.New(providers)
End Sub
Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
<ExportLanguageService(GetType(INewDocumentFormattingService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicNewDocumentFormattingService
Inherits AbstractNewDocumentFormattingService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(<ImportMany> providers As IEnumerable(Of Lazy(Of INewDocumentFormattingProvider, LanguageMetadata)))
MyBase.New(providers)
End Sub
Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockSemanticModelTests.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.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class WithBlockSemanticModelTests
Inherits FlowTestBase
#Region "Symbol / Type Info"
<Fact>
Public Sub WithAliasedStaticField()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports Alias1 = ClassWithField
Class ClassWithField
Public Shared field1 As String = "a"
End Class
Module WithAliasedStaticField
Sub Main()
With Alias1.field1 'BIND:"Alias1.field1"
Dim newString = .Replace("a", "b")
End With
End Sub
End Module
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim withExpression = DirectCast(tree.GetCompilationUnitRoot().DescendantNodes().Where(Function(n) n.Kind = SyntaxKind.SimpleMemberAccessExpression).First(), MemberAccessExpressionSyntax)
Assert.Equal("Alias1", model.GetAliasInfo(DirectCast(withExpression.Expression, IdentifierNameSyntax)).ToDisplayString())
Assert.False(model.GetConstantValue(withExpression).HasValue)
Dim typeInfo = model.GetTypeInfo(withExpression)
Assert.Equal("String", typeInfo.Type.ToDisplayString())
Assert.Equal("String", typeInfo.ConvertedType.ToDisplayString())
Dim conv = model.GetConversion(withExpression)
Assert.Equal(ConversionKind.Identity, conv.Kind)
Dim symbolInfo = model.GetSymbolInfo(withExpression)
Assert.Equal("Public Shared field1 As String", symbolInfo.Symbol.ToDisplayString())
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(0, model.GetMemberGroup(withExpression).Length)
End Sub
<Fact>
Public Sub WithDeclaresAnonymousLocalSymbolAndTypeInfo()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Module WithDeclaresAnonymousLocalSymbolAndTypeInfo
Sub Main()
With New With {.A = 1, .B = "2"} 'BIND:"New With {.A = 1, .B = "2"}"
.A = .B
End With
End Sub
End Module
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AnonymousObjectCreationExpressionSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Alias)
Assert.False(semanticInfo.ConstantValue.HasValue)
Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.Type.ToDisplayString())
Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.ConvertedType.ToDisplayString())
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Public Sub New(A As Integer, B As String)", semanticInfo.Symbol.ToDisplayString()) ' should get constructor for anonymous type
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
End Sub
<Fact(), WorkItem(544083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544083")>
Public Sub WithSpeculativeSymbolInfo()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Class C1
Property Property1 As Integer
Property Property2 As String
End Class
Module Module1
Sub Main()
Dim x As New C1()
With x
Dim f = Function() .Property1 'BINDHERE
End With
End Sub
End Module
</file>
</compilation>)
Dim semanticModel = GetSemanticModel(compilation, "a.vb")
Dim position = compilation.SyntaxTrees.Single().ToString().IndexOf("'BINDHERE", StringComparison.Ordinal)
Dim expr = SyntaxFactory.ParseExpression(".property2")
Dim speculativeTypeInfo = semanticModel.GetSpeculativeTypeInfo(position, expr, SpeculativeBindingOption.BindAsExpression)
Assert.Equal("String", speculativeTypeInfo.ConvertedType.ToDisplayString())
Dim conv = semanticModel.GetSpeculativeConversion(position, expr, SpeculativeBindingOption.BindAsExpression)
Assert.Equal(ConversionKind.Identity, conv.Kind)
Assert.Equal("String", speculativeTypeInfo.Type.ToDisplayString())
Dim speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, SyntaxFactory.ParseExpression(".property2"), SpeculativeBindingOption.BindAsExpression)
Assert.Equal("Public Property Property2 As String", speculativeSymbolInfo.Symbol.ToDisplayString())
Assert.Equal(SymbolKind.Property, speculativeSymbolInfo.Symbol.Kind)
End Sub
#End Region
#Region "FlowAnalysis"
<Fact>
Public Sub UseWithVariableInNestedLambda()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Class C1
Property Property1 As Integer
End Class
Module Module1
Sub Main()
Dim x As New C1()
With x
Dim f = Function()
[|Return .Property1|]
End Function
End With
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Empty(dataFlowResults.DataFlowsIn)
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Empty(dataFlowResults.ReadInside)
Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Equal("x, f", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Empty(controlFlowResults.EntryPoints)
Assert.False(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
Assert.Equal(1, controlFlowResults.ExitPoints.Count)
End Sub
<Fact>
Public Sub WithDeclaresAnonymousLocalDataFlow()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Module WithDeclaresAnonymousLocal
Sub Main()
With New With {.A = 1, .B = "2"}
[|.A = .B|]
End With
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Empty(dataFlowResults.DataFlowsIn) ' assume anonymous locals don't show
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Empty(dataFlowResults.ReadInside) ' assume anonymous locals don't show
Assert.Empty(dataFlowResults.ReadOutside)
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Empty(dataFlowResults.WrittenOutside) ' assume anonymous locals don't show
Assert.Empty(controlFlowResults.ExitPoints)
Assert.Empty(controlFlowResults.EntryPoints)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact>
Public Sub EmptyWith()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x As Object()
[|With x
End With|]
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Empty(dataFlowResults.ReadOutside)
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Empty(dataFlowResults.WrittenOutside)
Assert.Empty(controlFlowResults.ExitPoints)
Assert.Empty(controlFlowResults.EntryPoints)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
#End Region
<Fact, WorkItem(2662, "https://github.com/dotnet/roslyn/issues/2662")>
Public Sub Issue2662()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Module Program
Sub Main(args As String())
End Sub
Private Sub AddCustomer()
Dim theCustomer As New Customer
With theCustomer
.Name = "Abc"
.URL = "http://www.microsoft.com/"
.City = "Redmond"
.Print(.Name)
End With
End Sub
<Extension()>
Public Sub Print(ByVal cust As Customer, str As String)
Console.WriteLine(str)
End Sub
Public Class Customer
Public Property Name As String
Public Property City As String
Public Property URL As String
Public Property Comments As New List(Of String)
End Class
End Module
]]></file>
</compilation>, {Net40.SystemCore})
compilation.AssertNoDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim withBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single()
Dim name = withBlock.Statements(3).DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(i) i.Identifier.ValueText = "Name").Single()
model.GetAliasInfo(name)
Dim result2 = model.AnalyzeDataFlow(withBlock, withBlock)
Assert.True(result2.Succeeded)
model = compilation.GetSemanticModel(tree)
model.GetAliasInfo(name)
Assert.Equal("theCustomer As Program.Customer", model.GetSymbolInfo(withBlock.WithStatement.Expression).Symbol.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(187910, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=187910&_a=edit")>
Public Sub Bug187910()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Class ClassWithField
Public field1 As String = "a"
End Class
Class WithAliasedStaticField
Sub Test(parameter as ClassWithField)
With parameter
System.Console.WriteLine(.field1)
End With
End Sub
End Class
</file>
</compilation>)
Dim compilationB = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
Class WithAliasedStaticField1
Sub Test(parameter as ClassWithField)
With parameter
System.Console.WriteLine(.field1)
End With
End Sub
End Class
</file>
</compilation>)
compilation.AssertTheseDiagnostics()
Dim treeA = compilation.SyntaxTrees.Single()
Dim modelA = compilation.GetSemanticModel(treeA)
Dim parameter = treeA.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "parameter").First()
Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelA.GetEnclosingSymbol(parameter.SpanStart).ToTestDisplayString())
Dim treeB = compilationB.SyntaxTrees.Single()
Dim withBlockB = treeB.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single()
Dim modelAB As SemanticModel = Nothing
Assert.True(modelA.TryGetSpeculativeSemanticModel(parameter.Parent.Parent.SpanStart, withBlockB, modelAB))
Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelAB.GetEnclosingSymbol(withBlockB.WithStatement.Expression.SpanStart).ToTestDisplayString())
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Base
End Class
Class Derived
Inherits Base
Public Function Contains(node As Base) As Boolean
Return True
End Function
End Class
Module Ext
Sub M(vbNode As Derived)
With vbNode
If .Contains(vbNode) Then
End If
End With
End Sub
End Module
</file>
</compilation>)
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Ext
<System.Runtime.CompilerServices.Extension()>
Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
Return Nothing
End Function
Sub M(vbNode As Derived)
With vbNode
If .GetCurrent(vbNode) Is Nothing Then
End If
End With
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_03()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class Base
End Class
Class Derived
Inherits Base
Public Function Contains(node As Base) As Boolean
Return True
End Function
End Class
Module Ext
<System.Runtime.CompilerServices.Extension()>
Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
Return Nothing
End Function
Sub M(vbNode As Derived)
With vbNode
If .GetCurrent(vbNode) Is Nothing Then
End If
If .Contains(vbNode) Then
End If
End With
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)
Dim symbolInfo3 = model.GetSymbolInfo(nodes(2))
Assert.Equal("vbNode As Derived", symbolInfo3.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo3.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
Assert.Same(symbolInfo1.Symbol, symbolInfo3.Symbol)
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_04()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Ext
<System.Runtime.CompilerServices.Extension()>
Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
Return Nothing
End Function
readonly property vbNode As Derived
Get
return nothing
End Get
End Property
Sub M()
With vbNode
If .GetCurrent(vbNode) Is Nothing Then
End If
End With
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Property, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Property, symbolInfo2.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class WithBlockSemanticModelTests
Inherits FlowTestBase
#Region "Symbol / Type Info"
<Fact>
Public Sub WithAliasedStaticField()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports Alias1 = ClassWithField
Class ClassWithField
Public Shared field1 As String = "a"
End Class
Module WithAliasedStaticField
Sub Main()
With Alias1.field1 'BIND:"Alias1.field1"
Dim newString = .Replace("a", "b")
End With
End Sub
End Module
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim withExpression = DirectCast(tree.GetCompilationUnitRoot().DescendantNodes().Where(Function(n) n.Kind = SyntaxKind.SimpleMemberAccessExpression).First(), MemberAccessExpressionSyntax)
Assert.Equal("Alias1", model.GetAliasInfo(DirectCast(withExpression.Expression, IdentifierNameSyntax)).ToDisplayString())
Assert.False(model.GetConstantValue(withExpression).HasValue)
Dim typeInfo = model.GetTypeInfo(withExpression)
Assert.Equal("String", typeInfo.Type.ToDisplayString())
Assert.Equal("String", typeInfo.ConvertedType.ToDisplayString())
Dim conv = model.GetConversion(withExpression)
Assert.Equal(ConversionKind.Identity, conv.Kind)
Dim symbolInfo = model.GetSymbolInfo(withExpression)
Assert.Equal("Public Shared field1 As String", symbolInfo.Symbol.ToDisplayString())
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(0, model.GetMemberGroup(withExpression).Length)
End Sub
<Fact>
Public Sub WithDeclaresAnonymousLocalSymbolAndTypeInfo()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Module WithDeclaresAnonymousLocalSymbolAndTypeInfo
Sub Main()
With New With {.A = 1, .B = "2"} 'BIND:"New With {.A = 1, .B = "2"}"
.A = .B
End With
End Sub
End Module
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AnonymousObjectCreationExpressionSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Alias)
Assert.False(semanticInfo.ConstantValue.HasValue)
Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.Type.ToDisplayString())
Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.ConvertedType.ToDisplayString())
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Public Sub New(A As Integer, B As String)", semanticInfo.Symbol.ToDisplayString()) ' should get constructor for anonymous type
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
End Sub
<Fact(), WorkItem(544083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544083")>
Public Sub WithSpeculativeSymbolInfo()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Class C1
Property Property1 As Integer
Property Property2 As String
End Class
Module Module1
Sub Main()
Dim x As New C1()
With x
Dim f = Function() .Property1 'BINDHERE
End With
End Sub
End Module
</file>
</compilation>)
Dim semanticModel = GetSemanticModel(compilation, "a.vb")
Dim position = compilation.SyntaxTrees.Single().ToString().IndexOf("'BINDHERE", StringComparison.Ordinal)
Dim expr = SyntaxFactory.ParseExpression(".property2")
Dim speculativeTypeInfo = semanticModel.GetSpeculativeTypeInfo(position, expr, SpeculativeBindingOption.BindAsExpression)
Assert.Equal("String", speculativeTypeInfo.ConvertedType.ToDisplayString())
Dim conv = semanticModel.GetSpeculativeConversion(position, expr, SpeculativeBindingOption.BindAsExpression)
Assert.Equal(ConversionKind.Identity, conv.Kind)
Assert.Equal("String", speculativeTypeInfo.Type.ToDisplayString())
Dim speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, SyntaxFactory.ParseExpression(".property2"), SpeculativeBindingOption.BindAsExpression)
Assert.Equal("Public Property Property2 As String", speculativeSymbolInfo.Symbol.ToDisplayString())
Assert.Equal(SymbolKind.Property, speculativeSymbolInfo.Symbol.Kind)
End Sub
#End Region
#Region "FlowAnalysis"
<Fact>
Public Sub UseWithVariableInNestedLambda()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Class C1
Property Property1 As Integer
End Class
Module Module1
Sub Main()
Dim x As New C1()
With x
Dim f = Function()
[|Return .Property1|]
End Function
End With
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Empty(dataFlowResults.DataFlowsIn)
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Empty(dataFlowResults.ReadInside)
Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Equal("x, f", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Empty(controlFlowResults.EntryPoints)
Assert.False(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
Assert.Equal(1, controlFlowResults.ExitPoints.Count)
End Sub
<Fact>
Public Sub WithDeclaresAnonymousLocalDataFlow()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Module WithDeclaresAnonymousLocal
Sub Main()
With New With {.A = 1, .B = "2"}
[|.A = .B|]
End With
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Empty(dataFlowResults.DataFlowsIn) ' assume anonymous locals don't show
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Empty(dataFlowResults.ReadInside) ' assume anonymous locals don't show
Assert.Empty(dataFlowResults.ReadOutside)
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Empty(dataFlowResults.WrittenOutside) ' assume anonymous locals don't show
Assert.Empty(controlFlowResults.ExitPoints)
Assert.Empty(controlFlowResults.EntryPoints)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact>
Public Sub EmptyWith()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x As Object()
[|With x
End With|]
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Equal("x", GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Empty(dataFlowResults.ReadOutside)
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Empty(dataFlowResults.WrittenOutside)
Assert.Empty(controlFlowResults.ExitPoints)
Assert.Empty(controlFlowResults.EntryPoints)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
#End Region
<Fact, WorkItem(2662, "https://github.com/dotnet/roslyn/issues/2662")>
Public Sub Issue2662()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Module Program
Sub Main(args As String())
End Sub
Private Sub AddCustomer()
Dim theCustomer As New Customer
With theCustomer
.Name = "Abc"
.URL = "http://www.microsoft.com/"
.City = "Redmond"
.Print(.Name)
End With
End Sub
<Extension()>
Public Sub Print(ByVal cust As Customer, str As String)
Console.WriteLine(str)
End Sub
Public Class Customer
Public Property Name As String
Public Property City As String
Public Property URL As String
Public Property Comments As New List(Of String)
End Class
End Module
]]></file>
</compilation>, {Net40.SystemCore})
compilation.AssertNoDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim withBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single()
Dim name = withBlock.Statements(3).DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(i) i.Identifier.ValueText = "Name").Single()
model.GetAliasInfo(name)
Dim result2 = model.AnalyzeDataFlow(withBlock, withBlock)
Assert.True(result2.Succeeded)
model = compilation.GetSemanticModel(tree)
model.GetAliasInfo(name)
Assert.Equal("theCustomer As Program.Customer", model.GetSymbolInfo(withBlock.WithStatement.Expression).Symbol.ToTestDisplayString())
End Sub
<Fact>
<WorkItem(187910, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=187910&_a=edit")>
Public Sub Bug187910()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Class ClassWithField
Public field1 As String = "a"
End Class
Class WithAliasedStaticField
Sub Test(parameter as ClassWithField)
With parameter
System.Console.WriteLine(.field1)
End With
End Sub
End Class
</file>
</compilation>)
Dim compilationB = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
Class WithAliasedStaticField1
Sub Test(parameter as ClassWithField)
With parameter
System.Console.WriteLine(.field1)
End With
End Sub
End Class
</file>
</compilation>)
compilation.AssertTheseDiagnostics()
Dim treeA = compilation.SyntaxTrees.Single()
Dim modelA = compilation.GetSemanticModel(treeA)
Dim parameter = treeA.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "parameter").First()
Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelA.GetEnclosingSymbol(parameter.SpanStart).ToTestDisplayString())
Dim treeB = compilationB.SyntaxTrees.Single()
Dim withBlockB = treeB.GetCompilationUnitRoot().DescendantNodes().OfType(Of WithBlockSyntax)().Single()
Dim modelAB As SemanticModel = Nothing
Assert.True(modelA.TryGetSpeculativeSemanticModel(parameter.Parent.Parent.SpanStart, withBlockB, modelAB))
Assert.Equal("Sub WithAliasedStaticField.Test(parameter As ClassWithField)", modelAB.GetEnclosingSymbol(withBlockB.WithStatement.Expression.SpanStart).ToTestDisplayString())
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_01()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Base
End Class
Class Derived
Inherits Base
Public Function Contains(node As Base) As Boolean
Return True
End Function
End Class
Module Ext
Sub M(vbNode As Derived)
With vbNode
If .Contains(vbNode) Then
End If
End With
End Sub
End Module
</file>
</compilation>)
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Ext
<System.Runtime.CompilerServices.Extension()>
Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
Return Nothing
End Function
Sub M(vbNode As Derived)
With vbNode
If .GetCurrent(vbNode) Is Nothing Then
End If
End With
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_03()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class Base
End Class
Class Derived
Inherits Base
Public Function Contains(node As Base) As Boolean
Return True
End Function
End Class
Module Ext
<System.Runtime.CompilerServices.Extension()>
Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
Return Nothing
End Function
Sub M(vbNode As Derived)
With vbNode
If .GetCurrent(vbNode) Is Nothing Then
End If
If .Contains(vbNode) Then
End If
End With
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo2.Symbol.Kind)
Dim symbolInfo3 = model.GetSymbolInfo(nodes(2))
Assert.Equal("vbNode As Derived", symbolInfo3.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Parameter, symbolInfo3.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
Assert.Same(symbolInfo1.Symbol, symbolInfo3.Symbol)
End Sub
<Fact>
<WorkItem(10929, "https://github.com/dotnet/roslyn/issues/10929")>
Public Sub WithTargetAsArgument_04()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Ext
<System.Runtime.CompilerServices.Extension()>
Public Function GetCurrent(Of TNode As Base)(root As Base, node As TNode) As TNode
Return Nothing
End Function
readonly property vbNode As Derived
Get
return nothing
End Get
End Property
Sub M()
With vbNode
If .GetCurrent(vbNode) Is Nothing Then
End If
End With
End Sub
End Module
]]></file>
</compilation>, additionalRefs:={Net40.SystemCore})
compilation.AssertTheseDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "vbNode").ToArray()
Dim symbolInfo1 = model.GetSymbolInfo(nodes(0))
Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Property, symbolInfo1.Symbol.Kind)
Dim symbolInfo2 = model.GetSymbolInfo(nodes(1))
Assert.Equal("ReadOnly Property Ext.vbNode As Derived", symbolInfo2.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Property, symbolInfo2.Symbol.Kind)
Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/Test2/ReferenceHighlighting/VisualBasicReferenceHighlightingTests.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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting
Public Class VisualBasicReferenceHighlightingTests
Inherits AbstractReferenceHighlightingTests
<WpfTheory>
<CombinatorialData>
Public Async Function TestVerifyNoHighlightsWhenOptionDisabled(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class $$Goo
Dim f As Goo
End Class
</Document>
</Project>
</Workspace>,
testHost, optionIsEnabled:=False)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(539121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539121")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithConstructor(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class {|Definition:$$Goo|}
Public Sub {|Definition:New|}()
Dim x = New {|Reference:Goo|}()
Dim y As New {|Reference:Goo|}()
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(539121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539121")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithSynthesizedConstructor(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class {|Definition:Goo|}
Public Sub Blah()
Dim x = New {|Reference:$$Goo|}()
Dim y As New {|Reference:Goo|}()
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(540670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540670")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithMethodNameChange1(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Sub {|Definition:$$Goo|}()
End Interface
Class C
Implements I
Public Sub Bar() Implements I.{|Reference:Goo|}
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(540670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540670")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithMethodNameChange2(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Sub {|Definition:Goo|}()
End Interface
Class C
Implements I
Public Sub Bar() Implements I.{|Reference:$$Goo|}
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(540670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540670")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithMethodNameChange3(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Sub {|Definition:Goo|}()
End Interface
Class C
Implements I
Public Sub {|Definition:Goo|}() Implements I.{|Reference:$$Goo|}
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(543816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543816")>
Public Async Function TestVerifyNoHighlightsForLiteral(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Dim x as Integer = $$23
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(545531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545531")>
Public Async Function TestVerifyHighlightsForGlobal(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Sub Main
{|Reference:$$Global|}.M.Main()
{|Reference:Global|}.M.Main()
End Sub
End Module
</Document>
</Project>
</Workspace>, testHost)
End Function
<WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")>
<WpfTheory>
<CombinatorialData>
Public Async Function TestAccessor1(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Property P As String
$$Get
Return P
End Get
Set(value As String)
P = ""
End Set
End Property
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")>
<WpfTheory>
<CombinatorialData>
Public Async Function TestAccessor2(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Property P As String
Get
Return P
End Get
$$Set(value As String)
P = ""
End Set
End Property
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WorkItem(531624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531624")>
<WpfTheory>
<CombinatorialData>
Public Async Function TestHighlightParameterizedPropertyParameter(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Default Public Property Goo($${|Definition:x|} As Integer) As Integer
Get
Return {|Reference:x|}
End Get
Set(value As Integer)
End Set
End Property
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WpfTheory>
<CombinatorialData>
Public Async Function TestWrittenReference(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Public Sub New()
Dim {|Definition:$$x|} As Integer
{|WrittenReference:x|} = 0
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WpfTheory>
<CombinatorialData>
Public Async Function TestWrittenReference2(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Public Sub New()
Dim {|Definition:$$x|} As Integer
Goo({|WrittenReference:x|})
End Sub
Public Sub Goo(ByRef a as Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(1904, "https://github.com/dotnet/roslyn/issues/1904")>
<WorkItem(2079, "https://github.com/dotnet/roslyn/issues/2079")>
Public Async Function TestVerifyHighlightsForVisualBasicGlobalImportAliasedNamespace(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<CompilationOptions><GlobalImport>VB = Microsoft.VisualBasic</GlobalImport></CompilationOptions>
<Document>
Class Test
Public Sub TestMethod()
' Add reference tags to verify after #2079 is fixed
Console.Write(NameOf($$VB))
Console.Write(NameOf(VB))
Console.Write(NameOf(Microsoft.VisualBasic))
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting
Public Class VisualBasicReferenceHighlightingTests
Inherits AbstractReferenceHighlightingTests
<WpfTheory>
<CombinatorialData>
Public Async Function TestVerifyNoHighlightsWhenOptionDisabled(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class $$Goo
Dim f As Goo
End Class
</Document>
</Project>
</Workspace>,
testHost, optionIsEnabled:=False)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(539121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539121")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithConstructor(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class {|Definition:$$Goo|}
Public Sub {|Definition:New|}()
Dim x = New {|Reference:Goo|}()
Dim y As New {|Reference:Goo|}()
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(539121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539121")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithSynthesizedConstructor(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class {|Definition:Goo|}
Public Sub Blah()
Dim x = New {|Reference:$$Goo|}()
Dim y As New {|Reference:Goo|}()
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(540670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540670")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithMethodNameChange1(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Sub {|Definition:$$Goo|}()
End Interface
Class C
Implements I
Public Sub Bar() Implements I.{|Reference:Goo|}
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(540670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540670")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithMethodNameChange2(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Sub {|Definition:Goo|}()
End Interface
Class C
Implements I
Public Sub Bar() Implements I.{|Reference:$$Goo|}
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(540670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540670")>
Public Async Function TestVerifyHighlightsForVisualBasicClassWithMethodNameChange3(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Sub {|Definition:Goo|}()
End Interface
Class C
Implements I
Public Sub {|Definition:Goo|}() Implements I.{|Reference:$$Goo|}
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(543816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543816")>
Public Async Function TestVerifyNoHighlightsForLiteral(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Dim x as Integer = $$23
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(545531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545531")>
Public Async Function TestVerifyHighlightsForGlobal(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Sub Main
{|Reference:$$Global|}.M.Main()
{|Reference:Global|}.M.Main()
End Sub
End Module
</Document>
</Project>
</Workspace>, testHost)
End Function
<WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")>
<WpfTheory>
<CombinatorialData>
Public Async Function TestAccessor1(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Property P As String
$$Get
Return P
End Get
Set(value As String)
P = ""
End Set
End Property
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")>
<WpfTheory>
<CombinatorialData>
Public Async Function TestAccessor2(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Property P As String
Get
Return P
End Get
$$Set(value As String)
P = ""
End Set
End Property
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WorkItem(531624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531624")>
<WpfTheory>
<CombinatorialData>
Public Async Function TestHighlightParameterizedPropertyParameter(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Default Public Property Goo($${|Definition:x|} As Integer) As Integer
Get
Return {|Reference:x|}
End Get
Set(value As Integer)
End Set
End Property
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WpfTheory>
<CombinatorialData>
Public Async Function TestWrittenReference(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Public Sub New()
Dim {|Definition:$$x|} As Integer
{|WrittenReference:x|} = 0
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WpfTheory>
<CombinatorialData>
Public Async Function TestWrittenReference2(testHost As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Goo
Public Sub New()
Dim {|Definition:$$x|} As Integer
Goo({|WrittenReference:x|})
End Sub
Public Sub Goo(ByRef a as Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input, testHost)
End Function
<WpfTheory>
<CombinatorialData>
<WorkItem(1904, "https://github.com/dotnet/roslyn/issues/1904")>
<WorkItem(2079, "https://github.com/dotnet/roslyn/issues/2079")>
Public Async Function TestVerifyHighlightsForVisualBasicGlobalImportAliasedNamespace(testHost As TestHost) As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<CompilationOptions><GlobalImport>VB = Microsoft.VisualBasic</GlobalImport></CompilationOptions>
<Document>
Class Test
Public Sub TestMethod()
' Add reference tags to verify after #2079 is fixed
Console.Write(NameOf($$VB))
Console.Write(NameOf(VB))
Console.Write(NameOf(Microsoft.VisualBasic))
End Sub
End Class
</Document>
</Project>
</Workspace>, testHost)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/VisualBasic/Portable/GenerateMember/GenerateParameterizedMember/VisualBasicCommonGenerationServiceMethods.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.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod
Friend Class VisualBasicCommonGenerationServiceMethods
Public Shared Function AreSpecialOptionsActive(semanticModel As SemanticModel) As Boolean
' Check to see if option strict is on. if that is the case we will want to still
' generate methods even if they overshadow existing ones so the user has a partial fix.
Dim root = semanticModel.SyntaxTree.GetRoot
Dim optionStatement = CType(root.ChildNodes().FirstOrDefault(Function(n) n.IsKind(SyntaxKind.OptionStatement)), OptionStatementSyntax)
If optionStatement?.ValueKeyword.IsKind(SyntaxKind.OnKeyword) Then
Return True
End If
Dim options = TryCast(semanticModel.Compilation.Options, VisualBasicCompilationOptions)
If options IsNot Nothing Then
Return options.OptionStrict = OptionStrict.On
End If
Return False
End Function
Public Shared Function IsValidSymbol(symbol As ISymbol, semanticModel As SemanticModel) As Boolean
' We want to still generate a method even if this is a Namespace or NamedType symbol because unknown method calls without
' parenthesis are bound as namespaces or named types by the VB compiler.
Return symbol.Kind = SymbolKind.Namespace Or symbol.Kind = SymbolKind.NamedType Or AreSpecialOptionsActive(semanticModel)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod
Friend Class VisualBasicCommonGenerationServiceMethods
Public Shared Function AreSpecialOptionsActive(semanticModel As SemanticModel) As Boolean
' Check to see if option strict is on. if that is the case we will want to still
' generate methods even if they overshadow existing ones so the user has a partial fix.
Dim root = semanticModel.SyntaxTree.GetRoot
Dim optionStatement = CType(root.ChildNodes().FirstOrDefault(Function(n) n.IsKind(SyntaxKind.OptionStatement)), OptionStatementSyntax)
If optionStatement?.ValueKeyword.IsKind(SyntaxKind.OnKeyword) Then
Return True
End If
Dim options = TryCast(semanticModel.Compilation.Options, VisualBasicCompilationOptions)
If options IsNot Nothing Then
Return options.OptionStrict = OptionStrict.On
End If
Return False
End Function
Public Shared Function IsValidSymbol(symbol As ISymbol, semanticModel As SemanticModel) As Boolean
' We want to still generate a method even if this is a Namespace or NamedType symbol because unknown method calls without
' parenthesis are bound as namespaces or named types by the VB compiler.
Return symbol.Kind = SymbolKind.Namespace Or symbol.Kind = SymbolKind.NamedType Or AreSpecialOptionsActive(semanticModel)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/VisualBasic/Portable/AddDebuggerDisplay/VisualBasicAddDebuggerDisplayCodeRefactoringProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.AddDebuggerDisplay
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.AddDebuggerDisplay
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay), [Shared]>
Friend NotInheritable Class VisualBasicAddDebuggerDisplayCodeRefactoringProvider
Inherits AbstractAddDebuggerDisplayCodeRefactoringProvider(Of
TypeBlockSyntax, MethodStatementSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property CanNameofAccessNonPublicMembersFromAttributeArgument As Boolean
Protected Overrides Function SupportsConstantInterpolatedStrings(document As Document) As Boolean
Return False
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.AddDebuggerDisplay
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.AddDebuggerDisplay
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay), [Shared]>
Friend NotInheritable Class VisualBasicAddDebuggerDisplayCodeRefactoringProvider
Inherits AbstractAddDebuggerDisplayCodeRefactoringProvider(Of
TypeBlockSyntax, MethodStatementSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides ReadOnly Property CanNameofAccessNonPublicMembersFromAttributeArgument As Boolean
Protected Overrides Function SupportsConstantInterpolatedStrings(document As Document) As Boolean
Return False
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/FieldDeclarationStructureTests.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 FieldDeclarationStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of FieldDeclarationSyntax)
Protected Overrides ReadOnly Property WorkspaceKind As String
Get
Return CodeAnalysis.WorkspaceKind.MetadataAsSource
End Get
End Property
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New FieldDeclarationStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)>
Public Async Function NoCommentsOrAttributes() As Task
Dim code = "
Class C
Dim $$x As Integer
End Class
"
Await VerifyNoBlockSpansAsync(code)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)>
Public Async Function WithAttributes() As Task
Dim code = "
Class C
{|hint:{|textspan:<Goo>
|}Dim $$x As Integer|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("textspan", "hint", 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.
<Goo>
|}Dim $$x As Integer|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("textspan", "hint", 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 FieldDeclarationStructureProviderTests
Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of FieldDeclarationSyntax)
Protected Overrides ReadOnly Property WorkspaceKind As String
Get
Return CodeAnalysis.WorkspaceKind.MetadataAsSource
End Get
End Property
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New FieldDeclarationStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)>
Public Async Function NoCommentsOrAttributes() As Task
Dim code = "
Class C
Dim $$x As Integer
End Class
"
Await VerifyNoBlockSpansAsync(code)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)>
Public Async Function WithAttributes() As Task
Dim code = "
Class C
{|hint:{|textspan:<Goo>
|}Dim $$x As Integer|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("textspan", "hint", 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.
<Goo>
|}Dim $$x As Integer|}
End Class
"
Await VerifyBlockSpansAsync(code,
Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasic/EndConstructGeneration/AbstractEndConstructResult.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.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Friend MustInherit Class AbstractEndConstructResult
Public MustOverride Sub Apply(textView As ITextView,
subjectBuffer As ITextBuffer,
caretPosition As Integer,
smartIndentationService As ISmartIndentationService,
undoHistoryRegistry As ITextUndoHistoryRegistry,
editorOperationsFactoryService As IEditorOperationsFactoryService)
Protected Shared Sub SetIndentForFirstBlankLine(textView As ITextView, subjectBuffer As ITextBuffer, smartIndentationService As ISmartIndentationService, cursorLine As ITextSnapshotLine)
For lineNumber = cursorLine.LineNumber To subjectBuffer.CurrentSnapshot.LineCount
Dim line = subjectBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber)
If String.IsNullOrWhiteSpace(line.GetText()) Then
Dim indent = textView.GetDesiredIndentation(smartIndentationService, line)
If indent.HasValue Then
textView.TryMoveCaretToAndEnsureVisible(New VirtualSnapshotPoint(line.Start, indent.Value))
Else
textView.TryMoveCaretToAndEnsureVisible(New VirtualSnapshotPoint(line.Start, 0))
End If
Return
End If
Next
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Friend MustInherit Class AbstractEndConstructResult
Public MustOverride Sub Apply(textView As ITextView,
subjectBuffer As ITextBuffer,
caretPosition As Integer,
smartIndentationService As ISmartIndentationService,
undoHistoryRegistry As ITextUndoHistoryRegistry,
editorOperationsFactoryService As IEditorOperationsFactoryService)
Protected Shared Sub SetIndentForFirstBlankLine(textView As ITextView, subjectBuffer As ITextBuffer, smartIndentationService As ISmartIndentationService, cursorLine As ITextSnapshotLine)
For lineNumber = cursorLine.LineNumber To subjectBuffer.CurrentSnapshot.LineCount
Dim line = subjectBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber)
If String.IsNullOrWhiteSpace(line.GetText()) Then
Dim indent = textView.GetDesiredIndentation(smartIndentationService, line)
If indent.HasValue Then
textView.TryMoveCaretToAndEnsureVisible(New VirtualSnapshotPoint(line.Start, indent.Value))
Else
textView.TryMoveCaretToAndEnsureVisible(New VirtualSnapshotPoint(line.Start, 0))
End If
Return
End If
Next
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/EventDeclarationHighlighterTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class EventDeclarationHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function GetHighlighterType() As Type
Return GetType(EventDeclarationHighlighter)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestEventSample1_1() As Task
Await TestAsync(<Text>
Class C
{|Cursor:[|Public Event|]|} Goo() [|Implements|] I1.Goo
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestEventSample1_2() As Task
Await TestAsync(<Text>
Class C
[|Public Event|] Goo() {|Cursor:[|Implements|]|} I1.Goo
End Class</Text>)
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.Editor.VisualBasic.KeywordHighlighting
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting
Public Class EventDeclarationHighlighterTests
Inherits AbstractVisualBasicKeywordHighlighterTests
Friend Overrides Function GetHighlighterType() As Type
Return GetType(EventDeclarationHighlighter)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestEventSample1_1() As Task
Await TestAsync(<Text>
Class C
{|Cursor:[|Public Event|]|} Goo() [|Implements|] I1.Goo
End Class</Text>)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)>
Public Async Function TestEventSample1_2() As Task
Await TestAsync(<Text>
Class C
[|Public Event|] Goo() {|Cursor:[|Implements|]|} I1.Goo
End Class</Text>)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Binding/UsingInfo.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Holds all information needed to rewrite a bound using block node.
''' </summary>
Friend NotInheritable Class UsingInfo
''' <summary>
''' A dictionary holding a placeholder, a conversion from placeholder to IDisposable and a condition if placeholder IsNot nothing
''' per type.
''' </summary>
Public ReadOnly PlaceholderInfo As Dictionary(Of TypeSymbol, ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression))
''' <summary>
''' Syntax node for the using block.
''' </summary>
Public ReadOnly UsingStatementSyntax As UsingBlockSyntax
''' <summary>
''' Initializes a new instance of the <see cref="UsingInfo" /> class.
''' </summary>
''' <param name="usingStatementSyntax">The syntax node for the using block</param>
''' <param name="placeholderInfo">A dictionary holding a placeholder, a conversion from placeholder to IDisposable and
''' a condition if placeholder IsNot nothing per type.</param>
Public Sub New(
usingStatementSyntax As UsingBlockSyntax,
placeholderInfo As Dictionary(Of TypeSymbol, ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression))
)
Me.PlaceholderInfo = placeholderInfo
Me.UsingStatementSyntax = usingStatementSyntax
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.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Holds all information needed to rewrite a bound using block node.
''' </summary>
Friend NotInheritable Class UsingInfo
''' <summary>
''' A dictionary holding a placeholder, a conversion from placeholder to IDisposable and a condition if placeholder IsNot nothing
''' per type.
''' </summary>
Public ReadOnly PlaceholderInfo As Dictionary(Of TypeSymbol, ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression))
''' <summary>
''' Syntax node for the using block.
''' </summary>
Public ReadOnly UsingStatementSyntax As UsingBlockSyntax
''' <summary>
''' Initializes a new instance of the <see cref="UsingInfo" /> class.
''' </summary>
''' <param name="usingStatementSyntax">The syntax node for the using block</param>
''' <param name="placeholderInfo">A dictionary holding a placeholder, a conversion from placeholder to IDisposable and
''' a condition if placeholder IsNot nothing per type.</param>
Public Sub New(
usingStatementSyntax As UsingBlockSyntax,
placeholderInfo As Dictionary(Of TypeSymbol, ValueTuple(Of BoundRValuePlaceholder, BoundExpression, BoundExpression))
)
Me.PlaceholderInfo = placeholderInfo
Me.UsingStatementSyntax = usingStatementSyntax
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_INoneOperation.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.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub NoneOperation_Expression_01()
Dim source = <![CDATA[
Class C
Public Sub F(str As String)'BIND:"Public Sub F(str As String)"
Mid(str, 1, 1) = ""
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Mid(str, 1, 1) = ""')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, 1) = ""')
Children(2):
IParameterReferenceOperation: str (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str')
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, 1) = ""')
Children(4):
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.String) (Syntax: 'Mid(str, 1, 1)')
Operand:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'str')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "") (Syntax: '""')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub NoneOperation_Expression_02()
Dim source = <![CDATA[
Class C
Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)'BIND:"Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)"
Mid(str, 1, 1) = If(b, str1, str2)
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'str')
Value:
IParameterReferenceOperation: str (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, 1)')
Value:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.String) (Syntax: 'Mid(str, 1, 1)')
Operand:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'str')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'str1')
Value:
IParameterReferenceOperation: str1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'str2')
Value:
IParameterReferenceOperation: str2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Mid(str, 1, ... str1, str2)')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, ... str1, str2)')
Children(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'str')
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, ... str1, str2)')
Children(4):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Mid(str, 1, 1)')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(b, str1, str2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub NoneOperation_Expression_03()
Dim source = <![CDATA[
Class C
Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)'BIND:"Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)"
Mid(If(b, str1, str2), 1, 1) = str
End Sub
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30068: Expression is a value and therefore cannot be the target of an assignment.
Mid(If(b, str1, str2), 1, 1) = str
~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'str1')
Value:
IParameterReferenceOperation: str1 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'str1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'str2')
Value:
IParameterReferenceOperation: str2 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'str2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Mid(If(b, s ... 1, 1) = str')
Expression:
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Mid(If(b, s ... 1, 1) = str')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'If(b, str1, str2)')
Children(1):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'If(b, str1, str2)')
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Mid(If(b, s ... 1, 1) = str')
Children(4):
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.String, IsInvalid) (Syntax: 'Mid(If(b, s ... tr2), 1, 1)')
Operand:
IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'If(b, str1, str2)')
Children(0)
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IParameterReferenceOperation: str (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub NoneOperation_Expression_01()
Dim source = <![CDATA[
Class C
Public Sub F(str As String)'BIND:"Public Sub F(str As String)"
Mid(str, 1, 1) = ""
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Mid(str, 1, 1) = ""')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, 1) = ""')
Children(2):
IParameterReferenceOperation: str (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str')
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, 1) = ""')
Children(4):
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.String) (Syntax: 'Mid(str, 1, 1)')
Operand:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'str')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "") (Syntax: '""')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub NoneOperation_Expression_02()
Dim source = <![CDATA[
Class C
Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)'BIND:"Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)"
Mid(str, 1, 1) = If(b, str1, str2)
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'str')
Value:
IParameterReferenceOperation: str (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, 1)')
Value:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.String) (Syntax: 'Mid(str, 1, 1)')
Operand:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'str')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'str1')
Value:
IParameterReferenceOperation: str1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'str2')
Value:
IParameterReferenceOperation: str2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Mid(str, 1, ... str1, str2)')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, ... str1, str2)')
Children(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'str')
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'Mid(str, 1, ... str1, str2)')
Children(4):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'Mid(str, 1, 1)')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(b, str1, str2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub NoneOperation_Expression_03()
Dim source = <![CDATA[
Class C
Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)'BIND:"Public Sub F(str As String, b As Boolean, str1 As String, str2 As String)"
Mid(If(b, str1, str2), 1, 1) = str
End Sub
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30068: Expression is a value and therefore cannot be the target of an assignment.
Mid(If(b, str1, str2), 1, 1) = str
~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'str1')
Value:
IParameterReferenceOperation: str1 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'str1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'str2')
Value:
IParameterReferenceOperation: str2 (OperationKind.ParameterReference, Type: System.String, IsInvalid) (Syntax: 'str2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Mid(If(b, s ... 1, 1) = str')
Expression:
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Mid(If(b, s ... 1, 1) = str')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'If(b, str1, str2)')
Children(1):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'If(b, str1, str2)')
IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Mid(If(b, s ... 1, 1) = str')
Children(4):
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.String, IsInvalid) (Syntax: 'Mid(If(b, s ... tr2), 1, 1)')
Operand:
IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'If(b, str1, str2)')
Children(0)
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IParameterReferenceOperation: str (OperationKind.ParameterReference, Type: System.String) (Syntax: 'str')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceDelegateMethodSymbol.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.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class represent a compiler generated method of a delegate type that is based upon source delegate or event delegate declaration.
''' </summary>
Friend Class SourceDelegateMethodSymbol
Inherits SourceMethodSymbol
' Parameters.
Private _parameters As ImmutableArray(Of ParameterSymbol)
' Return type. Void for a Sub.
Private ReadOnly _returnType As TypeSymbol
Protected Sub New(delegateType As NamedTypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder,
flags As SourceMemberFlags,
returnType As TypeSymbol)
MyBase.New(delegateType, flags, binder.GetSyntaxReference(syntax), delegateType.Locations)
Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse
TypeOf syntax Is EventStatementSyntax)
Debug.Assert(returnType IsNot Nothing)
_returnType = returnType
End Sub
Protected Sub InitializeParameters(parameters As ImmutableArray(Of ParameterSymbol))
Debug.Assert(_parameters.IsDefault)
Debug.Assert(Not parameters.IsDefault)
_parameters = parameters
End Sub
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol)
Get
Return OverriddenMembersResult(Of MethodSymbol).Empty
End Get
End Property
Friend Shared Sub MakeDelegateMembers(delegateType As NamedTypeSymbol,
syntax As VisualBasicSyntaxNode,
parameterListOpt As ParameterListSyntax,
binder As Binder,
<Out> ByRef constructor As MethodSymbol,
<Out> ByRef beginInvoke As MethodSymbol,
<Out> ByRef endInvoke As MethodSymbol,
<Out> ByRef invoke As MethodSymbol,
diagnostics As BindingDiagnosticBag)
Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse
TypeOf syntax Is EventStatementSyntax)
Dim returnType As TypeSymbol = BindReturnType(syntax, binder, diagnostics)
' reuse types to avoid reporting duplicate errors if missing:
Dim voidType = binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics)
Dim iAsyncResultType = binder.GetSpecialType(SpecialType.System_IAsyncResult, syntax, diagnostics)
Dim objectType = binder.GetSpecialType(SpecialType.System_Object, syntax, diagnostics)
Dim intPtrType = binder.GetSpecialType(SpecialType.System_IntPtr, syntax, diagnostics)
Dim asyncCallbackType = binder.GetSpecialType(SpecialType.System_AsyncCallback, syntax, diagnostics)
' A delegate has the following members: (see CLI spec 13.6)
' (1) a method named Invoke with the specified signature
Dim invokeMethod = New InvokeMethod(delegateType, returnType, syntax, binder, parameterListOpt, diagnostics)
invoke = invokeMethod
' (2) a constructor with argument types (object, System.IntPtr)
constructor = New Constructor(delegateType, voidType, objectType, intPtrType, syntax, binder)
' If this is a winmd compilation we don't want to add the begin/endInvoke members to the symbol
If delegateType.IsCompilationOutputWinMdObj() Then
beginInvoke = Nothing
endInvoke = Nothing
Else
' (3) BeginInvoke
beginInvoke = New BeginInvokeMethod(invokeMethod, iAsyncResultType, objectType, asyncCallbackType, syntax, binder)
' and (4) EndInvoke methods
endInvoke = New EndInvokeMethod(invokeMethod, iAsyncResultType, syntax, binder)
End If
End Sub
Private Shared Function BindReturnType(syntax As VisualBasicSyntaxNode, binder As Binder, diagnostics As BindingDiagnosticBag) As TypeSymbol
If syntax.Kind = SyntaxKind.DelegateFunctionStatement Then
Dim delegateSyntax = DirectCast(syntax, DelegateStatementSyntax)
Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing
If binder.OptionStrict = OptionStrict.On Then
getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc
ElseIf binder.OptionStrict = OptionStrict.Custom Then
getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction
End If
Dim asClause = DirectCast(delegateSyntax.AsClause, SimpleAsClauseSyntax)
Return binder.DecodeIdentifierType(delegateSyntax.Identifier, asClause, getErrorInfo, diagnostics)
Else
Return binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics)
End If
End Function
''' <summary>
''' Returns true if this method is an extension method.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Gets a value indicating whether this instance is external method.
''' </summary>
''' <value>
''' <c>true</c> if this instance is external method; otherwise, <c>false</c>.
''' </value>
Public NotOverridable Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return True
End Get
End Property
Public NotOverridable Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return Reflection.MethodImplAttributes.Runtime
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
''' <summary>
''' Get the type parameters on this method. If the method has not generic,
''' returns an empty list.
''' </summary>
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
''' <summary>
''' Gets a value indicating whether the symbol was generated by the compiler
''' rather than declared explicitly.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return Me.MethodKind = MethodKind.Constructor
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Protected NotOverridable Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' delegate methods don't inherit attributes from the delegate type, only parameters and return types do
Return Nothing
End Function
Private NotInheritable Class Constructor
Inherits SourceDelegateMethodSymbol
Public Sub New(delegateType As NamedTypeSymbol,
voidType As TypeSymbol,
objectType As TypeSymbol,
intPtrType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(delegateType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindConstructor Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.MethodIsSub,
returnType:=voidType)
InitializeParameters(ImmutableArray.Create(Of ParameterSymbol)(
New SynthesizedParameterSymbol(Me, objectType, 0, False, StringConstants.DelegateConstructorInstanceParameterName),
New SynthesizedParameterSymbol(Me, intPtrType, 1, False, StringConstants.DelegateConstructorMethodParameterName)))
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.InstanceConstructorName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' Constructor doesn't have return type attributes
Return Nothing
End Function
End Class
Private NotInheritable Class InvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(delegateType As NamedTypeSymbol,
returnType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder,
parameterListOpt As ParameterListSyntax,
diagnostics As BindingDiagnosticBag)
MyBase.New(delegateType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindDelegateInvoke Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or
If(returnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing),
returnType:=returnType)
InitializeParameters(binder.DecodeParameterListOfDelegateDeclaration(Me, parameterListOpt, diagnostics))
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateInvokeName
End Get
End Property
End Class
Private NotInheritable Class BeginInvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(invoke As InvokeMethod,
iAsyncResultType As TypeSymbol,
objectType As TypeSymbol,
asyncCallbackType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(invoke.ContainingType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable,
returnType:=iAsyncResultType)
Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance()
Dim ordinal As Integer = 0
For Each parameter In invoke.Parameters
' Delegate parameters cannot be optional in VB.
' In error cases where the parameter is specified optional in source, the parameter
' will not have a True .IsOptional.
' This is ensured by 'CheckDelegateParameterModifier'
Debug.Assert(Not parameter.IsOptional)
parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal))
ordinal += 1
Next
parameters.Add(New SynthesizedParameterSymbol(Me, asyncCallbackType, ordinal, False, StringConstants.DelegateMethodCallbackParameterName))
ordinal += 1
parameters.Add(New SynthesizedParameterSymbol(Me, objectType, ordinal, False, StringConstants.DelegateMethodInstanceParameterName))
InitializeParameters(parameters.ToImmutableAndFree())
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateBeginInvokeName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' BeginInvoke doesn't have return type attributes
Return Nothing
End Function
End Class
Private NotInheritable Class EndInvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(invoke As InvokeMethod,
iAsyncResultType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(invoke.ContainingType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or
If(invoke.ReturnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing),
returnType:=invoke.ReturnType)
Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance()
Dim ordinal = 0
For Each parameter In invoke.Parameters
' Delegate parameters cannot be optional in VB.
' In error cases where the parameter is specified optional in source, the parameter
' will not have a True .IsOptional.
' This is ensured by 'CheckDelegateParameterModifier'
Debug.Assert(Not parameter.IsOptional)
If parameter.IsByRef Then
parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal))
ordinal += 1
End If
Next
parameters.Add(New SynthesizedParameterSymbol(Me, iAsyncResultType, parameters.Count, False, StringConstants.DelegateMethodResultParameterName))
InitializeParameters(parameters.ToImmutableAndFree())
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateEndInvokeName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' EndInvoke doesn't have return type attributes
Return Nothing
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' This class represent a compiler generated method of a delegate type that is based upon source delegate or event delegate declaration.
''' </summary>
Friend Class SourceDelegateMethodSymbol
Inherits SourceMethodSymbol
' Parameters.
Private _parameters As ImmutableArray(Of ParameterSymbol)
' Return type. Void for a Sub.
Private ReadOnly _returnType As TypeSymbol
Protected Sub New(delegateType As NamedTypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder,
flags As SourceMemberFlags,
returnType As TypeSymbol)
MyBase.New(delegateType, flags, binder.GetSyntaxReference(syntax), delegateType.Locations)
Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse
TypeOf syntax Is EventStatementSyntax)
Debug.Assert(returnType IsNot Nothing)
_returnType = returnType
End Sub
Protected Sub InitializeParameters(parameters As ImmutableArray(Of ParameterSymbol))
Debug.Assert(_parameters.IsDefault)
Debug.Assert(Not parameters.IsDefault)
_parameters = parameters
End Sub
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return _returnType
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol)
Get
Return OverriddenMembersResult(Of MethodSymbol).Empty
End Get
End Property
Friend Shared Sub MakeDelegateMembers(delegateType As NamedTypeSymbol,
syntax As VisualBasicSyntaxNode,
parameterListOpt As ParameterListSyntax,
binder As Binder,
<Out> ByRef constructor As MethodSymbol,
<Out> ByRef beginInvoke As MethodSymbol,
<Out> ByRef endInvoke As MethodSymbol,
<Out> ByRef invoke As MethodSymbol,
diagnostics As BindingDiagnosticBag)
Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse
TypeOf syntax Is EventStatementSyntax)
Dim returnType As TypeSymbol = BindReturnType(syntax, binder, diagnostics)
' reuse types to avoid reporting duplicate errors if missing:
Dim voidType = binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics)
Dim iAsyncResultType = binder.GetSpecialType(SpecialType.System_IAsyncResult, syntax, diagnostics)
Dim objectType = binder.GetSpecialType(SpecialType.System_Object, syntax, diagnostics)
Dim intPtrType = binder.GetSpecialType(SpecialType.System_IntPtr, syntax, diagnostics)
Dim asyncCallbackType = binder.GetSpecialType(SpecialType.System_AsyncCallback, syntax, diagnostics)
' A delegate has the following members: (see CLI spec 13.6)
' (1) a method named Invoke with the specified signature
Dim invokeMethod = New InvokeMethod(delegateType, returnType, syntax, binder, parameterListOpt, diagnostics)
invoke = invokeMethod
' (2) a constructor with argument types (object, System.IntPtr)
constructor = New Constructor(delegateType, voidType, objectType, intPtrType, syntax, binder)
' If this is a winmd compilation we don't want to add the begin/endInvoke members to the symbol
If delegateType.IsCompilationOutputWinMdObj() Then
beginInvoke = Nothing
endInvoke = Nothing
Else
' (3) BeginInvoke
beginInvoke = New BeginInvokeMethod(invokeMethod, iAsyncResultType, objectType, asyncCallbackType, syntax, binder)
' and (4) EndInvoke methods
endInvoke = New EndInvokeMethod(invokeMethod, iAsyncResultType, syntax, binder)
End If
End Sub
Private Shared Function BindReturnType(syntax As VisualBasicSyntaxNode, binder As Binder, diagnostics As BindingDiagnosticBag) As TypeSymbol
If syntax.Kind = SyntaxKind.DelegateFunctionStatement Then
Dim delegateSyntax = DirectCast(syntax, DelegateStatementSyntax)
Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing
If binder.OptionStrict = OptionStrict.On Then
getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc
ElseIf binder.OptionStrict = OptionStrict.Custom Then
getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction
End If
Dim asClause = DirectCast(delegateSyntax.AsClause, SimpleAsClauseSyntax)
Return binder.DecodeIdentifierType(delegateSyntax.Identifier, asClause, getErrorInfo, diagnostics)
Else
Return binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics)
End If
End Function
''' <summary>
''' Returns true if this method is an extension method.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Gets a value indicating whether this instance is external method.
''' </summary>
''' <value>
''' <c>true</c> if this instance is external method; otherwise, <c>false</c>.
''' </value>
Public NotOverridable Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return True
End Get
End Property
Public NotOverridable Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return Reflection.MethodImplAttributes.Runtime
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
''' <summary>
''' Get the type parameters on this method. If the method has not generic,
''' returns an empty list.
''' </summary>
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
''' <summary>
''' Gets a value indicating whether the symbol was generated by the compiler
''' rather than declared explicitly.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return True
End Get
End Property
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return Me.MethodKind = MethodKind.Constructor
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Protected NotOverridable Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' delegate methods don't inherit attributes from the delegate type, only parameters and return types do
Return Nothing
End Function
Private NotInheritable Class Constructor
Inherits SourceDelegateMethodSymbol
Public Sub New(delegateType As NamedTypeSymbol,
voidType As TypeSymbol,
objectType As TypeSymbol,
intPtrType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(delegateType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindConstructor Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.MethodIsSub,
returnType:=voidType)
InitializeParameters(ImmutableArray.Create(Of ParameterSymbol)(
New SynthesizedParameterSymbol(Me, objectType, 0, False, StringConstants.DelegateConstructorInstanceParameterName),
New SynthesizedParameterSymbol(Me, intPtrType, 1, False, StringConstants.DelegateConstructorMethodParameterName)))
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.InstanceConstructorName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' Constructor doesn't have return type attributes
Return Nothing
End Function
End Class
Private NotInheritable Class InvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(delegateType As NamedTypeSymbol,
returnType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder,
parameterListOpt As ParameterListSyntax,
diagnostics As BindingDiagnosticBag)
MyBase.New(delegateType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindDelegateInvoke Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or
If(returnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing),
returnType:=returnType)
InitializeParameters(binder.DecodeParameterListOfDelegateDeclaration(Me, parameterListOpt, diagnostics))
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateInvokeName
End Get
End Property
End Class
Private NotInheritable Class BeginInvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(invoke As InvokeMethod,
iAsyncResultType As TypeSymbol,
objectType As TypeSymbol,
asyncCallbackType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(invoke.ContainingType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable,
returnType:=iAsyncResultType)
Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance()
Dim ordinal As Integer = 0
For Each parameter In invoke.Parameters
' Delegate parameters cannot be optional in VB.
' In error cases where the parameter is specified optional in source, the parameter
' will not have a True .IsOptional.
' This is ensured by 'CheckDelegateParameterModifier'
Debug.Assert(Not parameter.IsOptional)
parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal))
ordinal += 1
Next
parameters.Add(New SynthesizedParameterSymbol(Me, asyncCallbackType, ordinal, False, StringConstants.DelegateMethodCallbackParameterName))
ordinal += 1
parameters.Add(New SynthesizedParameterSymbol(Me, objectType, ordinal, False, StringConstants.DelegateMethodInstanceParameterName))
InitializeParameters(parameters.ToImmutableAndFree())
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateBeginInvokeName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' BeginInvoke doesn't have return type attributes
Return Nothing
End Function
End Class
Private NotInheritable Class EndInvokeMethod
Inherits SourceDelegateMethodSymbol
Public Sub New(invoke As InvokeMethod,
iAsyncResultType As TypeSymbol,
syntax As VisualBasicSyntaxNode,
binder As Binder)
MyBase.New(invoke.ContainingType,
syntax,
binder,
flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or
If(invoke.ReturnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing),
returnType:=invoke.ReturnType)
Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance()
Dim ordinal = 0
For Each parameter In invoke.Parameters
' Delegate parameters cannot be optional in VB.
' In error cases where the parameter is specified optional in source, the parameter
' will not have a True .IsOptional.
' This is ensured by 'CheckDelegateParameterModifier'
Debug.Assert(Not parameter.IsOptional)
If parameter.IsByRef Then
parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal))
ordinal += 1
End If
Next
parameters.Add(New SynthesizedParameterSymbol(Me, iAsyncResultType, parameters.Count, False, StringConstants.DelegateMethodResultParameterName))
InitializeParameters(parameters.ToImmutableAndFree())
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return WellKnownMemberNames.DelegateEndInvokeName
End Get
End Property
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
' EndInvoke doesn't have return type attributes
Return Nothing
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/NativeIntegerTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class NativeIntegerTests
Inherits BasicTestBase
<Fact>
Public Sub TypeDefinitions_FromMetadata()
Dim source0 =
"public interface I
{
public void F1(System.IntPtr x, nint y);
public void F2(System.UIntPtr x, nuint y);
}"
Dim comp As Compilation = CreateCSharpCompilation(source0, parseOptions:=New CSharp.CSharpParseOptions(CSharp.LanguageVersion.CSharp9))
Dim ref0 = comp.EmitToImageReference()
Dim type = comp.GlobalNamespace.GetTypeMembers("I").Single()
Dim method = DirectCast(type.GetMembers("F1").Single(), IMethodSymbol)
Assert.Equal("Sub I.F1(x As System.IntPtr, y As System.IntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=True)
method = DirectCast(type.GetMembers("F2").Single(), IMethodSymbol)
Assert.Equal("Sub I.F2(x As System.UIntPtr, y As System.UIntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=True)
comp = CreateCompilation("", references:={ref0})
comp.VerifyDiagnostics()
type = comp.GlobalNamespace.GetTypeMembers("I").Single()
method = DirectCast(type.GetMembers("F1").Single(), IMethodSymbol)
Assert.Equal("Sub I.F1(x As System.IntPtr, y As System.IntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=False)
method = DirectCast(type.GetMembers("F2").Single(), IMethodSymbol)
Assert.Equal("Sub I.F2(x As System.UIntPtr, y As System.UIntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=False)
End Sub
Private Shared Sub VerifyType(type As INamedTypeSymbol, signed As Boolean, isNativeInteger As Boolean)
Assert.Equal(If(signed, SpecialType.System_IntPtr, SpecialType.System_UIntPtr), type.SpecialType)
Assert.Equal(SymbolKind.NamedType, type.Kind)
Assert.Equal(TypeKind.Struct, type.TypeKind)
Assert.Same(type, type.ConstructedFrom)
Assert.Equal(isNativeInteger, type.IsNativeIntegerType)
Dim underlyingType = type.NativeIntegerUnderlyingType
If isNativeInteger Then
Assert.NotNull(underlyingType)
VerifyType(underlyingType, signed, isNativeInteger:=False)
Else
Assert.Null(underlyingType)
End If
End Sub
<Fact>
Public Sub CreateNativeIntegerTypeSymbol()
Dim comp = VisualBasicCompilation.Create(assemblyName:=GetUniqueName(), references:=TargetFrameworkUtil.GetReferences(TargetFramework.DefaultVb), options:=TestOptions.ReleaseDll)
comp.AssertNoDiagnostics()
Assert.Throws(Of NotSupportedException)(Function() comp.CreateNativeIntegerTypeSymbol(signed:=True))
Assert.Throws(Of NotSupportedException)(Function() comp.CreateNativeIntegerTypeSymbol(signed:=False))
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.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class NativeIntegerTests
Inherits BasicTestBase
<Fact>
Public Sub TypeDefinitions_FromMetadata()
Dim source0 =
"public interface I
{
public void F1(System.IntPtr x, nint y);
public void F2(System.UIntPtr x, nuint y);
}"
Dim comp As Compilation = CreateCSharpCompilation(source0, parseOptions:=New CSharp.CSharpParseOptions(CSharp.LanguageVersion.CSharp9))
Dim ref0 = comp.EmitToImageReference()
Dim type = comp.GlobalNamespace.GetTypeMembers("I").Single()
Dim method = DirectCast(type.GetMembers("F1").Single(), IMethodSymbol)
Assert.Equal("Sub I.F1(x As System.IntPtr, y As System.IntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=True)
method = DirectCast(type.GetMembers("F2").Single(), IMethodSymbol)
Assert.Equal("Sub I.F2(x As System.UIntPtr, y As System.UIntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=True)
comp = CreateCompilation("", references:={ref0})
comp.VerifyDiagnostics()
type = comp.GlobalNamespace.GetTypeMembers("I").Single()
method = DirectCast(type.GetMembers("F1").Single(), IMethodSymbol)
Assert.Equal("Sub I.F1(x As System.IntPtr, y As System.IntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=True, isNativeInteger:=False)
method = DirectCast(type.GetMembers("F2").Single(), IMethodSymbol)
Assert.Equal("Sub I.F2(x As System.UIntPtr, y As System.UIntPtr)", SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat))
VerifyType(DirectCast(method.Parameters(0).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=False)
VerifyType(DirectCast(method.Parameters(1).Type, INamedTypeSymbol), signed:=False, isNativeInteger:=False)
End Sub
Private Shared Sub VerifyType(type As INamedTypeSymbol, signed As Boolean, isNativeInteger As Boolean)
Assert.Equal(If(signed, SpecialType.System_IntPtr, SpecialType.System_UIntPtr), type.SpecialType)
Assert.Equal(SymbolKind.NamedType, type.Kind)
Assert.Equal(TypeKind.Struct, type.TypeKind)
Assert.Same(type, type.ConstructedFrom)
Assert.Equal(isNativeInteger, type.IsNativeIntegerType)
Dim underlyingType = type.NativeIntegerUnderlyingType
If isNativeInteger Then
Assert.NotNull(underlyingType)
VerifyType(underlyingType, signed, isNativeInteger:=False)
Else
Assert.Null(underlyingType)
End If
End Sub
<Fact>
Public Sub CreateNativeIntegerTypeSymbol()
Dim comp = VisualBasicCompilation.Create(assemblyName:=GetUniqueName(), references:=TargetFrameworkUtil.GetReferences(TargetFramework.DefaultVb), options:=TestOptions.ReleaseDll)
comp.AssertNoDiagnostics()
Assert.Throws(Of NotSupportedException)(Function() comp.CreateNativeIntegerTypeSymbol(signed:=True))
Assert.Throws(Of NotSupportedException)(Function() comp.CreateNativeIntegerTypeSymbol(signed:=False))
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/SelectBlockHighlighter.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 SelectBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If node.IsIncorrectExitStatement(SyntaxKind.ExitSelectStatement) Then
Return
End If
Dim selectBlock = node.GetAncestor(Of SelectBlockSyntax)()
If selectBlock Is Nothing Then
Return
End If
With selectBlock
With .SelectStatement
highlights.Add(
TextSpan.FromBounds(
.SelectKeyword.SpanStart,
If(.CaseKeyword.Kind <> SyntaxKind.None, .CaseKeyword, .SelectKeyword).Span.End))
End With
For Each caseBlock In .CaseBlocks
With caseBlock.CaseStatement
If caseBlock.Kind = SyntaxKind.CaseElseBlock Then
Dim elseKeyword = DirectCast(.Cases.First(), ElseCaseClauseSyntax).ElseKeyword
highlights.Add(TextSpan.FromBounds(.CaseKeyword.SpanStart, elseKeyword.Span.End))
Else
highlights.Add(.CaseKeyword.Span)
End If
End With
highlights.AddRange(
caseBlock.GetRelatedStatementHighlights(
blockKind:=SyntaxKind.SelectKeyword))
Next
highlights.Add(.EndSelectStatement.Span)
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 SelectBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If node.IsIncorrectExitStatement(SyntaxKind.ExitSelectStatement) Then
Return
End If
Dim selectBlock = node.GetAncestor(Of SelectBlockSyntax)()
If selectBlock Is Nothing Then
Return
End If
With selectBlock
With .SelectStatement
highlights.Add(
TextSpan.FromBounds(
.SelectKeyword.SpanStart,
If(.CaseKeyword.Kind <> SyntaxKind.None, .CaseKeyword, .SelectKeyword).Span.End))
End With
For Each caseBlock In .CaseBlocks
With caseBlock.CaseStatement
If caseBlock.Kind = SyntaxKind.CaseElseBlock Then
Dim elseKeyword = DirectCast(.Cases.First(), ElseCaseClauseSyntax).ElseKeyword
highlights.Add(TextSpan.FromBounds(.CaseKeyword.SpanStart, elseKeyword.Span.End))
Else
highlights.Add(.CaseKeyword.Span)
End If
End With
highlights.AddRange(
caseBlock.GetRelatedStatementHighlights(
blockKind:=SyntaxKind.SelectKeyword))
Next
highlights.Add(.EndSelectStatement.Span)
End With
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Symbols/NamespaceExtent.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A NamespaceExtent represents whether a namespace contains types and sub-namespaces from a particular module,
''' assembly, or merged across all modules (source and metadata) in a particular compilation.
''' </summary>
Partial Friend Structure NamespaceExtent
Private ReadOnly _kind As NamespaceKind
Private ReadOnly _symbolOrCompilation As Object
''' <summary>
''' Returns what kind of extent: Module, Assembly, or Compilation.
''' </summary>
Public ReadOnly Property Kind As NamespaceKind
Get
Return _kind
End Get
End Property
''' <summary>
''' If the Kind is ExtendKind.Module, returns the module symbol that this namespace
''' encompasses. Otherwise throws InvalidOperationException.
''' </summary>
Public ReadOnly Property [Module] As ModuleSymbol
Get
If Kind = NamespaceKind.Module Then
Return DirectCast(_symbolOrCompilation, ModuleSymbol)
Else
Throw New InvalidOperationException()
End If
End Get
End Property
''' <summary>
''' If the Kind is ExtendKind.Assembly, returns the assembly symbol that this namespace
''' encompasses. Otherwise throws InvalidOperationException.
''' </summary>
Public ReadOnly Property Assembly As AssemblySymbol
Get
If Kind = NamespaceKind.Assembly Then
Return DirectCast(_symbolOrCompilation, AssemblySymbol)
Else
Throw New InvalidOperationException()
End If
End Get
End Property
''' <summary>
''' If the Kind is ExtendKind.Compilation, returns the compilation symbol that this namespace
''' encompasses. Otherwise throws InvalidOperationException.
''' </summary>
Public ReadOnly Property Compilation As VisualBasicCompilation
Get
If Kind = NamespaceKind.Compilation Then
Return DirectCast(_symbolOrCompilation, VisualBasicCompilation)
Else
Throw New InvalidOperationException()
End If
End Get
End Property
Public Overrides Function ToString() As String
Return String.Format("{0}: {1}", Kind.ToString(), _symbolOrCompilation.ToString())
End Function
''' <summary>
''' Create a NamespaceExtent that represents a given ModuleSymbol.
''' </summary>
Friend Sub New([module] As ModuleSymbol)
_kind = NamespaceKind.Module
_symbolOrCompilation = [module]
End Sub
''' <summary>
''' Create a NamespaceExtent that represents a given AssemblySymbol.
''' </summary>
Friend Sub New(assembly As AssemblySymbol)
_kind = NamespaceKind.Assembly
_symbolOrCompilation = assembly
End Sub
''' <summary>
''' Create a NamespaceExtent that represents a given Compilation.
''' </summary>
Friend Sub New(compilation As VisualBasicCompilation)
_kind = NamespaceKind.Compilation
_symbolOrCompilation = compilation
End Sub
#If DEBUG Then
Shared Sub New()
' Below is a set of compile time asserts, they break build if violated.
' Assert(NamespaceKind.Compilation <> NamespaceKindNamespaceGroup)
Const assert1 As Integer = 1 Mod (NamespaceKind.Compilation - NamespaceKindNamespaceGroup)
' Assert(NamespaceKind.Assembly <> NamespaceKindNamespaceGroup)
Const assert2 As Integer = 1 Mod (NamespaceKind.Assembly - NamespaceKindNamespaceGroup)
' Assert(NamespaceKind.Module <> NamespaceKindNamespaceGroup)
Const assert3 As Integer = 1 Mod (NamespaceKind.Module - NamespaceKindNamespaceGroup)
Dim dummy = assert1 + assert2 + assert3
End Sub
#End If
End Structure
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A NamespaceExtent represents whether a namespace contains types and sub-namespaces from a particular module,
''' assembly, or merged across all modules (source and metadata) in a particular compilation.
''' </summary>
Partial Friend Structure NamespaceExtent
Private ReadOnly _kind As NamespaceKind
Private ReadOnly _symbolOrCompilation As Object
''' <summary>
''' Returns what kind of extent: Module, Assembly, or Compilation.
''' </summary>
Public ReadOnly Property Kind As NamespaceKind
Get
Return _kind
End Get
End Property
''' <summary>
''' If the Kind is ExtendKind.Module, returns the module symbol that this namespace
''' encompasses. Otherwise throws InvalidOperationException.
''' </summary>
Public ReadOnly Property [Module] As ModuleSymbol
Get
If Kind = NamespaceKind.Module Then
Return DirectCast(_symbolOrCompilation, ModuleSymbol)
Else
Throw New InvalidOperationException()
End If
End Get
End Property
''' <summary>
''' If the Kind is ExtendKind.Assembly, returns the assembly symbol that this namespace
''' encompasses. Otherwise throws InvalidOperationException.
''' </summary>
Public ReadOnly Property Assembly As AssemblySymbol
Get
If Kind = NamespaceKind.Assembly Then
Return DirectCast(_symbolOrCompilation, AssemblySymbol)
Else
Throw New InvalidOperationException()
End If
End Get
End Property
''' <summary>
''' If the Kind is ExtendKind.Compilation, returns the compilation symbol that this namespace
''' encompasses. Otherwise throws InvalidOperationException.
''' </summary>
Public ReadOnly Property Compilation As VisualBasicCompilation
Get
If Kind = NamespaceKind.Compilation Then
Return DirectCast(_symbolOrCompilation, VisualBasicCompilation)
Else
Throw New InvalidOperationException()
End If
End Get
End Property
Public Overrides Function ToString() As String
Return String.Format("{0}: {1}", Kind.ToString(), _symbolOrCompilation.ToString())
End Function
''' <summary>
''' Create a NamespaceExtent that represents a given ModuleSymbol.
''' </summary>
Friend Sub New([module] As ModuleSymbol)
_kind = NamespaceKind.Module
_symbolOrCompilation = [module]
End Sub
''' <summary>
''' Create a NamespaceExtent that represents a given AssemblySymbol.
''' </summary>
Friend Sub New(assembly As AssemblySymbol)
_kind = NamespaceKind.Assembly
_symbolOrCompilation = assembly
End Sub
''' <summary>
''' Create a NamespaceExtent that represents a given Compilation.
''' </summary>
Friend Sub New(compilation As VisualBasicCompilation)
_kind = NamespaceKind.Compilation
_symbolOrCompilation = compilation
End Sub
#If DEBUG Then
Shared Sub New()
' Below is a set of compile time asserts, they break build if violated.
' Assert(NamespaceKind.Compilation <> NamespaceKindNamespaceGroup)
Const assert1 As Integer = 1 Mod (NamespaceKind.Compilation - NamespaceKindNamespaceGroup)
' Assert(NamespaceKind.Assembly <> NamespaceKindNamespaceGroup)
Const assert2 As Integer = 1 Mod (NamespaceKind.Assembly - NamespaceKindNamespaceGroup)
' Assert(NamespaceKind.Module <> NamespaceKindNamespaceGroup)
Const assert3 As Integer = 1 Mod (NamespaceKind.Module - NamespaceKindNamespaceGroup)
Dim dummy = assert1 + assert2 + assert3
End Sub
#End If
End Structure
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasicTest/Diagnostics/ConvertToAsync/ConvertToAsyncTests.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.VisualBasic.CodeFixes.ConvertToAsync
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.ConvertToAsync
Public Class ConvertToAsyncTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New VisualBasicConvertToAsyncFunctionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToAsync)>
Public Async Function CantAwaitAsyncSub1() As Task
Dim initial =
<ModuleDeclaration>
Async Function rtrt() As Task
[|Await gt()|]
End Function
Async Sub gt()
End Sub
</ModuleDeclaration>
Dim expected =
<ModuleDeclaration>
Async Function rtrt() As Task
Await gt()
End Function
Async Function gt() As Task
End Function
</ModuleDeclaration>
Await TestAsync(initial, 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.VisualBasic.CodeFixes.ConvertToAsync
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.ConvertToAsync
Public Class ConvertToAsyncTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New VisualBasicConvertToAsyncFunctionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsChangeToAsync)>
Public Async Function CantAwaitAsyncSub1() As Task
Dim initial =
<ModuleDeclaration>
Async Function rtrt() As Task
[|Await gt()|]
End Function
Async Sub gt()
End Sub
</ModuleDeclaration>
Dim expected =
<ModuleDeclaration>
Async Function rtrt() As Task
Await gt()
End Function
Async Function gt() As Task
End Function
</ModuleDeclaration>
Await TestAsync(initial, expected)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/OptionStatements/CompareBinaryTextRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.OptionStatements
''' <summary>
''' Recommends the "Binary" and "Text" options that come after "Option Compare"
''' </summary>
Friend Class CompareBinaryTextRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(
New RecommendedKeyword("Binary", VBFeaturesResources.Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order),
New RecommendedKeyword("Text", VBFeaturesResources.Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Return If(context.TargetToken.IsKind(SyntaxKind.CompareKeyword), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.OptionStatements
''' <summary>
''' Recommends the "Binary" and "Text" options that come after "Option Compare"
''' </summary>
Friend Class CompareBinaryTextRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(
New RecommendedKeyword("Binary", VBFeaturesResources.Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order),
New RecommendedKeyword("Text", VBFeaturesResources.Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, CancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Return If(context.TargetToken.IsKind(SyntaxKind.CompareKeyword), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWinMdEvents.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
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenWinMdEvents
Inherits BasicTestBase
<Fact()>
Public Sub MissingReferences_SynthesizedAccessors()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_AddHandler()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
AddHandler E, Nothing
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
' 1 for the AddHandler statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_RemoveHandler()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
RemoveHandler E, Nothing
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
' 1 for the RemoveHandler statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_RaiseEvent()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
RaiseEvent E()
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
' 1 for the RaiseEvent statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_RaiseEvent_MissingAccessor()
Dim source =
<compilation>
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
RaiseEvent E()
End Sub
End Class
Namespace System.Runtime.InteropServices.WindowsRuntime
Public Structure EventRegistrationToken
End Structure
Public Class EventRegistrationTokenTable(Of T)
Public Shared Function GetOrCreateEventRegistrationTokenTable(ByRef table As EventRegistrationTokenTable(Of T)) As EventRegistrationTokenTable(Of T)
Return table
End Function
Public WriteOnly Property InvocationList as T
Set (value As T)
End Set
End Property
Public Function AddEventHandler(handler as T) as EventRegistrationToken
Return Nothing
End Function
Public Sub RemoveEventHandler(token as EventRegistrationToken)
End Sub
End Class
End Namespace
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 1 for the RaiseEvent statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "RaiseEvent E()").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.get_InvocationList"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact>
Public Sub MissingReferences_HandlesClause()
Dim source =
<compilation name="test">
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate()
Class Test
WithEvents T As Test
Public Event E As EventDelegate
Sub Handler() Handles Me.E, T.E
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' This test is specifically interested in the ERR_MissingRuntimeHelper errors: one for each helper times one for each handled event
comp.VerifyDiagnostics(
Diagnostic(ERRID.WRN_UndefinedOrEmptyNamespaceOrClass1, "System.Runtime.InteropServices.WindowsRuntime").WithArguments("System.Runtime.InteropServices.WindowsRuntime"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "test.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "test.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "test.winmdobj"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.AddEventHandler"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.RemoveEventHandler"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.AddEventHandler"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.RemoveEventHandler"),
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Runtime.InteropServices.WindowsRuntime"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub InstanceFieldLikeEventAccessors()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Event E As System.Action
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("C.add_E", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0006: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000b: ldarg.1
IL_000c: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).AddEventHandler(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0011: ret
}
]]>)
verifier.VerifyIL("C.remove_E", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0006: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000b: ldarg.1
IL_000c: callvirt "Sub System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).RemoveEventHandler(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub SharedFieldLikeEventAccessors()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Event E As System.Action
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("C.add_E", <![CDATA[
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldsflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0005: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000a: ldarg.0
IL_000b: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).AddEventHandler(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0010: ret
}
]]>)
verifier.VerifyIL("C.remove_E", <![CDATA[
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldsflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0005: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000a: ldarg.0
IL_000b: callvirt "Sub System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).RemoveEventHandler(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0010: ret
}
]]>)
End Sub
<Fact()>
Public Sub AddAndRemoveHandlerStatements()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Public Event InstanceEvent As System.Action
Public Shared Event SharedEvent As System.Action
End Class
Class D
Private c1 as C
Sub InstanceAdd()
AddHandler c1.InstanceEvent, AddressOf Action
End Sub
Sub InstanceRemove()
RemoveHandler c1.InstanceEvent, AddressOf Action
End Sub
Sub SharedAdd()
AddHandler C.SharedEvent, AddressOf Action
End Sub
Sub SharedRemove()
RemoveHandler C.SharedEvent, AddressOf Action
End Sub
Shared Sub Action()
End Sub
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("D.InstanceAdd", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C V_0)
IL_0000: ldarg.0
IL_0001: ldfld "D.c1 As C"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldftn "Sub C.add_InstanceEvent(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000e: newobj "Sub System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0013: ldloc.0
IL_0014: ldftn "Sub C.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_001a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001f: ldnull
IL_0020: ldftn "Sub D.Action()"
IL_0026: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_002b: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of System.Action)(System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_0030: ret
}
]]>)
verifier.VerifyIL("D.InstanceRemove", <![CDATA[
{
// Code size 35 (0x23)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldfld "D.c1 As C"
IL_0006: ldftn "Sub C.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_000c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0011: ldnull
IL_0012: ldftn "Sub D.Action()"
IL_0018: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_001d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of System.Action)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_0022: ret
}
]]>)
verifier.VerifyIL("D.SharedAdd", <![CDATA[
{
// Code size 42 (0x2a)
.maxstack 4
IL_0000: ldnull
IL_0001: ldftn "Sub C.add_SharedEvent(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0007: newobj "Sub System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000c: ldnull
IL_000d: ldftn "Sub C.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0013: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0018: ldnull
IL_0019: ldftn "Sub D.Action()"
IL_001f: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_0024: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of System.Action)(System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_0029: ret
}
]]>)
verifier.VerifyIL("D.SharedRemove", <![CDATA[
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldnull
IL_0001: ldftn "Sub C.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0007: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000c: ldnull
IL_000d: ldftn "Sub D.Action()"
IL_0013: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_0018: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of System.Action)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_001d: ret
}
]]>)
End Sub
<Fact()>
Public Sub [RaiseEvent]()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Public Event InstanceEvent As System.Action(Of Integer)
Public Shared Event SharedEvent As System.Action(Of Integer)
Sub InstanceRaise()
RaiseEvent InstanceEvent(1)
End Sub
Sub SharedRaise()
RaiseEvent SharedEvent(2)
End Sub
Shared Sub Action()
End Sub
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("C.InstanceRaise", <![CDATA[
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (System.Action(Of Integer) V_0)
IL_0000: ldarg.0
IL_0001: ldflda "C.InstanceEventEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_0006: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_000b: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).get_InvocationList() As System.Action(Of Integer)"
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: brfalse.s IL_001b
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: callvirt "Sub System.Action(Of Integer).Invoke(Integer)"
IL_001b: ret
}
]]>)
verifier.VerifyIL("C.SharedRaise", <![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (System.Action(Of Integer) V_0)
IL_0000: ldsflda "C.SharedEventEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_0005: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_000a: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).get_InvocationList() As System.Action(Of Integer)"
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: brfalse.s IL_001a
IL_0013: ldloc.0
IL_0014: ldc.i4.2
IL_0015: callvirt "Sub System.Action(Of Integer).Invoke(Integer)"
IL_001a: ret
}
]]>)
End Sub
''' <summary>
''' Dev11 had bugs in this area (e.g. 281866, 298564), but Roslyn shouldn't be affected.
''' </summary>
''' <remarks>
''' I'm assuming this is why the final dev11 impl uses GetOrCreateEventRegistrationTokenTable.
''' </remarks>
<WorkItem(1003209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003209")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.WinRTNeedsWindowsDesktop)>
Public Sub FieldLikeEventSerialization()
Dim source1 =
<compilation>
<file name="a.vb">
Namespace EventDeserialization
Public Delegate Sub EventDelegate
Public Interface IEvent
Event E as EventDelegate
End Interface
End Namespace
</file>
</compilation>
Dim source2 =
<compilation>
<file name="b.vb">
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Namespace EventDeserialization
Module MainPage
Public Sub Main()
Dim m1 as new Model()
AddHandler m1.E, Sub() Console.Write("A")
m1.Invoke()
Dim bytes = Serialize(m1)
Dim m2 as Model = Deserialize(bytes)
Console.WriteLine(m1 is m2)
m2.Invoke()
AddHandler m2.E, Sub() Console.Write("B")
m2.Invoke()
End Sub
Function Serialize(m as Model) as Byte()
Dim ser as new DataContractSerializer(GetType(Model))
Using stream = new MemoryStream()
ser.WriteObject(stream, m)
Return stream.ToArray()
End Using
End Function
Function Deserialize(b as Byte()) As Model
Dim ser as new DataContractSerializer(GetType(Model))
Using stream = new MemoryStream(b)
Return DirectCast(ser.ReadObject(stream), Model)
End Using
End Function
End Module
<DataContract>
Public NotInheritable Class Model
Implements IEvent
Public Event E as EventDelegate Implements IEvent.E
Public Sub Invoke()
RaiseEvent E()
Console.WriteLine()
End Sub
End Class
End Namespace
</file>
</compilation>
Dim comp1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs, options:=TestOptions.ReleaseWinMD)
comp1.VerifyDiagnostics()
Dim serializationRef = TestMetadata.Net451.SystemRuntimeSerialization
Dim comp2 = CreateEmptyCompilationWithReferences(source2, WinRtRefs.Concat({New VisualBasicCompilationReference(comp1), serializationRef, MsvbRef, SystemXmlRef}), options:=TestOptions.ReleaseExe)
CompileAndVerify(comp2, expectedOutput:=<![CDATA[
A
False
B
]]>)
End Sub
' Receiver can be MyBase, MyClass, Me, or the name of a WithEvents member (instance or shared).
<Fact>
Public Sub HandlesClauses_ReceiverKinds()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate()
Class Base
Public Event InstanceEvent As EventDelegate
Public Shared Event SharedEvent As EventDelegate
End Class
Class Derived
Inherits Base
WithEvents B As Base
Shared WithEvents BX As Base
Public Shadows Event InstanceEvent As EventDelegate
Public Shadows Shared Event SharedEvent As EventDelegate
Sub InstanceHandler() Handles _
MyBase.InstanceEvent,
MyBase.SharedEvent,
MyClass.InstanceEvent,
MyClass.SharedEvent,
Me.InstanceEvent,
Me.SharedEvent,
B.InstanceEvent,
B.SharedEvent
End Sub
Shared Sub SharedHandler() Handles _
MyBase.InstanceEvent,
MyBase.SharedEvent,
MyClass.InstanceEvent,
MyClass.SharedEvent,
Me.InstanceEvent,
Me.SharedEvent,
B.InstanceEvent,
B.SharedEvent,
BX.InstanceEvent,
BX.SharedEvent
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
Dim verifier = CompileAndVerify(comp)
' Attach Me.InstanceHandler to {Base/Derived/Derived}.{InstanceEvent/SharedEvent} (from {MyBase/MyClass/Me}.{InstanceEvent/SharedEvent}).
' Attach Derived.SharedHandler to {Base/Derived/Derived}.InstanceEvent (from {MyBase/MyClass/Me}.InstanceEvent).
verifier.VerifyIL("Derived..ctor", <![CDATA[
{
// Code size 376 (0x178)
.maxstack 4
IL_0000: ldarg.0
IL_0001: call "Sub Base..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0012: ldarg.0
IL_0013: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0019: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001e: ldarg.0
IL_001f: ldftn "Sub Derived.InstanceHandler()"
IL_0025: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_002a: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_002f: ldnull
IL_0030: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0036: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003b: ldnull
IL_003c: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0042: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0047: ldarg.0
IL_0048: ldftn "Sub Derived.InstanceHandler()"
IL_004e: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0058: ldarg.0
IL_0059: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_005f: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0064: ldarg.0
IL_0065: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_006b: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0070: ldarg.0
IL_0071: ldftn "Sub Derived.InstanceHandler()"
IL_0077: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_007c: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0081: ldnull
IL_0082: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0088: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_008d: ldnull
IL_008e: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0094: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0099: ldarg.0
IL_009a: ldftn "Sub Derived.InstanceHandler()"
IL_00a0: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_00a5: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00aa: ldarg.0
IL_00ab: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00b1: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00b6: ldarg.0
IL_00b7: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00bd: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00c2: ldarg.0
IL_00c3: ldftn "Sub Derived.InstanceHandler()"
IL_00c9: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_00ce: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00d3: ldnull
IL_00d4: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00da: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00df: ldnull
IL_00e0: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00e6: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00eb: ldarg.0
IL_00ec: ldftn "Sub Derived.InstanceHandler()"
IL_00f2: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_00f7: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00fc: ldarg.0
IL_00fd: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0103: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0108: ldarg.0
IL_0109: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_010f: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0114: ldnull
IL_0115: ldftn "Sub Derived.SharedHandler()"
IL_011b: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0120: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0125: ldarg.0
IL_0126: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_012c: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0131: ldarg.0
IL_0132: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0138: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_013d: ldnull
IL_013e: ldftn "Sub Derived.SharedHandler()"
IL_0144: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0149: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_014e: ldarg.0
IL_014f: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0155: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_015a: ldarg.0
IL_015b: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0161: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0166: ldnull
IL_0167: ldftn "Sub Derived.SharedHandler()"
IL_016d: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0172: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0177: ret
}
]]>)
' Attach Derived.SharedHandler to from {Base/Derived/Derived}.SharedEvent (from {MyBase/MyClass/Me}.SharedEvent).
verifier.VerifyIL("Derived..cctor", <![CDATA[
{
// Code size 124 (0x7c)
.maxstack 4
IL_0000: ldnull
IL_0001: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0007: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000c: ldnull
IL_000d: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0013: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0018: ldnull
IL_0019: ldftn "Sub Derived.SharedHandler()"
IL_001f: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0024: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0029: ldnull
IL_002a: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0030: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0035: ldnull
IL_0036: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0041: ldnull
IL_0042: ldftn "Sub Derived.SharedHandler()"
IL_0048: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_004d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0052: ldnull
IL_0053: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0059: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_005e: ldnull
IL_005f: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0065: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_006a: ldnull
IL_006b: ldftn "Sub Derived.SharedHandler()"
IL_0071: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0076: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_007b: ret
}
]]>)
' Wire up Me.InstanceHandler to Me.B.InstanceEvent and Base.SharedEvent.
' Wire up Derived.SharedHandler to Me.B.InstanceEvent and Base.SharedEvent.
verifier.VerifyIL("Derived.put_B", <![CDATA[
{
// Code size 282 (0x11a)
.maxstack 3
.locals init (EventDelegate V_0,
EventDelegate V_1,
EventDelegate V_2,
EventDelegate V_3,
Base V_4)
IL_0000: ldarg.0
IL_0001: ldftn "Sub Derived.InstanceHandler()"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub Derived.InstanceHandler()"
IL_0014: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldnull
IL_001b: ldftn "Sub Derived.SharedHandler()"
IL_0021: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0026: stloc.2
IL_0027: ldnull
IL_0028: ldftn "Sub Derived.SharedHandler()"
IL_002e: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0033: stloc.3
IL_0034: ldarg.0
IL_0035: ldfld "Derived._B As Base"
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: brfalse.s IL_008a
IL_0040: ldloc.s V_4
IL_0042: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0048: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_004d: ldloc.0
IL_004e: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0053: ldnull
IL_0054: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_005a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_005f: ldloc.1
IL_0060: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0065: ldloc.s V_4
IL_0067: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_006d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0072: ldloc.2
IL_0073: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0078: ldnull
IL_0079: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_007f: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0084: ldloc.3
IL_0085: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_008a: ldarg.0
IL_008b: ldarg.1
IL_008c: stfld "Derived._B As Base"
IL_0091: ldarg.0
IL_0092: ldfld "Derived._B As Base"
IL_0097: stloc.s V_4
IL_0099: ldloc.s V_4
IL_009b: brfalse.s IL_0119
IL_009d: ldloc.s V_4
IL_009f: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00a5: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00aa: ldloc.s V_4
IL_00ac: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00b2: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00b7: ldloc.0
IL_00b8: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00bd: ldnull
IL_00be: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00c4: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00c9: ldnull
IL_00ca: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00d0: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00d5: ldloc.1
IL_00d6: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00db: ldloc.s V_4
IL_00dd: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00e3: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00e8: ldloc.s V_4
IL_00ea: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00f0: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00f5: ldloc.2
IL_00f6: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00fb: ldnull
IL_00fc: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0102: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0107: ldnull
IL_0108: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_010e: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0113: ldloc.3
IL_0114: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0119: ret
}
]]>)
' Wire up Derived.SharedHandler to Derived.BX.InstanceEvent and Base.SharedEvent.
verifier.VerifyIL("Derived.put_BX", <![CDATA[
{
// Code size 147 (0x93)
.maxstack 3
.locals init (EventDelegate V_0,
EventDelegate V_1,
Base V_2)
IL_0000: ldnull
IL_0001: ldftn "Sub Derived.SharedHandler()"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldnull
IL_000e: ldftn "Sub Derived.SharedHandler()"
IL_0014: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldsfld "Derived._BX As Base"
IL_001f: stloc.2
IL_0020: ldloc.2
IL_0021: brfalse.s IL_0047
IL_0023: ldloc.2
IL_0024: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_002a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_002f: ldloc.0
IL_0030: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0035: ldnull
IL_0036: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0041: ldloc.1
IL_0042: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0047: ldarg.0
IL_0048: stsfld "Derived._BX As Base"
IL_004d: ldsfld "Derived._BX As Base"
IL_0052: stloc.2
IL_0053: ldloc.2
IL_0054: brfalse.s IL_0092
IL_0056: ldloc.2
IL_0057: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_005d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0062: ldloc.2
IL_0063: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0069: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_006e: ldloc.0
IL_006f: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0074: ldnull
IL_0075: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_007b: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0080: ldnull
IL_0081: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0087: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_008c: ldloc.1
IL_008d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0092: ret
}
]]>)
End Sub
<Fact(), WorkItem(6313, "https://github.com/dotnet/roslyn/issues/6313")>
Public Sub CustomEventWinMd()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Class Test
Public Custom Event CustomEvent As System.Action(Of Integer)
AddHandler(value As System.Action(Of Integer))
Return Nothing
End AddHandler
RemoveHandler(value As EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.DebugWinMD)
Dim verifier = CompileAndVerify(comp)
End Sub
' Field-like and custom events are not treated differently.
<Fact(), WorkItem(1003209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003209")>
Public Sub HandlesClauses_EventKinds()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate()
Class Test
WithEvents T As Test
Public Event FieldLikeEvent As EventDelegate
Public Custom Event CustomEvent As EventDelegate
AddHandler(value As EventDelegate)
Return Nothing
End AddHandler
RemoveHandler(value As EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Sub Handler() Handles _
Me.FieldLikeEvent,
Me.CustomEvent,
T.FieldLikeEvent,
T.CustomEvent
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
Dim verifier = CompileAndVerify(comp)
verifier.VerifyIL("Test..ctor", <![CDATA[
{
// Code size 89 (0x59)
.maxstack 4
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Test.add_FieldLikeEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0012: ldarg.0
IL_0013: ldftn "Sub Test.remove_FieldLikeEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0019: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001e: ldarg.0
IL_001f: ldftn "Sub Test.Handler()"
IL_0025: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_002a: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_002f: ldarg.0
IL_0030: ldftn "Sub Test.add_CustomEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0036: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003b: ldarg.0
IL_003c: ldftn "Sub Test.remove_CustomEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0042: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0047: ldarg.0
IL_0048: ldftn "Sub Test.Handler()"
IL_004e: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0058: ret
}
]]>)
verifier.VerifyIL("Test.put_T", <![CDATA[
{
// Code size 150 (0x96)
.maxstack 3
.locals init (EventDelegate V_0,
EventDelegate V_1,
Test V_2)
IL_0000: ldarg.0
IL_0001: ldftn "Sub Test.Handler()"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub Test.Handler()"
IL_0014: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldarg.0
IL_001b: ldfld "Test._T As Test"
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: brfalse.s IL_0048
IL_0024: ldloc.2
IL_0025: ldftn "Sub Test.remove_FieldLikeEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_002b: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0030: ldloc.0
IL_0031: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0036: ldloc.2
IL_0037: ldftn "Sub Test.remove_CustomEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0042: ldloc.1
IL_0043: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0048: ldarg.0
IL_0049: ldarg.1
IL_004a: stfld "Test._T As Test"
IL_004f: ldarg.0
IL_0050: ldfld "Test._T As Test"
IL_0055: stloc.2
IL_0056: ldloc.2
IL_0057: brfalse.s IL_0095
IL_0059: ldloc.2
IL_005a: ldftn "Sub Test.add_FieldLikeEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0060: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0065: ldloc.2
IL_0066: ldftn "Sub Test.remove_FieldLikeEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_006c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0071: ldloc.0
IL_0072: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0077: ldloc.2
IL_0078: ldftn "Sub Test.add_CustomEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_007e: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0083: ldloc.2
IL_0084: ldftn "Sub Test.remove_CustomEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_008a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_008f: ldloc.1
IL_0090: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0095: ret
}
]]>)
End Sub
' The handler is allowed to have zero arguments (event if using AddHandler would be illegal).
<Fact>
Public Sub HandlesClauses_ZeroArgumentHandler()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate(x as Integer)
Class Test
WithEvents T As Test
Public Event E As EventDelegate
Sub Handler() Handles Me.E, T.E
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
Dim verifier = CompileAndVerify(comp)
' Note: actually attaching a lambda.
verifier.VerifyIL("Test..ctor", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 4
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Test.add_E(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0012: ldarg.0
IL_0013: ldftn "Sub Test.remove_E(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0019: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001e: ldarg.0
IL_001f: ldftn "Sub Test._Lambda$__R0-1(Integer)"
IL_0025: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_002a: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_002f: ret
}
]]>)
' Note: actually attaching a lambda.
verifier.VerifyIL("Test.put_T", <![CDATA[
{
// Code size 89 (0x59)
.maxstack 3
.locals init (EventDelegate V_0,
Test V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub Test._Lambda$__R3-2(Integer)"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "Test._T As Test"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: brfalse.s IL_0029
IL_0017: ldloc.1
IL_0018: ldftn "Sub Test.remove_E(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_001e: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0023: ldloc.0
IL_0024: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0029: ldarg.0
IL_002a: ldarg.1
IL_002b: stfld "Test._T As Test"
IL_0030: ldarg.0
IL_0031: ldfld "Test._T As Test"
IL_0036: stloc.1
IL_0037: ldloc.1
IL_0038: brfalse.s IL_0058
IL_003a: ldloc.1
IL_003b: ldftn "Sub Test.add_E(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0041: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0046: ldloc.1
IL_0047: ldftn "Sub Test.remove_E(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_004d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0052: ldloc.0
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0058: ret
}
]]>)
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.VisualBasic
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenWinMdEvents
Inherits BasicTestBase
<Fact()>
Public Sub MissingReferences_SynthesizedAccessors()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_AddHandler()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
AddHandler E, Nothing
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
' 1 for the AddHandler statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_RemoveHandler()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
RemoveHandler E, Nothing
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
' 1 for the RemoveHandler statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_RaiseEvent()
Dim source =
<compilation name="MissingReferences">
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
RaiseEvent E()
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 3 for the backing field and each accessor.
' 1 for the RaiseEvent statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "MissingReferences.winmdobj"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub MissingReferences_RaiseEvent_MissingAccessor()
Dim source =
<compilation>
<file name="a.vb">
Class C
Event E As System.Action
Sub Test()
RaiseEvent E()
End Sub
End Class
Namespace System.Runtime.InteropServices.WindowsRuntime
Public Structure EventRegistrationToken
End Structure
Public Class EventRegistrationTokenTable(Of T)
Public Shared Function GetOrCreateEventRegistrationTokenTable(ByRef table As EventRegistrationTokenTable(Of T)) As EventRegistrationTokenTable(Of T)
Return table
End Function
Public WriteOnly Property InvocationList as T
Set (value As T)
End Set
End Property
Public Function AddEventHandler(handler as T) as EventRegistrationToken
Return Nothing
End Function
Public Sub RemoveEventHandler(token as EventRegistrationToken)
End Sub
End Class
End Namespace
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' 1 for the RaiseEvent statement
comp.VerifyEmitDiagnostics(
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "RaiseEvent E()").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.get_InvocationList"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact>
Public Sub MissingReferences_HandlesClause()
Dim source =
<compilation name="test">
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate()
Class Test
WithEvents T As Test
Public Event E As EventDelegate
Sub Handler() Handles Me.E, T.E
End Sub
End Class
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.WindowsRuntimeMetadata)
' This test is specifically interested in the ERR_MissingRuntimeHelper errors: one for each helper times one for each handled event
comp.VerifyDiagnostics(
Diagnostic(ERRID.WRN_UndefinedOrEmptyNamespaceOrClass1, "System.Runtime.InteropServices.WindowsRuntime").WithArguments("System.Runtime.InteropServices.WindowsRuntime"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of )", "test.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "test.winmdobj"),
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", "test.winmdobj"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.AddEventHandler"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.RemoveEventHandler"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.AddEventHandler"),
Diagnostic(ERRID.ERR_MissingRuntimeHelper, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable`1.RemoveEventHandler"),
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Runtime.InteropServices.WindowsRuntime"))
' Throws *test* exception, but does not assert or throw produce exception.
Assert.Throws(Of EmitException)(Sub() CompileAndVerify(comp))
End Sub
<Fact()>
Public Sub InstanceFieldLikeEventAccessors()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Event E As System.Action
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("C.add_E", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0006: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000b: ldarg.1
IL_000c: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).AddEventHandler(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0011: ret
}
]]>)
verifier.VerifyIL("C.remove_E", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0006: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000b: ldarg.1
IL_000c: callvirt "Sub System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).RemoveEventHandler(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub SharedFieldLikeEventAccessors()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Shared Event E As System.Action
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("C.add_E", <![CDATA[
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldsflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0005: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000a: ldarg.0
IL_000b: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).AddEventHandler(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0010: ret
}
]]>)
verifier.VerifyIL("C.remove_E", <![CDATA[
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldsflda "C.EEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_0005: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action)"
IL_000a: ldarg.0
IL_000b: callvirt "Sub System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action).RemoveEventHandler(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0010: ret
}
]]>)
End Sub
<Fact()>
Public Sub AddAndRemoveHandlerStatements()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Public Event InstanceEvent As System.Action
Public Shared Event SharedEvent As System.Action
End Class
Class D
Private c1 as C
Sub InstanceAdd()
AddHandler c1.InstanceEvent, AddressOf Action
End Sub
Sub InstanceRemove()
RemoveHandler c1.InstanceEvent, AddressOf Action
End Sub
Sub SharedAdd()
AddHandler C.SharedEvent, AddressOf Action
End Sub
Sub SharedRemove()
RemoveHandler C.SharedEvent, AddressOf Action
End Sub
Shared Sub Action()
End Sub
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("D.InstanceAdd", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C V_0)
IL_0000: ldarg.0
IL_0001: ldfld "D.c1 As C"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldftn "Sub C.add_InstanceEvent(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000e: newobj "Sub System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0013: ldloc.0
IL_0014: ldftn "Sub C.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_001a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001f: ldnull
IL_0020: ldftn "Sub D.Action()"
IL_0026: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_002b: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of System.Action)(System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_0030: ret
}
]]>)
verifier.VerifyIL("D.InstanceRemove", <![CDATA[
{
// Code size 35 (0x23)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldfld "D.c1 As C"
IL_0006: ldftn "Sub C.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_000c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0011: ldnull
IL_0012: ldftn "Sub D.Action()"
IL_0018: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_001d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of System.Action)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_0022: ret
}
]]>)
verifier.VerifyIL("D.SharedAdd", <![CDATA[
{
// Code size 42 (0x2a)
.maxstack 4
IL_0000: ldnull
IL_0001: ldftn "Sub C.add_SharedEvent(System.Action) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0007: newobj "Sub System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000c: ldnull
IL_000d: ldftn "Sub C.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0013: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0018: ldnull
IL_0019: ldftn "Sub D.Action()"
IL_001f: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_0024: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of System.Action)(System.Func(Of System.Action, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_0029: ret
}
]]>)
verifier.VerifyIL("D.SharedRemove", <![CDATA[
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldnull
IL_0001: ldftn "Sub C.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0007: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000c: ldnull
IL_000d: ldftn "Sub D.Action()"
IL_0013: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_0018: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of System.Action)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action)"
IL_001d: ret
}
]]>)
End Sub
<Fact()>
Public Sub [RaiseEvent]()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Class C
Public Event InstanceEvent As System.Action(Of Integer)
Public Shared Event SharedEvent As System.Action(Of Integer)
Sub InstanceRaise()
RaiseEvent InstanceEvent(1)
End Sub
Sub SharedRaise()
RaiseEvent SharedEvent(2)
End Sub
Shared Sub Action()
End Sub
End Class
</file>
</compilation>, WinRtRefs, options:=TestOptions.ReleaseWinMD)
verifier.VerifyIL("C.InstanceRaise", <![CDATA[
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (System.Action(Of Integer) V_0)
IL_0000: ldarg.0
IL_0001: ldflda "C.InstanceEventEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_0006: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_000b: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).get_InvocationList() As System.Action(Of Integer)"
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: brfalse.s IL_001b
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: callvirt "Sub System.Action(Of Integer).Invoke(Integer)"
IL_001b: ret
}
]]>)
verifier.VerifyIL("C.SharedRaise", <![CDATA[
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (System.Action(Of Integer) V_0)
IL_0000: ldsflda "C.SharedEventEvent As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_0005: call "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).GetOrCreateEventRegistrationTokenTable(ByRef System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer))"
IL_000a: callvirt "Function System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of System.Action(Of Integer)).get_InvocationList() As System.Action(Of Integer)"
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: brfalse.s IL_001a
IL_0013: ldloc.0
IL_0014: ldc.i4.2
IL_0015: callvirt "Sub System.Action(Of Integer).Invoke(Integer)"
IL_001a: ret
}
]]>)
End Sub
''' <summary>
''' Dev11 had bugs in this area (e.g. 281866, 298564), but Roslyn shouldn't be affected.
''' </summary>
''' <remarks>
''' I'm assuming this is why the final dev11 impl uses GetOrCreateEventRegistrationTokenTable.
''' </remarks>
<WorkItem(1003209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003209")>
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:=ConditionalSkipReason.WinRTNeedsWindowsDesktop)>
Public Sub FieldLikeEventSerialization()
Dim source1 =
<compilation>
<file name="a.vb">
Namespace EventDeserialization
Public Delegate Sub EventDelegate
Public Interface IEvent
Event E as EventDelegate
End Interface
End Namespace
</file>
</compilation>
Dim source2 =
<compilation>
<file name="b.vb">
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Namespace EventDeserialization
Module MainPage
Public Sub Main()
Dim m1 as new Model()
AddHandler m1.E, Sub() Console.Write("A")
m1.Invoke()
Dim bytes = Serialize(m1)
Dim m2 as Model = Deserialize(bytes)
Console.WriteLine(m1 is m2)
m2.Invoke()
AddHandler m2.E, Sub() Console.Write("B")
m2.Invoke()
End Sub
Function Serialize(m as Model) as Byte()
Dim ser as new DataContractSerializer(GetType(Model))
Using stream = new MemoryStream()
ser.WriteObject(stream, m)
Return stream.ToArray()
End Using
End Function
Function Deserialize(b as Byte()) As Model
Dim ser as new DataContractSerializer(GetType(Model))
Using stream = new MemoryStream(b)
Return DirectCast(ser.ReadObject(stream), Model)
End Using
End Function
End Module
<DataContract>
Public NotInheritable Class Model
Implements IEvent
Public Event E as EventDelegate Implements IEvent.E
Public Sub Invoke()
RaiseEvent E()
Console.WriteLine()
End Sub
End Class
End Namespace
</file>
</compilation>
Dim comp1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs, options:=TestOptions.ReleaseWinMD)
comp1.VerifyDiagnostics()
Dim serializationRef = TestMetadata.Net451.SystemRuntimeSerialization
Dim comp2 = CreateEmptyCompilationWithReferences(source2, WinRtRefs.Concat({New VisualBasicCompilationReference(comp1), serializationRef, MsvbRef, SystemXmlRef}), options:=TestOptions.ReleaseExe)
CompileAndVerify(comp2, expectedOutput:=<![CDATA[
A
False
B
]]>)
End Sub
' Receiver can be MyBase, MyClass, Me, or the name of a WithEvents member (instance or shared).
<Fact>
Public Sub HandlesClauses_ReceiverKinds()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate()
Class Base
Public Event InstanceEvent As EventDelegate
Public Shared Event SharedEvent As EventDelegate
End Class
Class Derived
Inherits Base
WithEvents B As Base
Shared WithEvents BX As Base
Public Shadows Event InstanceEvent As EventDelegate
Public Shadows Shared Event SharedEvent As EventDelegate
Sub InstanceHandler() Handles _
MyBase.InstanceEvent,
MyBase.SharedEvent,
MyClass.InstanceEvent,
MyClass.SharedEvent,
Me.InstanceEvent,
Me.SharedEvent,
B.InstanceEvent,
B.SharedEvent
End Sub
Shared Sub SharedHandler() Handles _
MyBase.InstanceEvent,
MyBase.SharedEvent,
MyClass.InstanceEvent,
MyClass.SharedEvent,
Me.InstanceEvent,
Me.SharedEvent,
B.InstanceEvent,
B.SharedEvent,
BX.InstanceEvent,
BX.SharedEvent
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
Dim verifier = CompileAndVerify(comp)
' Attach Me.InstanceHandler to {Base/Derived/Derived}.{InstanceEvent/SharedEvent} (from {MyBase/MyClass/Me}.{InstanceEvent/SharedEvent}).
' Attach Derived.SharedHandler to {Base/Derived/Derived}.InstanceEvent (from {MyBase/MyClass/Me}.InstanceEvent).
verifier.VerifyIL("Derived..ctor", <![CDATA[
{
// Code size 376 (0x178)
.maxstack 4
IL_0000: ldarg.0
IL_0001: call "Sub Base..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0012: ldarg.0
IL_0013: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0019: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001e: ldarg.0
IL_001f: ldftn "Sub Derived.InstanceHandler()"
IL_0025: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_002a: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_002f: ldnull
IL_0030: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0036: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003b: ldnull
IL_003c: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0042: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0047: ldarg.0
IL_0048: ldftn "Sub Derived.InstanceHandler()"
IL_004e: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0058: ldarg.0
IL_0059: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_005f: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0064: ldarg.0
IL_0065: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_006b: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0070: ldarg.0
IL_0071: ldftn "Sub Derived.InstanceHandler()"
IL_0077: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_007c: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0081: ldnull
IL_0082: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0088: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_008d: ldnull
IL_008e: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0094: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0099: ldarg.0
IL_009a: ldftn "Sub Derived.InstanceHandler()"
IL_00a0: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_00a5: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00aa: ldarg.0
IL_00ab: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00b1: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00b6: ldarg.0
IL_00b7: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00bd: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00c2: ldarg.0
IL_00c3: ldftn "Sub Derived.InstanceHandler()"
IL_00c9: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_00ce: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00d3: ldnull
IL_00d4: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00da: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00df: ldnull
IL_00e0: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00e6: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00eb: ldarg.0
IL_00ec: ldftn "Sub Derived.InstanceHandler()"
IL_00f2: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_00f7: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00fc: ldarg.0
IL_00fd: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0103: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0108: ldarg.0
IL_0109: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_010f: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0114: ldnull
IL_0115: ldftn "Sub Derived.SharedHandler()"
IL_011b: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0120: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0125: ldarg.0
IL_0126: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_012c: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0131: ldarg.0
IL_0132: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0138: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_013d: ldnull
IL_013e: ldftn "Sub Derived.SharedHandler()"
IL_0144: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0149: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_014e: ldarg.0
IL_014f: ldftn "Sub Derived.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0155: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_015a: ldarg.0
IL_015b: ldftn "Sub Derived.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0161: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0166: ldnull
IL_0167: ldftn "Sub Derived.SharedHandler()"
IL_016d: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0172: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0177: ret
}
]]>)
' Attach Derived.SharedHandler to from {Base/Derived/Derived}.SharedEvent (from {MyBase/MyClass/Me}.SharedEvent).
verifier.VerifyIL("Derived..cctor", <![CDATA[
{
// Code size 124 (0x7c)
.maxstack 4
IL_0000: ldnull
IL_0001: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0007: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_000c: ldnull
IL_000d: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0013: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0018: ldnull
IL_0019: ldftn "Sub Derived.SharedHandler()"
IL_001f: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0024: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0029: ldnull
IL_002a: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0030: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0035: ldnull
IL_0036: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0041: ldnull
IL_0042: ldftn "Sub Derived.SharedHandler()"
IL_0048: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_004d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0052: ldnull
IL_0053: ldftn "Sub Derived.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0059: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_005e: ldnull
IL_005f: ldftn "Sub Derived.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0065: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_006a: ldnull
IL_006b: ldftn "Sub Derived.SharedHandler()"
IL_0071: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0076: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_007b: ret
}
]]>)
' Wire up Me.InstanceHandler to Me.B.InstanceEvent and Base.SharedEvent.
' Wire up Derived.SharedHandler to Me.B.InstanceEvent and Base.SharedEvent.
verifier.VerifyIL("Derived.put_B", <![CDATA[
{
// Code size 282 (0x11a)
.maxstack 3
.locals init (EventDelegate V_0,
EventDelegate V_1,
EventDelegate V_2,
EventDelegate V_3,
Base V_4)
IL_0000: ldarg.0
IL_0001: ldftn "Sub Derived.InstanceHandler()"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub Derived.InstanceHandler()"
IL_0014: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldnull
IL_001b: ldftn "Sub Derived.SharedHandler()"
IL_0021: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0026: stloc.2
IL_0027: ldnull
IL_0028: ldftn "Sub Derived.SharedHandler()"
IL_002e: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0033: stloc.3
IL_0034: ldarg.0
IL_0035: ldfld "Derived._B As Base"
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: brfalse.s IL_008a
IL_0040: ldloc.s V_4
IL_0042: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0048: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_004d: ldloc.0
IL_004e: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0053: ldnull
IL_0054: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_005a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_005f: ldloc.1
IL_0060: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0065: ldloc.s V_4
IL_0067: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_006d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0072: ldloc.2
IL_0073: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0078: ldnull
IL_0079: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_007f: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0084: ldloc.3
IL_0085: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_008a: ldarg.0
IL_008b: ldarg.1
IL_008c: stfld "Derived._B As Base"
IL_0091: ldarg.0
IL_0092: ldfld "Derived._B As Base"
IL_0097: stloc.s V_4
IL_0099: ldloc.s V_4
IL_009b: brfalse.s IL_0119
IL_009d: ldloc.s V_4
IL_009f: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00a5: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00aa: ldloc.s V_4
IL_00ac: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00b2: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00b7: ldloc.0
IL_00b8: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00bd: ldnull
IL_00be: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00c4: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00c9: ldnull
IL_00ca: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00d0: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00d5: ldloc.1
IL_00d6: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00db: ldloc.s V_4
IL_00dd: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_00e3: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00e8: ldloc.s V_4
IL_00ea: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_00f0: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_00f5: ldloc.2
IL_00f6: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_00fb: ldnull
IL_00fc: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0102: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0107: ldnull
IL_0108: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_010e: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0113: ldloc.3
IL_0114: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0119: ret
}
]]>)
' Wire up Derived.SharedHandler to Derived.BX.InstanceEvent and Base.SharedEvent.
verifier.VerifyIL("Derived.put_BX", <![CDATA[
{
// Code size 147 (0x93)
.maxstack 3
.locals init (EventDelegate V_0,
EventDelegate V_1,
Base V_2)
IL_0000: ldnull
IL_0001: ldftn "Sub Derived.SharedHandler()"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldnull
IL_000e: ldftn "Sub Derived.SharedHandler()"
IL_0014: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldsfld "Derived._BX As Base"
IL_001f: stloc.2
IL_0020: ldloc.2
IL_0021: brfalse.s IL_0047
IL_0023: ldloc.2
IL_0024: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_002a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_002f: ldloc.0
IL_0030: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0035: ldnull
IL_0036: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0041: ldloc.1
IL_0042: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0047: ldarg.0
IL_0048: stsfld "Derived._BX As Base"
IL_004d: ldsfld "Derived._BX As Base"
IL_0052: stloc.2
IL_0053: ldloc.2
IL_0054: brfalse.s IL_0092
IL_0056: ldloc.2
IL_0057: ldftn "Sub Base.add_InstanceEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_005d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0062: ldloc.2
IL_0063: ldftn "Sub Base.remove_InstanceEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0069: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_006e: ldloc.0
IL_006f: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0074: ldnull
IL_0075: ldftn "Sub Base.add_SharedEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_007b: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0080: ldnull
IL_0081: ldftn "Sub Base.remove_SharedEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0087: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_008c: ldloc.1
IL_008d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0092: ret
}
]]>)
End Sub
<Fact(), WorkItem(6313, "https://github.com/dotnet/roslyn/issues/6313")>
Public Sub CustomEventWinMd()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Class Test
Public Custom Event CustomEvent As System.Action(Of Integer)
AddHandler(value As System.Action(Of Integer))
Return Nothing
End AddHandler
RemoveHandler(value As EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.DebugWinMD)
Dim verifier = CompileAndVerify(comp)
End Sub
' Field-like and custom events are not treated differently.
<Fact(), WorkItem(1003209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003209")>
Public Sub HandlesClauses_EventKinds()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate()
Class Test
WithEvents T As Test
Public Event FieldLikeEvent As EventDelegate
Public Custom Event CustomEvent As EventDelegate
AddHandler(value As EventDelegate)
Return Nothing
End AddHandler
RemoveHandler(value As EventRegistrationToken)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Sub Handler() Handles _
Me.FieldLikeEvent,
Me.CustomEvent,
T.FieldLikeEvent,
T.CustomEvent
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
Dim verifier = CompileAndVerify(comp)
verifier.VerifyIL("Test..ctor", <![CDATA[
{
// Code size 89 (0x59)
.maxstack 4
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Test.add_FieldLikeEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0012: ldarg.0
IL_0013: ldftn "Sub Test.remove_FieldLikeEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0019: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001e: ldarg.0
IL_001f: ldftn "Sub Test.Handler()"
IL_0025: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_002a: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_002f: ldarg.0
IL_0030: ldftn "Sub Test.add_CustomEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0036: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_003b: ldarg.0
IL_003c: ldftn "Sub Test.remove_CustomEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0042: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0047: ldarg.0
IL_0048: ldftn "Sub Test.Handler()"
IL_004e: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0058: ret
}
]]>)
verifier.VerifyIL("Test.put_T", <![CDATA[
{
// Code size 150 (0x96)
.maxstack 3
.locals init (EventDelegate V_0,
EventDelegate V_1,
Test V_2)
IL_0000: ldarg.0
IL_0001: ldftn "Sub Test.Handler()"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub Test.Handler()"
IL_0014: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldarg.0
IL_001b: ldfld "Test._T As Test"
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: brfalse.s IL_0048
IL_0024: ldloc.2
IL_0025: ldftn "Sub Test.remove_FieldLikeEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_002b: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0030: ldloc.0
IL_0031: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0036: ldloc.2
IL_0037: ldftn "Sub Test.remove_CustomEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_003d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0042: ldloc.1
IL_0043: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0048: ldarg.0
IL_0049: ldarg.1
IL_004a: stfld "Test._T As Test"
IL_004f: ldarg.0
IL_0050: ldfld "Test._T As Test"
IL_0055: stloc.2
IL_0056: ldloc.2
IL_0057: brfalse.s IL_0095
IL_0059: ldloc.2
IL_005a: ldftn "Sub Test.add_FieldLikeEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0060: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0065: ldloc.2
IL_0066: ldftn "Sub Test.remove_FieldLikeEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_006c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0071: ldloc.0
IL_0072: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0077: ldloc.2
IL_0078: ldftn "Sub Test.add_CustomEvent(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_007e: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0083: ldloc.2
IL_0084: ldftn "Sub Test.remove_CustomEvent(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_008a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_008f: ldloc.1
IL_0090: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0095: ret
}
]]>)
End Sub
' The handler is allowed to have zero arguments (event if using AddHandler would be illegal).
<Fact>
Public Sub HandlesClauses_ZeroArgumentHandler()
Dim source =
<compilation>
<file name="a.vb">
Imports System.Runtime.InteropServices.WindowsRuntime
Delegate Sub EventDelegate(x as Integer)
Class Test
WithEvents T As Test
Public Event E As EventDelegate
Sub Handler() Handles Me.E, T.E
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD)
Dim verifier = CompileAndVerify(comp)
' Note: actually attaching a lambda.
verifier.VerifyIL("Test..ctor", <![CDATA[
{
// Code size 48 (0x30)
.maxstack 4
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Test.add_E(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_000d: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0012: ldarg.0
IL_0013: ldftn "Sub Test.remove_E(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_0019: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_001e: ldarg.0
IL_001f: ldftn "Sub Test._Lambda$__R0-1(Integer)"
IL_0025: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_002a: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_002f: ret
}
]]>)
' Note: actually attaching a lambda.
verifier.VerifyIL("Test.put_T", <![CDATA[
{
// Code size 89 (0x59)
.maxstack 3
.locals init (EventDelegate V_0,
Test V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub Test._Lambda$__R3-2(Integer)"
IL_0007: newobj "Sub EventDelegate..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "Test._T As Test"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: brfalse.s IL_0029
IL_0017: ldloc.1
IL_0018: ldftn "Sub Test.remove_E(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_001e: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0023: ldloc.0
IL_0024: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0029: ldarg.0
IL_002a: ldarg.1
IL_002b: stfld "Test._T As Test"
IL_0030: ldarg.0
IL_0031: ldfld "Test._T As Test"
IL_0036: stloc.1
IL_0037: ldloc.1
IL_0038: brfalse.s IL_0058
IL_003a: ldloc.1
IL_003b: ldftn "Sub Test.add_E(EventDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"
IL_0041: newobj "Sub System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0046: ldloc.1
IL_0047: ldftn "Sub Test.remove_E(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"
IL_004d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)"
IL_0052: ldloc.0
IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventDelegate)(System.Func(Of EventDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventDelegate)"
IL_0058: ret
}
]]>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasicTest/LineCommit/CommitTestData.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Indentation
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit
Friend Class CommitTestData
Implements IDisposable
Public ReadOnly Buffer As ITextBuffer
Public ReadOnly CommandHandler As CommitCommandHandler
Public ReadOnly EditorOperations As IEditorOperations
Public ReadOnly Workspace As TestWorkspace
Public ReadOnly View As ITextView
Public ReadOnly UndoHistory As ITextUndoHistory
Private ReadOnly _formatter As FormatterMock
Private ReadOnly _inlineRenameService As InlineRenameServiceMock
Public Shared Function Create(test As XElement) As CommitTestData
Dim workspace = TestWorkspace.Create(test, composition:=EditorTestCompositions.EditorFeaturesWpf)
Return New CommitTestData(workspace)
End Function
Public Sub New(workspace As TestWorkspace)
Me.Workspace = workspace
View = workspace.Documents.Single().GetTextView()
EditorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(View)
Dim position = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
View.Caret.MoveTo(New SnapshotPoint(View.TextSnapshot, position))
Buffer = workspace.Documents.Single().GetTextBuffer()
' HACK: We may have already created a CommitBufferManager for the buffer, so remove it
If Buffer.Properties.ContainsProperty(GetType(CommitBufferManager)) Then
Dim oldManager = Buffer.Properties.GetProperty(Of CommitBufferManager)(GetType(CommitBufferManager))
oldManager.RemoveReferencingView()
Buffer.Properties.RemoveProperty(GetType(CommitBufferManager))
End If
Dim textUndoHistoryRegistry = workspace.GetService(Of ITextUndoHistoryRegistry)()
UndoHistory = textUndoHistoryRegistry.GetHistory(View.TextBuffer)
_formatter = New FormatterMock(workspace)
_inlineRenameService = New InlineRenameServiceMock()
Dim commitManagerFactory As New CommitBufferManagerFactory(_formatter, _inlineRenameService, workspace.GetService(Of IThreadingContext))
' Make sure the manager exists for the buffer
Dim commitManager = commitManagerFactory.CreateForBuffer(Buffer)
commitManager.AddReferencingView()
CommandHandler = New CommitCommandHandler(
commitManagerFactory,
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of ISmartIndentationService),
textUndoHistoryRegistry)
End Sub
Friend Sub AssertHadCommit(expectCommit As Boolean)
Assert.Equal(expectCommit, _formatter.GotCommit)
End Sub
Friend Sub AssertUsedSemantics(expected As Boolean)
Assert.Equal(expected, _formatter.UsedSemantics)
End Sub
Friend Sub StartInlineRenameSession()
_inlineRenameService.HasSession = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Workspace.Dispose()
End Sub
Private Class InlineRenameServiceMock
Implements IInlineRenameService
Public Property HasSession As Boolean
Public ReadOnly Property ActiveSession As IInlineRenameSession Implements IInlineRenameService.ActiveSession
Get
Return If(HasSession, New MockInlineRenameSession(), Nothing)
End Get
End Property
Public Function StartInlineSession(snapshot As Document, triggerSpan As TextSpan, Optional cancellationToken As CancellationToken = Nothing) As InlineRenameSessionInfo Implements IInlineRenameService.StartInlineSession
Throw New NotImplementedException()
End Function
Private Class MockInlineRenameSession
Implements IInlineRenameSession
Public Sub Cancel() Implements IInlineRenameSession.Cancel
Throw New NotImplementedException()
End Sub
Public Sub Commit(Optional previewChanges As Boolean = False) Implements IInlineRenameSession.Commit
Throw New NotImplementedException()
End Sub
End Class
End Class
Private Class FormatterMock
Implements ICommitFormatter
Private ReadOnly _testWorkspace As TestWorkspace
Public Property GotCommit As Boolean
Public Property UsedSemantics As Boolean
Public Sub New(testWorkspace As TestWorkspace)
_testWorkspace = testWorkspace
End Sub
Public Sub CommitRegion(spanToFormat As SnapshotSpan,
isExplicitFormat As Boolean,
useSemantics As Boolean,
dirtyRegion As SnapshotSpan,
baseSnapshot As ITextSnapshot,
baseTree As SyntaxTree,
cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion
GotCommit = True
UsedSemantics = useSemantics
' Assert the span if we have an assertion
If _testWorkspace.Documents.Any(Function(d) d.SelectedSpans.Any()) Then
Dim expectedSpan = _testWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Single()
Dim trackingSpan = _testWorkspace.Documents.Single().InitialTextSnapshot.CreateTrackingSpan(expectedSpan.ToSpan(), SpanTrackingMode.EdgeInclusive)
Assert.Equal(trackingSpan.GetSpan(spanToFormat.Snapshot), spanToFormat.Span)
End If
Dim realCommitFormatter = Assert.IsType(Of CommitFormatter)(_testWorkspace.GetService(Of ICommitFormatter)())
realCommitFormatter.CommitRegion(spanToFormat, isExplicitFormat, useSemantics, dirtyRegion, baseSnapshot, baseTree, cancellationToken)
End Sub
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.Threading
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Imports Microsoft.CodeAnalysis.Indentation
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit
Friend Class CommitTestData
Implements IDisposable
Public ReadOnly Buffer As ITextBuffer
Public ReadOnly CommandHandler As CommitCommandHandler
Public ReadOnly EditorOperations As IEditorOperations
Public ReadOnly Workspace As TestWorkspace
Public ReadOnly View As ITextView
Public ReadOnly UndoHistory As ITextUndoHistory
Private ReadOnly _formatter As FormatterMock
Private ReadOnly _inlineRenameService As InlineRenameServiceMock
Public Shared Function Create(test As XElement) As CommitTestData
Dim workspace = TestWorkspace.Create(test, composition:=EditorTestCompositions.EditorFeaturesWpf)
Return New CommitTestData(workspace)
End Function
Public Sub New(workspace As TestWorkspace)
Me.Workspace = workspace
View = workspace.Documents.Single().GetTextView()
EditorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(View)
Dim position = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value
View.Caret.MoveTo(New SnapshotPoint(View.TextSnapshot, position))
Buffer = workspace.Documents.Single().GetTextBuffer()
' HACK: We may have already created a CommitBufferManager for the buffer, so remove it
If Buffer.Properties.ContainsProperty(GetType(CommitBufferManager)) Then
Dim oldManager = Buffer.Properties.GetProperty(Of CommitBufferManager)(GetType(CommitBufferManager))
oldManager.RemoveReferencingView()
Buffer.Properties.RemoveProperty(GetType(CommitBufferManager))
End If
Dim textUndoHistoryRegistry = workspace.GetService(Of ITextUndoHistoryRegistry)()
UndoHistory = textUndoHistoryRegistry.GetHistory(View.TextBuffer)
_formatter = New FormatterMock(workspace)
_inlineRenameService = New InlineRenameServiceMock()
Dim commitManagerFactory As New CommitBufferManagerFactory(_formatter, _inlineRenameService, workspace.GetService(Of IThreadingContext))
' Make sure the manager exists for the buffer
Dim commitManager = commitManagerFactory.CreateForBuffer(Buffer)
commitManager.AddReferencingView()
CommandHandler = New CommitCommandHandler(
commitManagerFactory,
workspace.GetService(Of IEditorOperationsFactoryService),
workspace.GetService(Of ISmartIndentationService),
textUndoHistoryRegistry)
End Sub
Friend Sub AssertHadCommit(expectCommit As Boolean)
Assert.Equal(expectCommit, _formatter.GotCommit)
End Sub
Friend Sub AssertUsedSemantics(expected As Boolean)
Assert.Equal(expected, _formatter.UsedSemantics)
End Sub
Friend Sub StartInlineRenameSession()
_inlineRenameService.HasSession = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Workspace.Dispose()
End Sub
Private Class InlineRenameServiceMock
Implements IInlineRenameService
Public Property HasSession As Boolean
Public ReadOnly Property ActiveSession As IInlineRenameSession Implements IInlineRenameService.ActiveSession
Get
Return If(HasSession, New MockInlineRenameSession(), Nothing)
End Get
End Property
Public Function StartInlineSession(snapshot As Document, triggerSpan As TextSpan, Optional cancellationToken As CancellationToken = Nothing) As InlineRenameSessionInfo Implements IInlineRenameService.StartInlineSession
Throw New NotImplementedException()
End Function
Private Class MockInlineRenameSession
Implements IInlineRenameSession
Public Sub Cancel() Implements IInlineRenameSession.Cancel
Throw New NotImplementedException()
End Sub
Public Sub Commit(Optional previewChanges As Boolean = False) Implements IInlineRenameSession.Commit
Throw New NotImplementedException()
End Sub
End Class
End Class
Private Class FormatterMock
Implements ICommitFormatter
Private ReadOnly _testWorkspace As TestWorkspace
Public Property GotCommit As Boolean
Public Property UsedSemantics As Boolean
Public Sub New(testWorkspace As TestWorkspace)
_testWorkspace = testWorkspace
End Sub
Public Sub CommitRegion(spanToFormat As SnapshotSpan,
isExplicitFormat As Boolean,
useSemantics As Boolean,
dirtyRegion As SnapshotSpan,
baseSnapshot As ITextSnapshot,
baseTree As SyntaxTree,
cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion
GotCommit = True
UsedSemantics = useSemantics
' Assert the span if we have an assertion
If _testWorkspace.Documents.Any(Function(d) d.SelectedSpans.Any()) Then
Dim expectedSpan = _testWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Single()
Dim trackingSpan = _testWorkspace.Documents.Single().InitialTextSnapshot.CreateTrackingSpan(expectedSpan.ToSpan(), SpanTrackingMode.EdgeInclusive)
Assert.Equal(trackingSpan.GetSpan(spanToFormat.Snapshot), spanToFormat.Span)
End If
Dim realCommitFormatter = Assert.IsType(Of CommitFormatter)(_testWorkspace.GetService(Of ICommitFormatter)())
realCommitFormatter.CommitRegion(spanToFormat, isExplicitFormat, useSemantics, dirtyRegion, baseSnapshot, baseTree, cancellationToken)
End Sub
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Differencing
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue
Friend NotInheritable Class VisualBasicEditAndContinueAnalyzer
Inherits AbstractEditAndContinueAnalyzer
<ExportLanguageServiceFactory(GetType(IEditAndContinueAnalyzer), LanguageNames.VisualBasic), [Shared]>
Private NotInheritable Class Factory
Implements ILanguageServiceFactory
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
Return New VisualBasicEditAndContinueAnalyzer(testFaultInjector:=Nothing)
End Function
End Class
' Public for testing purposes
Public Sub New(Optional testFaultInjector As Action(Of SyntaxNode) = Nothing)
MyBase.New(testFaultInjector)
End Sub
#Region "Syntax Analysis"
Friend Overrides Function TryFindMemberDeclaration(rootOpt As SyntaxNode, node As SyntaxNode, <Out> ByRef declarations As OneOrMany(Of SyntaxNode)) As Boolean
Dim current = node
While current IsNot rootOpt
Select Case current.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
declarations = OneOrMany.Create(current)
Return True
Case SyntaxKind.PropertyStatement
' Property a As Integer = 1
' Property a As New T
If Not current.Parent.IsKind(SyntaxKind.PropertyBlock) Then
declarations = OneOrMany.Create(current)
Return True
End If
Case SyntaxKind.VariableDeclarator
If current.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Dim variableDeclarator = CType(current, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count = 1 Then
declarations = OneOrMany.Create(current)
Else
declarations = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) CType(n, SyntaxNode)))
End If
Return True
End If
Case SyntaxKind.ModifiedIdentifier
If current.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
declarations = OneOrMany.Create(current)
Return True
End If
End Select
current = current.Parent
End While
declarations = Nothing
Return False
End Function
''' <summary>
''' Returns true if the <see cref="ModifiedIdentifierSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As ModifiedIdentifierSyntax) As Boolean
Return node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
''' <summary>
''' Returns true if the <see cref="VariableDeclaratorSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As VariableDeclaratorSyntax) As Boolean
Return node.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso node.Names.Count = 1
End Function
''' <returns>
''' Given a node representing a declaration or a top-level edit node returns:
''' - <see cref="MethodBlockBaseSyntax"/> for methods, constructors, operators and accessors.
''' - <see cref="ExpressionSyntax"/> for auto-properties and fields with initializer or AsNew clause.
''' - <see cref="ArgumentListSyntax"/> for fields with array initializer, e.g. "Dim a(1) As Integer".
''' A null reference otherwise.
''' </returns>
Friend Overrides Function TryGetDeclarationBody(node As SyntaxNode) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node
Case SyntaxKind.PropertyStatement
' the body is the initializer expression/new expression (if any)
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return propertyStatement.Initializer.Value
End If
If HasAsNewClause(propertyStatement) Then
Return DirectCast(propertyStatement.AsClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
If Not node.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
Dim body As SyntaxNode = Nothing
If variableDeclarator.Initializer IsNot Nothing Then
' Dim a = initializer
body = variableDeclarator.Initializer.Value
ElseIf HasAsNewClause(variableDeclarator) Then
' Dim a As New T
' Dim a,b As New T
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As T
If variableDeclarator.Names.Count = 1 Then
Dim name = variableDeclarator.Names(0)
If name.ArrayBounds IsNot Nothing Then
' Initializer and AsNew clause can't be syntactically specified at the same time, but array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, name.ArrayBounds, Nothing)
End If
End If
Return body
Case SyntaxKind.ModifiedIdentifier
If Not node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim modifiedIdentifier = CType(node, ModifiedIdentifierSyntax)
Dim body As SyntaxNode = Nothing
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
' AsNew clause can be syntactically specified at the same time as array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, modifiedIdentifier.ArrayBounds, Nothing)
End If
Return body
Case Else
' Note: A method without body is represented by a SubStatement.
Return Nothing
End Select
End Function
Friend Overrides Function IsDeclarationWithSharedBody(declaration As SyntaxNode) As Boolean
If declaration.Kind = SyntaxKind.ModifiedIdentifier AndAlso declaration.Parent.Kind = SyntaxKind.VariableDeclarator Then
Dim variableDeclarator = CType(declaration.Parent, VariableDeclaratorSyntax)
Return variableDeclarator.Names.Count > 1 AndAlso variableDeclarator.Initializer IsNot Nothing OrElse HasAsNewClause(variableDeclarator)
End If
Return False
End Function
Protected Overrides Function GetCapturedVariables(model As SemanticModel, memberBody As SyntaxNode) As ImmutableArray(Of ISymbol)
Dim methodBlock = TryCast(memberBody, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
If methodBlock.Statements.IsEmpty Then
Return ImmutableArray(Of ISymbol).Empty
End If
Return model.AnalyzeDataFlow(methodBlock.Statements.First, methodBlock.Statements.Last).Captured
End If
Dim expression = TryCast(memberBody, ExpressionSyntax)
If expression IsNot Nothing Then
Return model.AnalyzeDataFlow(expression).Captured
End If
' Edge case, no need to be efficient, currently there can either be no captured variables or just "Me".
' Dim a((Function(n) n + 1).Invoke(1), (Function(n) n + 2).Invoke(2)) As Integer
Dim arrayBounds = TryCast(memberBody, ArgumentListSyntax)
If arrayBounds IsNot Nothing Then
Return ImmutableArray.CreateRange(
arrayBounds.Arguments.
SelectMany(AddressOf GetArgumentExpressions).
SelectMany(Function(expr) model.AnalyzeDataFlow(expr).Captured).
Distinct())
End If
Throw ExceptionUtilities.UnexpectedValue(memberBody)
End Function
Private Shared Iterator Function GetArgumentExpressions(argument As ArgumentSyntax) As IEnumerable(Of ExpressionSyntax)
Select Case argument.Kind
Case SyntaxKind.SimpleArgument
Yield DirectCast(argument, SimpleArgumentSyntax).Expression
Case SyntaxKind.RangeArgument
Dim range = DirectCast(argument, RangeArgumentSyntax)
Yield range.LowerBound
Yield range.UpperBound
Case SyntaxKind.OmittedArgument
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
End Function
Friend Overrides Function HasParameterClosureScope(member As ISymbol) As Boolean
Return False
End Function
Protected Overrides Function GetVariableUseSites(roots As IEnumerable(Of SyntaxNode), localOrParameter As ISymbol, model As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode)
Debug.Assert(TypeOf localOrParameter Is IParameterSymbol OrElse TypeOf localOrParameter Is ILocalSymbol OrElse TypeOf localOrParameter Is IRangeVariableSymbol)
' Not supported (it's non trivial to find all places where "this" is used):
Debug.Assert(Not localOrParameter.IsThisParameter())
Return From root In roots
From node In root.DescendantNodesAndSelf()
Where node.IsKind(SyntaxKind.IdentifierName)
Let identifier = DirectCast(node, IdentifierNameSyntax)
Where String.Equals(DirectCast(identifier.Identifier.Value, String), localOrParameter.Name, StringComparison.OrdinalIgnoreCase) AndAlso
If(model.GetSymbolInfo(identifier, cancellationToken).Symbol?.Equals(localOrParameter), False)
Select node
End Function
Private Shared Function HasAsNewClause(variableDeclarator As VariableDeclaratorSyntax) As Boolean
Return variableDeclarator.AsClause IsNot Nothing AndAlso variableDeclarator.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
Private Shared Function HasAsNewClause(propertyStatement As PropertyStatementSyntax) As Boolean
Return propertyStatement.AsClause IsNot Nothing AndAlso propertyStatement.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
''' <returns>
''' Methods, operators, constructors, property and event accessors:
''' - We need to return the entire block declaration since the Begin and End statements are covered by breakpoint spans.
''' Field declarations in form of "Dim a, b, c As New C()"
''' - Breakpoint spans cover "a", "b" and "c" and also "New C()" since the expression may contain lambdas.
''' For simplicity we don't allow moving the new expression independently of the field name.
''' Field declarations with array initializers "Dim a(n), b(n) As Integer"
''' - Breakpoint spans cover "a(n)" and "b(n)".
''' </returns>
Friend Overrides Function TryGetActiveTokens(node As SyntaxNode) As IEnumerable(Of SyntaxToken)
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node.DescendantTokens()
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(If(propertyStatement.AsClause?.DescendantTokens(),
Array.Empty(Of SyntaxToken))).Concat(propertyStatement.Initializer.DescendantTokens())
End If
If HasAsNewClause(propertyStatement) Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(propertyStatement.AsClause.DescendantTokens())
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
If Not IsFieldDeclaration(variableDeclarator) Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(node.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
If Not IsFieldDeclaration(modifiedIdentifier) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Return node.DescendantTokens().Concat(DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression.DescendantTokens())
End If
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return node.DescendantTokens()
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Friend Overrides Function GetActiveSpanEnvelope(declaration As SyntaxNode) As (envelope As TextSpan, hole As TextSpan)
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return (declaration.Span, Nothing)
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.Initializer.Span.End), Nothing)
End If
If HasAsNewClause(propertyStatement) Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.AsClause.Span.End), Nothing)
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(declaration, VariableDeclaratorSyntax)
If Not declaration.Parent.IsKind(SyntaxKind.FieldDeclaration) OrElse variableDeclarator.Names.Count > 1 Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(declaration.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
If Not declaration.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Dim asNewClause = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax)
Return (envelope:=TextSpan.FromBounds(declaration.Span.Start, asNewClause.NewExpression.Span.End),
hole:=TextSpan.FromBounds(declaration.Span.End, asNewClause.NewExpression.Span.Start))
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
Dim modifiedIdentifier = DirectCast(declaration, ModifiedIdentifierSyntax)
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (declaration.Span, Nothing)
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetEncompassingAncestorImpl(bodyOrMatchRoot As SyntaxNode) As SyntaxNode
' AsNewClause is a match root for field/property As New initializer
' EqualsClause is a match root for field/property initializer
If bodyOrMatchRoot.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.PropertyStatement))
Return bodyOrMatchRoot.Parent
End If
' ArgumentList is a match root for an array initialized field
If bodyOrMatchRoot.IsKind(SyntaxKind.ArgumentList) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return bodyOrMatchRoot.Parent
End If
' The following active nodes are outside of the initializer body,
' we need to return a node that encompasses them.
' Dim [|a = <<Body>>|]
' Dim [|a As Integer = <<Body>>|]
' Dim [|a As <<Body>>|]
' Dim [|a|], [|b|], [|c|] As <<Body>>
' Property [|P As Integer = <<Body>>|]
' Property [|P As <<Body>>|]
If bodyOrMatchRoot.Parent.IsKind(SyntaxKind.AsNewClause) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValue) Then
Return bodyOrMatchRoot.Parent.Parent
End If
Return bodyOrMatchRoot
End Function
Protected Overrides Function FindStatementAndPartner(declarationBody As SyntaxNode,
span As TextSpan,
partnerDeclarationBodyOpt As SyntaxNode,
<Out> ByRef partnerOpt As SyntaxNode,
<Out> ByRef statementPart As Integer) As SyntaxNode
Dim position = span.Start
SyntaxUtilities.AssertIsBody(declarationBody, allowLambda:=False)
Debug.Assert(partnerDeclarationBodyOpt Is Nothing OrElse partnerDeclarationBodyOpt.RawKind = declarationBody.RawKind)
' Only field and property initializers may have an [|active statement|] starting outside of the <<body>>.
' Simple field initializers: Dim [|a = <<expr>>|]
' Dim [|a As Integer = <<expr>>|]
' Dim [|a = <<expr>>|], [|b = <<expr>>|], [|c As Integer = <<expr>>|]
' Dim [|a As <<New C>>|]
' Array initialized fields: Dim [|a<<(array bounds)>>|] As Integer
' Shared initializers: Dim [|a|], [|b|] As <<New C(Function() [|...|])>>
' Property initializers: Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If position < declarationBody.SpanStart Then
If declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
Return declarationBody.Parent.Parent
End If
If declarationBody.IsKind(SyntaxKind.ArgumentList) Then
' Dim a<<ArgumentList>> As Integer
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent
End If
Debug.Assert(declarationBody.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return declarationBody.Parent
End If
If declarationBody.Parent.IsKind(SyntaxKind.AsNewClause) Then
Dim variableDeclarator = DirectCast(declarationBody.Parent.Parent, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
' Dim a, b, c As <<NewExpression>>
Dim nameIndex = GetItemIndexByPosition(variableDeclarator.Names, position)
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = DirectCast(partnerDeclarationBodyOpt.Parent.Parent, VariableDeclaratorSyntax).Names(nameIndex)
End If
Return variableDeclarator.Names(nameIndex)
Else
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
' Dim a As <<NewExpression>>
Return variableDeclarator
End If
End If
If declarationBody.Parent.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
declarationBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Return declarationBody.Parent.Parent
End If
End If
If Not declarationBody.FullSpan.Contains(position) Then
' invalid position, let's find a labeled node that encompasses the body:
position = declarationBody.SpanStart
End If
Dim node As SyntaxNode = Nothing
If partnerDeclarationBodyOpt IsNot Nothing Then
SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBodyOpt, node, partnerOpt)
Else
node = declarationBody.FindToken(position).Parent
partnerOpt = Nothing
End If
' In some cases active statements may start at the same position.
' Consider a nested lambda:
' Function(a) [|[|Function(b)|] a + b|]
' There are 2 active statements, one spanning the the body of the outer lambda and
' the other on the nested lambda's header.
' Find the parent whose span starts at the same position but it's length is at least as long as the active span's length.
While node.Span.Length < span.Length AndAlso node.Parent.SpanStart = position
node = node.Parent
partnerOpt = partnerOpt?.Parent
End While
Debug.Assert(node IsNot Nothing)
While node IsNot declarationBody AndAlso
Not SyntaxComparer.Statement.HasLabel(node) AndAlso
Not LambdaUtilities.IsLambdaBodyStatementOrExpression(node)
node = node.Parent
If partnerOpt IsNot Nothing Then
partnerOpt = partnerOpt.Parent
End If
End While
' In case of local variable declaration an active statement may start with a modified identifier.
' If it is a declaration with a simple initializer we want the resulting statement to be the declaration,
' not the identifier.
If node.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
node.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count = 1 Then
node = node.Parent
End If
Return node
End Function
Friend Overrides Function FindDeclarationBodyPartner(leftDeclaration As SyntaxNode, rightDeclaration As SyntaxNode, leftNode As SyntaxNode) As SyntaxNode
Debug.Assert(leftDeclaration.Kind = rightDeclaration.Kind)
' Special case modified identifiers with AsNew clause - the node we are seeking can be in the AsNew clause.
If leftDeclaration.Kind = SyntaxKind.ModifiedIdentifier Then
Dim leftDeclarator = CType(leftDeclaration.Parent, VariableDeclaratorSyntax)
Dim rightDeclarator = CType(rightDeclaration.Parent, VariableDeclaratorSyntax)
If leftDeclarator.AsClause IsNot Nothing AndAlso leftNode.SpanStart >= leftDeclarator.AsClause.SpanStart Then
Return SyntaxUtilities.FindPartner(leftDeclarator.AsClause, rightDeclarator.AsClause, leftNode)
End If
End If
Return SyntaxUtilities.FindPartner(leftDeclaration, rightDeclaration, leftNode)
End Function
Friend Overrides Function IsClosureScope(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsClosureScope(node)
End Function
Protected Overrides Function FindEnclosingLambdaBody(containerOpt As SyntaxNode, node As SyntaxNode) As SyntaxNode
Dim root As SyntaxNode = GetEncompassingAncestor(containerOpt)
While node IsNot root And node IsNot Nothing
Dim body As SyntaxNode = Nothing
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node, body) Then
Return body
End If
node = node.Parent
End While
Return Nothing
End Function
Protected Overrides Function TryGetPartnerLambdaBody(oldBody As SyntaxNode, newLambda As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetCorrespondingLambdaBody(oldBody, newLambda)
End Function
Protected Overrides Function ComputeTopLevelMatch(oldCompilationUnit As SyntaxNode, newCompilationUnit As SyntaxNode) As Match(Of SyntaxNode)
Return SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit)
End Function
Protected Overrides Function ComputeTopLevelDeclarationMatch(oldDeclaration As SyntaxNode, newDeclaration As SyntaxNode) As Match(Of SyntaxNode)
Contract.ThrowIfNull(oldDeclaration.Parent)
Contract.ThrowIfNull(newDeclaration.Parent)
' Allow matching field declarations represented by a identitifer and the whole variable declarator
' even when their node kinds do not match.
If oldDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso newDeclaration.IsKind(SyntaxKind.VariableDeclarator) Then
oldDeclaration = oldDeclaration.Parent
ElseIf oldDeclaration.IsKind(SyntaxKind.VariableDeclarator) AndAlso newDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) Then
newDeclaration = newDeclaration.Parent
End If
Dim comparer = New SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, {oldDeclaration}, {newDeclaration})
Return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent)
End Function
Protected Overrides Function ComputeBodyMatch(oldBody As SyntaxNode, newBody As SyntaxNode, knownMatches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As Match(Of SyntaxNode)
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
Debug.Assert((TypeOf oldBody.Parent Is LambdaExpressionSyntax) = (TypeOf oldBody.Parent Is LambdaExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
If TypeOf oldBody.Parent Is LambdaExpressionSyntax Then
' The root is a single/multi line sub/function lambda.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, oldBody.Parent.ChildNodes(), newBody.Parent.ChildNodes(), matchingLambdas:=True, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
If TypeOf oldBody Is ExpressionSyntax Then
' Dim a = <Expression>
' Dim a As <NewExpression>
' Dim a, b, c As <NewExpression>
' Queries: The root is a query clause, the body is the expression.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, {oldBody}, {newBody}, matchingLambdas:=False, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
' Method, accessor, operator, etc. bodies are represented by the declaring block, which is also the root.
' The body of an array initialized fields is an ArgumentListSyntax, which is the match root.
Return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches)
End Function
Protected Overrides Function TryMatchActiveStatement(oldStatement As SyntaxNode,
statementPart As Integer,
oldBody As SyntaxNode,
newBody As SyntaxNode,
<Out> ByRef newStatement As SyntaxNode) As Boolean
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
' only statements in bodies of the same kind can be matched
Debug.Assert((TypeOf oldBody Is MethodBlockBaseSyntax) = (TypeOf newBody Is MethodBlockBaseSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
Debug.Assert((TypeOf oldBody Is LambdaHeaderSyntax) = (TypeOf newBody Is LambdaHeaderSyntax))
Debug.Assert(oldBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) = newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Debug.Assert(oldBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) = newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
' methods
If TypeOf oldBody Is MethodBlockBaseSyntax Then
newStatement = Nothing
Return False
End If
' lambdas
If oldBody.IsKind(SyntaxKind.FunctionLambdaHeader) OrElse oldBody.IsKind(SyntaxKind.SubLambdaHeader) Then
Dim oldSingleLineLambda = TryCast(oldBody.Parent, SingleLineLambdaExpressionSyntax)
Dim newSingleLineLambda = TryCast(newBody.Parent, SingleLineLambdaExpressionSyntax)
If oldSingleLineLambda IsNot Nothing AndAlso
newSingleLineLambda IsNot Nothing AndAlso
oldStatement Is oldSingleLineLambda.Body Then
newStatement = newSingleLineLambda.Body
Return True
End If
newStatement = Nothing
Return False
End If
' array initialized fields
If newBody.IsKind(SyntaxKind.ArgumentList) Then
' the parent ModifiedIdentifier is the active statement
If oldStatement Is oldBody.Parent Then
newStatement = newBody.Parent
Return True
End If
newStatement = Nothing
Return False
End If
' field and property initializers
If TypeOf newBody Is ExpressionSyntax Then
If newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
' field
Dim newDeclarator = DirectCast(newBody.Parent.Parent, VariableDeclaratorSyntax)
Dim oldName As SyntaxToken
If oldStatement.IsKind(SyntaxKind.VariableDeclarator) Then
oldName = DirectCast(oldStatement, VariableDeclaratorSyntax).Names.Single.Identifier
Else
oldName = DirectCast(oldStatement, ModifiedIdentifierSyntax).Identifier
End If
For Each newName In newDeclarator.Names
If SyntaxFactory.AreEquivalent(newName.Identifier, oldName) Then
newStatement = newName
Return True
End If
Next
newStatement = Nothing
Return False
ElseIf newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' property
If oldStatement Is oldBody.Parent.Parent Then
newStatement = newBody.Parent.Parent
Return True
End If
newStatement = newBody
Return True
End If
End If
' queries
If oldStatement Is oldBody Then
newStatement = newBody
Return True
End If
newStatement = Nothing
Return False
End Function
#End Region
#Region "Syntax And Semantic Utils"
Protected Overrides Function GetGlobalStatementDiagnosticSpan(node As SyntaxNode) As TextSpan
Return Nothing
End Function
Protected Overrides ReadOnly Property LineDirectiveKeyword As String
Get
Return "ExternalSource"
End Get
End Property
Protected Overrides ReadOnly Property LineDirectiveSyntaxKind As UShort
Get
Return SyntaxKind.ExternalSourceDirectiveTrivia
End Get
End Property
Protected Overrides Function GetSyntaxSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit)
Return SyntaxComparer.GetSequenceEdits(oldNodes, newNodes)
End Function
Friend Overrides ReadOnly Property EmptyCompilationUnit As SyntaxNode
Get
Return SyntaxFactory.CompilationUnit()
End Get
End Property
Friend Overrides Function ExperimentalFeaturesEnabled(tree As SyntaxTree) As Boolean
' There are no experimental features at this time.
Return False
End Function
Protected Overrides Function StatementLabelEquals(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean
Return SyntaxComparer.Statement.GetLabelImpl(node1) = SyntaxComparer.Statement.GetLabelImpl(node2)
End Function
Private Shared Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer
For i = list.SeparatorCount - 1 To 0 Step -1
If position > list.GetSeparator(i).SpanStart Then
Return i + 1
End If
Next
Return 0
End Function
Private Shared Function ChildrenCompiledInBody(node As SyntaxNode) As Boolean
Return Not node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineSubLambdaExpression)
End Function
Protected Overrides Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(root, position, minLength:=0, span)
End Function
Protected Overrides Function TryGetActiveSpan(node As SyntaxNode, statementPart As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(node, node.SpanStart, minLength, span)
End Function
Protected Overrides Iterator Function EnumerateNearStatements(statement As SyntaxNode) As IEnumerable(Of ValueTuple(Of SyntaxNode, Integer))
Dim direction As Integer = +1
Dim nodeOrToken As SyntaxNodeOrToken = statement
Dim propertyOrFieldModifiers As SyntaxTokenList? = GetFieldOrPropertyModifiers(statement)
While True
' If the current statement is the last statement of if-block or try-block statements
' pretend there are no siblings following it.
Dim lastBlockStatement As SyntaxNode = Nothing
If nodeOrToken.Parent IsNot Nothing Then
If nodeOrToken.Parent.IsKind(SyntaxKind.MultiLineIfBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, MultiLineIfBlockSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.SingleLineIfStatement) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, SingleLineIfStatementSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.TryBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, TryBlockSyntax).Statements.LastOrDefault()
End If
End If
If direction > 0 Then
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
Else
nodeOrToken = nodeOrToken.GetNextSibling()
End If
Else
nodeOrToken = nodeOrToken.GetPreviousSibling()
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
End If
End If
If nodeOrToken.RawKind = 0 Then
Dim parent = statement.Parent
If parent Is Nothing Then
Return
End If
If direction > 0 Then
nodeOrToken = statement
direction = -1
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Yield (statement, -1)
End If
nodeOrToken = parent
statement = parent
propertyOrFieldModifiers = GetFieldOrPropertyModifiers(statement)
direction = +1
End If
Dim node = nodeOrToken.AsNode()
If node Is Nothing Then
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Dim nodeModifiers = GetFieldOrPropertyModifiers(node)
If Not nodeModifiers.HasValue OrElse
propertyOrFieldModifiers.Value.Any(SyntaxKind.SharedKeyword) <> nodeModifiers.Value.Any(SyntaxKind.SharedKeyword) Then
Continue While
End If
End If
Yield (node, DefaultStatementPart)
End While
End Function
Private Shared Function GetFieldOrPropertyModifiers(node As SyntaxNode) As SyntaxTokenList?
If node.IsKind(SyntaxKind.FieldDeclaration) Then
Return DirectCast(node, FieldDeclarationSyntax).Modifiers
ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then
Return DirectCast(node, PropertyStatementSyntax).Modifiers
Else
Return Nothing
End If
End Function
Protected Overrides Function AreEquivalent(left As SyntaxNode, right As SyntaxNode) As Boolean
Return SyntaxFactory.AreEquivalent(left, right)
End Function
Private Shared Function AreEquivalentIgnoringLambdaBodies(left As SyntaxNode, right As SyntaxNode) As Boolean
' usual case
If SyntaxFactory.AreEquivalent(left, right) Then
Return True
End If
Return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right)
End Function
Protected Overrides Function AreEquivalentActiveStatements(oldStatement As SyntaxNode, newStatement As SyntaxNode, statementPart As Integer) As Boolean
If oldStatement.RawKind <> newStatement.RawKind Then
Return False
End If
' Dim a,b,c As <NewExpression>
' We need to check the actual initializer expression in addition to the identifier.
If HasMultiInitializer(oldStatement) Then
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) AndAlso
AreEquivalentIgnoringLambdaBodies(DirectCast(oldStatement.Parent, VariableDeclaratorSyntax).AsClause,
DirectCast(newStatement.Parent, VariableDeclaratorSyntax).AsClause)
End If
Select Case oldStatement.Kind
Case SyntaxKind.SubNewStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' Header statements are nops. Changes in the header statements are changes in top-level surface
' which should not be reported as active statement rude edits.
Return True
Case Else
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement)
End Select
End Function
Private Shared Function HasMultiInitializer(modifiedIdentifier As SyntaxNode) As Boolean
Return modifiedIdentifier.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
Friend Overrides Function IsInterfaceDeclaration(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.InterfaceBlock)
End Function
Friend Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean
' No records in VB
Return False
End Function
Friend Overrides Function TryGetContainingTypeDeclaration(node As SyntaxNode) As SyntaxNode
Return node.Parent.FirstAncestorOrSelf(Of TypeBlockSyntax)() ' TODO: EnbumBlock?
End Function
Friend Overrides Function TryGetAssociatedMemberDeclaration(node As SyntaxNode, <Out> ByRef declaration As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter) Then
Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList))
declaration = node.Parent.Parent
Return True
End If
If node.IsParentKind(SyntaxKind.PropertyBlock, SyntaxKind.EventBlock) Then
declaration = node.Parent
Return True
End If
declaration = Nothing
Return False
End Function
Friend Overrides Function HasBackingField(propertyDeclaration As SyntaxNode) As Boolean
Return SyntaxUtilities.HasBackingField(propertyDeclaration)
End Function
Friend Overrides Function IsDeclarationWithInitializer(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.VariableDeclarator
Dim declarator = DirectCast(declaration, VariableDeclaratorSyntax)
Return GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing OrElse
declarator.Names.Any(Function(n) n.ArrayBounds IsNot Nothing)
Case SyntaxKind.ModifiedIdentifier
Debug.Assert(declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
declaration.Parent.IsKind(SyntaxKind.Parameter))
If Not declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
Return False
End If
Dim declarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
Dim identifier = DirectCast(declaration, ModifiedIdentifierSyntax)
Return identifier.ArrayBounds IsNot Nothing OrElse
GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing
Case SyntaxKind.PropertyStatement
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
Return GetInitializerExpression(propertyStatement.Initializer, propertyStatement.AsClause) IsNot Nothing
Case Else
Return False
End Select
End Function
Friend Overrides Function IsRecordPrimaryConstructorParameter(declaration As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(declaration As SyntaxNode, newContainingType As INamedTypeSymbol, ByRef isFirstAccessor As Boolean) As Boolean
Return False
End Function
Private Shared Function GetInitializerExpression(equalsValue As EqualsValueSyntax, asClause As AsClauseSyntax) As ExpressionSyntax
If equalsValue IsNot Nothing Then
Return equalsValue.Value
End If
If asClause IsNot Nothing AndAlso asClause.IsKind(SyntaxKind.AsNewClause) Then
Return DirectCast(asClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
End Function
''' <summary>
''' VB symbols return references that represent the declaration statement.
''' The node that represenets the whole declaration (the block) is the parent node if it exists.
''' For example, a method with a body is represented by a SubBlock/FunctionBlock while a method without a body
''' is represented by its declaration statement.
''' </summary>
Protected Overrides Function GetSymbolDeclarationSyntax(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode
Dim syntax = reference.GetSyntax(cancellationToken)
Dim parent = syntax.Parent
Select Case syntax.Kind
' declarations that always have block
Case SyntaxKind.NamespaceStatement
Debug.Assert(parent.Kind = SyntaxKind.NamespaceBlock)
Return parent
Case SyntaxKind.ClassStatement
Debug.Assert(parent.Kind = SyntaxKind.ClassBlock)
Return parent
Case SyntaxKind.StructureStatement
Debug.Assert(parent.Kind = SyntaxKind.StructureBlock)
Return parent
Case SyntaxKind.InterfaceStatement
Debug.Assert(parent.Kind = SyntaxKind.InterfaceBlock)
Return parent
Case SyntaxKind.ModuleStatement
Debug.Assert(parent.Kind = SyntaxKind.ModuleBlock)
Return parent
Case SyntaxKind.EnumStatement
Debug.Assert(parent.Kind = SyntaxKind.EnumBlock)
Return parent
Case SyntaxKind.SubNewStatement
Debug.Assert(parent.Kind = SyntaxKind.ConstructorBlock)
Return parent
Case SyntaxKind.OperatorStatement
Debug.Assert(parent.Kind = SyntaxKind.OperatorBlock)
Return parent
Case SyntaxKind.GetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.GetAccessorBlock)
Return parent
Case SyntaxKind.SetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.SetAccessorBlock)
Return parent
Case SyntaxKind.AddHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.AddHandlerAccessorBlock)
Return parent
Case SyntaxKind.RemoveHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RemoveHandlerAccessorBlock)
Return parent
Case SyntaxKind.RaiseEventAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RaiseEventAccessorBlock)
Return parent
' declarations that may or may not have block
Case SyntaxKind.SubStatement
Return If(parent.Kind = SyntaxKind.SubBlock, parent, syntax)
Case SyntaxKind.FunctionStatement
Return If(parent.Kind = SyntaxKind.FunctionBlock, parent, syntax)
Case SyntaxKind.PropertyStatement
Return If(parent.Kind = SyntaxKind.PropertyBlock, parent, syntax)
Case SyntaxKind.EventStatement
Return If(parent.Kind = SyntaxKind.EventBlock, parent, syntax)
' declarations that never have a block
Case SyntaxKind.ModifiedIdentifier
Contract.ThrowIfFalse(parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Dim variableDeclaration = CType(parent, VariableDeclaratorSyntax)
Return If(variableDeclaration.Names.Count = 1, parent, syntax)
Case SyntaxKind.VariableDeclarator
' fields are represented by ModifiedIdentifier:
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
Case Else
Return syntax
End Select
End Function
Friend Overrides Function IsConstructorWithMemberInitializers(declaration As SyntaxNode) As Boolean
Dim ctor = TryCast(declaration, ConstructorBlockSyntax)
If ctor Is Nothing Then
Return False
End If
' Constructor includes field initializers if the first statement
' isn't a call to another constructor of the declaring class or module.
If ctor.Statements.Count = 0 Then
Return True
End If
Dim firstStatement = ctor.Statements.First
If Not firstStatement.IsKind(SyntaxKind.ExpressionStatement) Then
Return True
End If
Dim expressionStatement = DirectCast(firstStatement, ExpressionStatementSyntax)
If Not expressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then
Return True
End If
Dim invocation = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
If Not invocation.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Return True
End If
Dim memberAccess = DirectCast(invocation.Expression, MemberAccessExpressionSyntax)
If Not memberAccess.Name.IsKind(SyntaxKind.IdentifierName) OrElse
Not memberAccess.Name.Identifier.IsKind(SyntaxKind.IdentifierToken) Then
Return True
End If
' Note that ValueText returns "New" for both New and [New]
If Not String.Equals(memberAccess.Name.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Return memberAccess.Expression.IsKind(SyntaxKind.MyBaseKeyword)
End Function
Friend Overrides Function IsPartial(type As INamedTypeSymbol) As Boolean
Dim syntaxRefs = type.DeclaringSyntaxReferences
Return syntaxRefs.Length > 1 OrElse
DirectCast(syntaxRefs.Single().GetSyntax(), TypeStatementSyntax).Modifiers.Any(SyntaxKind.PartialKeyword)
End Function
Protected Overrides Function GetSymbolEdits(
editKind As EditKind,
oldNode As SyntaxNode,
newNode As SyntaxNode,
oldModel As SemanticModel,
newModel As SemanticModel,
editMap As IReadOnlyDictionary(Of SyntaxNode, EditKind),
cancellationToken As CancellationToken) As OneOrMany(Of (oldSymbol As ISymbol, newSymbol As ISymbol, editKind As EditKind))
Dim oldSymbols As OneOrMany(Of ISymbol) = Nothing
Dim newSymbols As OneOrMany(Of ISymbol) = Nothing
If editKind = EditKind.Delete Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return oldSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(s, Nothing, editKind))
End If
If editKind = EditKind.Insert Then
If Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return newSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(Nothing, s, editKind))
End If
If editKind = EditKind.Update Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) OrElse
Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
If oldSymbols.Count = 1 AndAlso newSymbols.Count = 1 Then
Return OneOrMany.Create((oldSymbols(0), newSymbols(0), editKind))
End If
' This only occurs when field identifiers are deleted/inserted/reordered from/to/within their variable declarator list,
' or their shared initializer is updated. The particular inserted and deleted fields will be represented by separate edits,
' but the AsNew clause of the declarator may have been updated as well, which needs to update the remaining (matching) fields.
Dim builder = ArrayBuilder(Of (ISymbol, ISymbol, EditKind)).GetInstance()
For Each oldSymbol In oldSymbols
Dim newSymbol = newSymbols.FirstOrDefault(Function(s, o) CaseInsensitiveComparison.Equals(s.Name, o.Name), oldSymbol)
If newSymbol IsNot Nothing Then
builder.Add((oldSymbol, newSymbol, editKind))
End If
Next
Return OneOrMany.Create(builder.ToImmutableAndFree())
End If
Throw ExceptionUtilities.UnexpectedValue(editKind)
End Function
Private Shared Function TryGetSyntaxNodesForEdit(
editKind As EditKind,
node As SyntaxNode,
model As SemanticModel,
<Out> ByRef symbols As OneOrMany(Of ISymbol),
cancellationToken As CancellationToken) As Boolean
Select Case node.Kind()
Case SyntaxKind.ImportsStatement,
SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock
Return False
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = CType(node, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
symbols = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) model.GetDeclaredSymbol(n, cancellationToken)))
Return True
End If
node = variableDeclarator.Names(0)
Case SyntaxKind.FieldDeclaration
If editKind = EditKind.Update Then
Dim field = CType(node, FieldDeclarationSyntax)
If field.Declarators.Count = 1 AndAlso field.Declarators(0).Names.Count = 1 Then
node = field.Declarators(0).Names(0)
Else
symbols = OneOrMany.Create(
(From declarator In field.Declarators
From name In declarator.Names
Select model.GetDeclaredSymbol(name, cancellationToken)).ToImmutableArray())
Return True
End If
End If
End Select
Dim symbol = model.GetDeclaredSymbol(node, cancellationToken)
If symbol Is Nothing Then
Return False
End If
' Ignore partial method definition parts.
' Partial method that does not have implementation part is not emitted to metadata.
' Partial method without a definition part is a compilation error.
If symbol.Kind = SymbolKind.Method AndAlso CType(symbol, IMethodSymbol).IsPartialDefinition Then
Return False
End If
symbols = OneOrMany.Create(symbol)
Return True
End Function
Friend Overrides Function ContainsLambda(declaration As SyntaxNode) As Boolean
Return declaration.DescendantNodes().Any(AddressOf LambdaUtilities.IsLambda)
End Function
Friend Overrides Function IsLambda(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsLambda(node)
End Function
Friend Overrides Function IsNestedFunction(node As SyntaxNode) As Boolean
Return TypeOf node Is LambdaExpressionSyntax
End Function
Friend Overrides Function IsLocalFunction(node As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function TryGetLambdaBodies(node As SyntaxNode, ByRef body1 As SyntaxNode, ByRef body2 As SyntaxNode) As Boolean
Return LambdaUtilities.TryGetLambdaBodies(node, body1, body2)
End Function
Friend Overrides Function GetLambda(lambdaBody As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetLambda(lambdaBody)
End Function
Protected Overrides Function GetLambdaBodyExpressionsAndStatements(lambdaBody As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return LambdaUtilities.GetLambdaBodyExpressionsAndStatements(lambdaBody)
End Function
Friend Overrides Function GetLambdaExpressionSymbol(model As SemanticModel, lambdaExpression As SyntaxNode, cancellationToken As CancellationToken) As IMethodSymbol
Dim lambdaExpressionSyntax = DirectCast(lambdaExpression, LambdaExpressionSyntax)
' The semantic model only returns the lambda symbol for positions that are within the body of the lambda (not the header)
Return DirectCast(model.GetEnclosingSymbol(lambdaExpressionSyntax.SubOrFunctionHeader.Span.End, cancellationToken), IMethodSymbol)
End Function
Friend Overrides Function GetContainingQueryExpression(node As SyntaxNode) As SyntaxNode
Return node.FirstAncestorOrSelf(Of QueryExpressionSyntax)
End Function
Friend Overrides Function QueryClauseLambdasTypeEquivalent(oldModel As SemanticModel, oldNode As SyntaxNode, newModel As SemanticModel, newNode As SyntaxNode, cancellationToken As CancellationToken) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.AggregateClause
Dim oldInfo = oldModel.GetAggregateClauseSymbolInfo(DirectCast(oldNode, AggregateClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetAggregateClauseSymbolInfo(DirectCast(newNode, AggregateClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Select1.Symbol, newInfo.Select1.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.Select2.Symbol, newInfo.Select2.Symbol)
Case SyntaxKind.CollectionRangeVariable
Dim oldInfo = oldModel.GetCollectionRangeVariableSymbolInfo(DirectCast(oldNode, CollectionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetCollectionRangeVariableSymbolInfo(DirectCast(newNode, CollectionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.AsClauseConversion.Symbol, newInfo.AsClauseConversion.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.SelectMany.Symbol, newInfo.SelectMany.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.ToQueryableCollectionConversion.Symbol, newInfo.ToQueryableCollectionConversion.Symbol)
Case SyntaxKind.FunctionAggregation
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, FunctionAggregationSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, FunctionAggregationSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.ExpressionRangeVariable
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, ExpressionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, ExpressionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, OrderingSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, OrderingSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.FromClause,
SyntaxKind.WhereClause,
SyntaxKind.SkipClause,
SyntaxKind.TakeClause,
SyntaxKind.SkipWhileClause,
SyntaxKind.TakeWhileClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause,
SyntaxKind.SelectClause
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, QueryClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, QueryClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case Else
Return True
End Select
End Function
Protected Overrides Sub ReportLocalFunctionsDeclarationRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), bodyMatch As Match(Of SyntaxNode))
' VB has no local functions so we don't have anything to report
End Sub
#End Region
#Region "Diagnostic Info"
Protected Overrides ReadOnly Property ErrorDisplayFormat As SymbolDisplayFormat
Get
Return SymbolDisplayFormat.VisualBasicShortErrorMessageFormat
End Get
End Property
Protected Overrides Function TryGetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return If(TryGetDiagnosticSpanImpl(node, editKind), node.Span)
End Function
Private Shared Function TryGetDiagnosticSpanImpl(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node.Kind, node, editKind)
End Function
Protected Overrides Function GetBodyDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return GetDiagnosticSpan(node, editKind)
End Function
' internal for testing; kind is passed explicitly for testing as well
Friend Shared Function TryGetDiagnosticSpanImpl(kind As SyntaxKind, node As SyntaxNode, editKind As EditKind) As TextSpan?
Select Case kind
Case SyntaxKind.CompilationUnit
Return New TextSpan()
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement
Return node.Span
Case SyntaxKind.NamespaceBlock
Return GetDiagnosticSpan(DirectCast(node, NamespaceBlockSyntax).NamespaceStatement)
Case SyntaxKind.NamespaceStatement
Return GetDiagnosticSpan(DirectCast(node, NamespaceStatementSyntax))
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock
Return GetDiagnosticSpan(DirectCast(node, TypeBlockSyntax).BlockStatement)
Case SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement
Return GetDiagnosticSpan(DirectCast(node, TypeStatementSyntax))
Case SyntaxKind.EnumBlock
Return TryGetDiagnosticSpanImpl(DirectCast(node, EnumBlockSyntax).EnumStatement, editKind)
Case SyntaxKind.EnumStatement
Dim enumStatement = DirectCast(node, EnumStatementSyntax)
Return GetDiagnosticSpan(enumStatement.Modifiers, enumStatement.EnumKeyword, enumStatement.Identifier)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetDiagnosticSpan(DirectCast(node, MethodBlockBaseSyntax).BlockStatement)
Case SyntaxKind.EventBlock
Return GetDiagnosticSpan(DirectCast(node, EventBlockSyntax).EventStatement)
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.EventStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return GetDiagnosticSpan(DirectCast(node, MethodBaseSyntax))
Case SyntaxKind.PropertyBlock
Return GetDiagnosticSpan(DirectCast(node, PropertyBlockSyntax).PropertyStatement)
Case SyntaxKind.PropertyStatement
Return GetDiagnosticSpan(DirectCast(node, PropertyStatementSyntax))
Case SyntaxKind.FieldDeclaration
Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax)
Return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declarators.First, fieldDeclaration.Declarators.Last)
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return node.Span
Case SyntaxKind.TypeParameter
Return DirectCast(node, TypeParameterSyntax).Identifier.Span
Case SyntaxKind.TypeParameterList,
SyntaxKind.ParameterList,
SyntaxKind.AttributeList,
SyntaxKind.SimpleAsClause
If editKind = EditKind.Delete Then
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Else
Return node.Span
End If
Case SyntaxKind.AttributesStatement,
SyntaxKind.Attribute
Return node.Span
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
Return GetDiagnosticSpan(parameter.Modifiers, parameter.Identifier, parameter)
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return GetDiagnosticSpan(DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader)
Case SyntaxKind.MultiLineIfBlock
Dim ifStatement = DirectCast(node, MultiLineIfBlockSyntax).IfStatement
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.ElseIfBlock
Dim elseIfStatement = DirectCast(node, ElseIfBlockSyntax).ElseIfStatement
Return GetDiagnosticSpan(elseIfStatement.ElseIfKeyword, elseIfStatement.Condition, elseIfStatement.ThenKeyword)
Case SyntaxKind.SingleLineIfStatement
Dim ifStatement = DirectCast(node, SingleLineIfStatementSyntax)
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.SingleLineElseClause
Return DirectCast(node, SingleLineElseClauseSyntax).ElseKeyword.Span
Case SyntaxKind.TryBlock
Return DirectCast(node, TryBlockSyntax).TryStatement.TryKeyword.Span
Case SyntaxKind.CatchBlock
Return DirectCast(node, CatchBlockSyntax).CatchStatement.CatchKeyword.Span
Case SyntaxKind.FinallyBlock
Return DirectCast(node, FinallyBlockSyntax).FinallyStatement.FinallyKeyword.Span
Case SyntaxKind.SyncLockBlock
Return DirectCast(node, SyncLockBlockSyntax).SyncLockStatement.Span
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).WithStatement.Span
Case SyntaxKind.UsingBlock
Return DirectCast(node, UsingBlockSyntax).UsingStatement.Span
Case SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock,
SyntaxKind.DoLoopWhileBlock,
SyntaxKind.DoLoopUntilBlock
Return DirectCast(node, DoLoopBlockSyntax).DoStatement.Span
Case SyntaxKind.WhileBlock
Return DirectCast(node, WhileBlockSyntax).WhileStatement.Span
Case SyntaxKind.ForEachBlock,
SyntaxKind.ForBlock
Return DirectCast(node, ForOrForEachBlockSyntax).ForOrForEachStatement.Span
Case SyntaxKind.AwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).AwaitKeyword.Span
Case SyntaxKind.AnonymousObjectCreationExpression
Dim newWith = DirectCast(node, AnonymousObjectCreationExpressionSyntax)
Return TextSpan.FromBounds(newWith.NewKeyword.Span.Start,
newWith.Initializer.WithKeyword.Span.End)
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span
Case SyntaxKind.QueryExpression
Return TryGetDiagnosticSpanImpl(DirectCast(node, QueryExpressionSyntax).Clauses.First(), editKind)
Case SyntaxKind.WhereClause
Return DirectCast(node, WhereClauseSyntax).WhereKeyword.Span
Case SyntaxKind.SelectClause
Return DirectCast(node, SelectClauseSyntax).SelectKeyword.Span
Case SyntaxKind.FromClause
Return DirectCast(node, FromClauseSyntax).FromKeyword.Span
Case SyntaxKind.AggregateClause
Return DirectCast(node, AggregateClauseSyntax).AggregateKeyword.Span
Case SyntaxKind.LetClause
Return DirectCast(node, LetClauseSyntax).LetKeyword.Span
Case SyntaxKind.SimpleJoinClause
Return DirectCast(node, SimpleJoinClauseSyntax).JoinKeyword.Span
Case SyntaxKind.GroupJoinClause
Dim groupJoin = DirectCast(node, GroupJoinClauseSyntax)
Return TextSpan.FromBounds(groupJoin.GroupKeyword.SpanStart, groupJoin.JoinKeyword.Span.End)
Case SyntaxKind.GroupByClause
Return DirectCast(node, GroupByClauseSyntax).GroupKeyword.Span
Case SyntaxKind.FunctionAggregation
Return node.Span
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause,
SyntaxKind.SkipWhileClause
Dim partition = DirectCast(node, PartitionWhileClauseSyntax)
Return TextSpan.FromBounds(partition.SkipOrTakeKeyword.SpanStart, partition.WhileKeyword.Span.End)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return node.Span
Case SyntaxKind.JoinCondition
Return DirectCast(node, JoinConditionSyntax).EqualsKeyword.Span
Case Else
Return node.Span
End Select
End Function
Private Overloads Shared Function GetDiagnosticSpan(ifKeyword As SyntaxToken, condition As SyntaxNode, thenKeywordOpt As SyntaxToken) As TextSpan
Return TextSpan.FromBounds(ifKeyword.Span.Start,
If(thenKeywordOpt.RawKind <> 0, thenKeywordOpt.Span.End, condition.Span.End))
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As NamespaceStatementSyntax) As TextSpan
Return TextSpan.FromBounds(node.NamespaceKeyword.SpanStart, node.Name.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As TypeStatementSyntax) As TextSpan
Return GetDiagnosticSpan(node.Modifiers,
node.DeclarationKeyword,
If(node.TypeParameterList, CType(node.Identifier, SyntaxNodeOrToken)))
End Function
Private Overloads Shared Function GetDiagnosticSpan(modifiers As SyntaxTokenList, start As SyntaxNodeOrToken, endNode As SyntaxNodeOrToken) As TextSpan
Return TextSpan.FromBounds(If(modifiers.Count <> 0, modifiers.First.SpanStart, start.SpanStart),
endNode.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(header As MethodBaseSyntax) As TextSpan
Dim startToken As SyntaxToken
Dim endToken As SyntaxToken
If header.Modifiers.Count > 0 Then
startToken = header.Modifiers.First
Else
Select Case header.Kind
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
startToken = DirectCast(header, DelegateStatementSyntax).DelegateKeyword
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
startToken = DirectCast(header, DeclareStatementSyntax).DeclareKeyword
Case Else
startToken = header.DeclarationKeyword
End Select
End If
If header.ParameterList IsNot Nothing Then
endToken = header.ParameterList.CloseParenToken
Else
Select Case header.Kind
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
endToken = DirectCast(header, MethodStatementSyntax).Identifier
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
endToken = DirectCast(header, DeclareStatementSyntax).LibraryName.Token
Case SyntaxKind.OperatorStatement
endToken = DirectCast(header, OperatorStatementSyntax).OperatorToken
Case SyntaxKind.SubNewStatement
endToken = DirectCast(header, SubNewStatementSyntax).NewKeyword
Case SyntaxKind.PropertyStatement
endToken = DirectCast(header, PropertyStatementSyntax).Identifier
Case SyntaxKind.EventStatement
endToken = DirectCast(header, EventStatementSyntax).Identifier
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
endToken = DirectCast(header, DelegateStatementSyntax).Identifier
Case SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
endToken = header.DeclarationKeyword
Case Else
Throw ExceptionUtilities.UnexpectedValue(header.Kind)
End Select
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(lambda As LambdaHeaderSyntax) As TextSpan
Dim startToken = If(lambda.Modifiers.Count <> 0, lambda.Modifiers.First, lambda.DeclarationKeyword)
Dim endToken As SyntaxToken
If lambda.ParameterList IsNot Nothing Then
endToken = lambda.ParameterList.CloseParenToken
Else
endToken = lambda.DeclarationKeyword
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Friend Overrides Function GetLambdaParameterDiagnosticSpan(lambda As SyntaxNode, ordinal As Integer) As TextSpan
Select Case lambda.Kind
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(lambda, LambdaExpressionSyntax).SubOrFunctionHeader.ParameterList.Parameters(ordinal).Identifier.Span
Case Else
Return lambda.Span
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As INamedTypeSymbol) As String
Select Case symbol.TypeKind
Case TypeKind.Structure
Return VBFeaturesResources.structure_
Case TypeKind.Module
Return VBFeaturesResources.module_
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IMethodSymbol) As String
Select Case symbol.MethodKind
Case MethodKind.StaticConstructor
Return VBFeaturesResources.Shared_constructor
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IPropertySymbol) As String
If symbol.IsWithEvents Then
Return VBFeaturesResources.WithEvents_field
End If
Return MyBase.GetDisplayName(symbol)
End Function
Protected Overrides Function TryGetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Return TryGetDisplayNameImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Dim result = TryGetDisplayNameImpl(node, editKind)
If result Is Nothing Then
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End If
Return result
End Function
Protected Overrides Function GetBodyDisplayName(node As SyntaxNode, Optional editKind As EditKind = EditKind.Update) As String
Return GetDisplayName(node, editKind)
End Function
Private Shared Function TryGetDisplayNameImpl(node As SyntaxNode, editKind As EditKind) As String
Select Case node.Kind
' top-level
Case SyntaxKind.OptionStatement
Return VBFeaturesResources.option_
Case SyntaxKind.ImportsStatement
Return VBFeaturesResources.import
Case SyntaxKind.NamespaceBlock,
SyntaxKind.NamespaceStatement
Return FeaturesResources.namespace_
Case SyntaxKind.ClassBlock,
SyntaxKind.ClassStatement
Return FeaturesResources.class_
Case SyntaxKind.StructureBlock,
SyntaxKind.StructureStatement
Return VBFeaturesResources.structure_
Case SyntaxKind.InterfaceBlock,
SyntaxKind.InterfaceStatement
Return FeaturesResources.interface_
Case SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement
Return VBFeaturesResources.module_
Case SyntaxKind.EnumBlock,
SyntaxKind.EnumStatement
Return FeaturesResources.enum_
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return FeaturesResources.delegate_
Case SyntaxKind.FieldDeclaration
Dim declaration = DirectCast(node, FieldDeclarationSyntax)
Return If(declaration.Modifiers.Any(SyntaxKind.WithEventsKeyword), VBFeaturesResources.WithEvents_field,
If(declaration.Modifiers.Any(SyntaxKind.ConstKeyword), FeaturesResources.const_field, FeaturesResources.field))
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return FeaturesResources.method
Case SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement
Return FeaturesResources.operator_
Case SyntaxKind.ConstructorBlock
Return If(CType(node, ConstructorBlockSyntax).SubNewStatement.Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.SubNewStatement
Return If(CType(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.PropertyBlock
Return FeaturesResources.property_
Case SyntaxKind.PropertyStatement
Return If(node.IsParentKind(SyntaxKind.PropertyBlock),
FeaturesResources.property_,
FeaturesResources.auto_property)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return FeaturesResources.event_
Case SyntaxKind.EnumMemberDeclaration
Return FeaturesResources.enum_value
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
Return FeaturesResources.property_accessor
Case SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return FeaturesResources.event_accessor
Case SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return FeaturesResources.type_constraint
Case SyntaxKind.SimpleAsClause
Return VBFeaturesResources.as_clause
Case SyntaxKind.TypeParameterList
Return VBFeaturesResources.type_parameters
Case SyntaxKind.TypeParameter
Return FeaturesResources.type_parameter
Case SyntaxKind.ParameterList
Return VBFeaturesResources.parameters
Case SyntaxKind.Parameter
Return FeaturesResources.parameter
Case SyntaxKind.AttributeList,
SyntaxKind.AttributesStatement
Return VBFeaturesResources.attributes
Case SyntaxKind.Attribute
Return FeaturesResources.attribute
' statement-level
Case SyntaxKind.TryBlock
Return VBFeaturesResources.Try_block
Case SyntaxKind.CatchBlock
Return VBFeaturesResources.Catch_clause
Case SyntaxKind.FinallyBlock
Return VBFeaturesResources.Finally_clause
Case SyntaxKind.UsingBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.Using_statement, VBFeaturesResources.Using_block)
Case SyntaxKind.WithBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.With_statement, VBFeaturesResources.With_block)
Case SyntaxKind.SyncLockBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.SyncLock_statement, VBFeaturesResources.SyncLock_block)
Case SyntaxKind.ForEachBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.For_Each_statement, VBFeaturesResources.For_Each_block)
Case SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.OnErrorGoToLabelStatement
Return VBFeaturesResources.On_Error_statement
Case SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return VBFeaturesResources.Resume_statement
Case SyntaxKind.YieldStatement
Return VBFeaturesResources.Yield_statement
Case SyntaxKind.AwaitExpression
Return VBFeaturesResources.Await_expression
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader
Return VBFeaturesResources.Lambda
Case SyntaxKind.WhereClause
Return VBFeaturesResources.Where_clause
Case SyntaxKind.SelectClause
Return VBFeaturesResources.Select_clause
Case SyntaxKind.FromClause
Return VBFeaturesResources.From_clause
Case SyntaxKind.AggregateClause
Return VBFeaturesResources.Aggregate_clause
Case SyntaxKind.LetClause
Return VBFeaturesResources.Let_clause
Case SyntaxKind.SimpleJoinClause
Return VBFeaturesResources.Join_clause
Case SyntaxKind.GroupJoinClause
Return VBFeaturesResources.Group_Join_clause
Case SyntaxKind.GroupByClause
Return VBFeaturesResources.Group_By_clause
Case SyntaxKind.FunctionAggregation
Return VBFeaturesResources.Function_aggregation
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause
Return VBFeaturesResources.Take_While_clause
Case SyntaxKind.SkipWhileClause
Return VBFeaturesResources.Skip_While_clause
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return VBFeaturesResources.Ordering_clause
Case SyntaxKind.JoinCondition
Return VBFeaturesResources.Join_condition
Case Else
Return Nothing
End Select
End Function
#End Region
#Region "Top-level Syntactic Rude Edits"
Private Structure EditClassifier
Private ReadOnly _analyzer As VisualBasicEditAndContinueAnalyzer
Private ReadOnly _diagnostics As ArrayBuilder(Of RudeEditDiagnostic)
Private ReadOnly _match As Match(Of SyntaxNode)
Private ReadOnly _oldNode As SyntaxNode
Private ReadOnly _newNode As SyntaxNode
Private ReadOnly _kind As EditKind
Private ReadOnly _span As TextSpan?
Public Sub New(analyzer As VisualBasicEditAndContinueAnalyzer,
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
oldNode As SyntaxNode,
newNode As SyntaxNode,
kind As EditKind,
Optional match As Match(Of SyntaxNode) = Nothing,
Optional span As TextSpan? = Nothing)
_analyzer = analyzer
_diagnostics = diagnostics
_oldNode = oldNode
_newNode = newNode
_kind = kind
_span = span
_match = match
End Sub
Private Sub ReportError(kind As RudeEditKind)
ReportError(kind, {GetDisplayName(If(_newNode, _oldNode), EditKind.Update)})
End Sub
Private Sub ReportError(kind As RudeEditKind, args As String())
_diagnostics.Add(New RudeEditDiagnostic(kind, GetSpan(), If(_newNode, _oldNode), args))
End Sub
Private Sub ReportError(kind As RudeEditKind, spanNode As SyntaxNode, displayNode As SyntaxNode)
_diagnostics.Add(New RudeEditDiagnostic(kind, GetDiagnosticSpan(spanNode, _kind), displayNode, {GetDisplayName(displayNode, EditKind.Update)}))
End Sub
Private Function GetSpan() As TextSpan
If _span.HasValue Then
Return _span.Value
End If
If _newNode Is Nothing Then
Return _analyzer.GetDeletedNodeDiagnosticSpan(_match.Matches, _oldNode)
Else
Return GetDiagnosticSpan(_newNode, _kind)
End If
End Function
Public Sub ClassifyEdit()
Select Case _kind
Case EditKind.Delete
ClassifyDelete(_oldNode)
Return
Case EditKind.Update
ClassifyUpdate(_oldNode, _newNode)
Return
Case EditKind.Move
ClassifyMove(_newNode)
Return
Case EditKind.Insert
ClassifyInsert(_newNode)
Return
Case EditKind.Reorder
ClassifyReorder(_oldNode, _newNode)
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(_kind)
End Select
End Sub
#Region "Move and Reorder"
Private Sub ClassifyMove(newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
ReportError(RudeEditKind.Move)
End Select
End Sub
Private Sub ClassifyReorder(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement,
SyntaxKind.AttributesStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.EventBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint,
SyntaxKind.AttributeList,
SyntaxKind.Attribute
' We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection.
Return
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
' Interface methods. We could allow reordering of non-COM interface methods.
Debug.Assert(oldNode.Parent.IsKind(SyntaxKind.InterfaceBlock) AndAlso newNode.Parent.IsKind(SyntaxKind.InterfaceBlock))
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.PropertyStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.EventStatement
' Maybe we could allow changing order of field declarations unless the containing type layout is sequential,
' and it's not a COM interface.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.EnumMemberDeclaration
' To allow this change we would need to check that values of all fields of the enum
' are preserved, or make sure we can update all method bodies that accessed those that changed.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.TypeParameter,
SyntaxKind.Parameter
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(newNode.Kind)
End Select
End Sub
#End Region
#Region "Insert"
Private Sub ClassifyInsert(node As SyntaxNode)
Select Case node.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.AttributesStatement
' Module/assembly attribute
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude
If node.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude
If node.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Delete"
Private Sub ClassifyDelete(oldNode As SyntaxNode)
Select Case oldNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Delete)
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude edits
If oldNode.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If oldNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Update"
Private Sub ClassifyUpdate(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.NamespaceStatement
ClassifyUpdate(DirectCast(oldNode, NamespaceStatementSyntax), DirectCast(newNode, NamespaceStatementSyntax))
Return
Case SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If newNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Update)
End If
Return
End Select
End Sub
Private Sub ClassifyUpdate(oldNode As NamespaceStatementSyntax, newNode As NamespaceStatementSyntax)
Debug.Assert(Not SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name))
ReportError(RudeEditKind.Renamed)
End Sub
Public Sub ClassifyDeclarationBodyRudeUpdates(newDeclarationOrBody As SyntaxNode)
For Each node In newDeclarationOrBody.DescendantNodesAndSelf()
Select Case node.Kind
Case SyntaxKind.AggregateClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause
ReportError(RudeEditKind.ComplexQueryExpression, node, Me._newNode)
Return
Case SyntaxKind.LocalDeclarationStatement
Dim declaration = DirectCast(node, LocalDeclarationStatementSyntax)
If declaration.Modifiers.Any(SyntaxKind.StaticKeyword) Then
ReportError(RudeEditKind.UpdateStaticLocal)
End If
End Select
Next
End Sub
#End Region
End Structure
Friend Overrides Sub ReportTopLevelSyntacticRudeEdits(
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
edit As Edit(Of SyntaxNode),
editMap As Dictionary(Of SyntaxNode, EditKind))
' For most nodes we ignore Insert and Delete edits if their parent was also inserted or deleted, respectively.
' For ModifiedIdentifiers though we check the grandparent instead because variables can move across
' VariableDeclarators. Moving a variable from a VariableDeclarator that only has a single variable results in
' deletion of that declarator. We don't want to report that delete. Similarly for moving to a new VariableDeclarator.
If edit.Kind = EditKind.Delete AndAlso
edit.OldNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.OldNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.OldNode.Parent.Parent, EditKind.Delete) Then
Return
End If
ElseIf edit.Kind = EditKind.Insert AndAlso
edit.NewNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.NewNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.NewNode.Parent.Parent, EditKind.Insert) Then
Return
End If
ElseIf HasParentEdit(editMap, edit) Then
Return
End If
Dim classifier = New EditClassifier(Me, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match)
classifier.ClassifyEdit()
End Sub
Friend Overrides Sub ReportMemberBodyUpdateRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newMember As SyntaxNode, span As TextSpan?)
Dim classifier = New EditClassifier(Me, diagnostics, Nothing, newMember, EditKind.Update, span:=span)
classifier.ClassifyDeclarationBodyRudeUpdates(newMember)
End Sub
#End Region
#Region "Semantic Rude Edits"
Protected Overrides Function AreHandledEventsEqual(oldMethod As IMethodSymbol, newMethod As IMethodSymbol) As Boolean
Return oldMethod.HandledEvents.SequenceEqual(
newMethod.HandledEvents,
Function(x, y)
Return x.HandlesKind = y.HandlesKind AndAlso
SymbolsEquivalent(x.EventContainer, y.EventContainer) AndAlso
SymbolsEquivalent(x.EventSymbol, y.EventSymbol) AndAlso
SymbolsEquivalent(x.WithEventsSourceProperty, y.WithEventsSourceProperty)
End Function)
End Function
Friend Overrides Sub ReportInsertedMemberSymbolRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newSymbol As ISymbol, newNode As SyntaxNode, insertingIntoExistingContainingType As Boolean)
Dim kind = GetInsertedMemberSymbolRudeEditKind(newSymbol, insertingIntoExistingContainingType)
If kind <> RudeEditKind.None Then
diagnostics.Add(New RudeEditDiagnostic(
kind,
GetDiagnosticSpan(newNode, EditKind.Insert),
newNode,
arguments:={GetDisplayName(newNode, EditKind.Insert)}))
End If
End Sub
Private Shared Function GetInsertedMemberSymbolRudeEditKind(newSymbol As ISymbol, insertingIntoExistingContainingType As Boolean) As RudeEditKind
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting P/Invoke into a new or existing type is not allowed.
If method.GetDllImportData() IsNot Nothing Then
Return RudeEditKind.InsertDllImport
End If
' Inserting method with handles clause into a new or existing type is not allowed.
If Not method.HandledEvents.IsEmpty Then
Return RudeEditKind.InsertHandlesClause
End If
Case SymbolKind.NamedType
Dim type = CType(newSymbol, INamedTypeSymbol)
' Inserting module is not allowed.
If type.TypeKind = TypeKind.Module Then
Return RudeEditKind.Insert
End If
End Select
' All rude edits below only apply when inserting into an existing type (not when the type itself is inserted):
If Not insertingIntoExistingContainingType Then
Return RudeEditKind.None
End If
If newSymbol.ContainingType.Arity > 0 AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertIntoGenericType
End If
' Inserting virtual or interface member is not allowed.
If (newSymbol.IsVirtual Or newSymbol.IsOverride Or newSymbol.IsAbstract) AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertVirtual
End If
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting generic method into an existing type is not allowed.
If method.Arity > 0 Then
Return RudeEditKind.InsertGenericMethod
End If
' Inserting operator to an existing type is not allowed.
If method.MethodKind = MethodKind.Conversion OrElse method.MethodKind = MethodKind.UserDefinedOperator Then
Return RudeEditKind.InsertOperator
End If
Return RudeEditKind.None
Case SymbolKind.Field
' Inserting a field into an enum is not allowed.
If newSymbol.ContainingType.TypeKind = TypeKind.Enum Then
Return RudeEditKind.Insert
End If
Return RudeEditKind.None
End Select
Return RudeEditKind.None
End Function
#End Region
#Region "Exception Handling Rude Edits"
Protected Overrides Function GetExceptionHandlingAncestors(node As SyntaxNode, isNonLeaf As Boolean) As List(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)()
While node IsNot Nothing
Dim kind = node.Kind
Select Case kind
Case SyntaxKind.TryBlock
If isNonLeaf Then
result.Add(node)
End If
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
result.Add(node)
Debug.Assert(node.Parent.Kind = SyntaxKind.TryBlock)
node = node.Parent
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock
' stop at type declaration
Exit While
End Select
' stop at lambda
If LambdaUtilities.IsLambda(node) Then
Exit While
End If
node = node.Parent
End While
Return result
End Function
Friend Overrides Sub ReportEnclosingExceptionHandlingRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
exceptionHandlingEdits As IEnumerable(Of Edit(Of SyntaxNode)),
oldStatement As SyntaxNode,
newStatementSpan As TextSpan)
For Each edit In exceptionHandlingEdits
Debug.Assert(edit.Kind <> EditKind.Update OrElse edit.OldNode.RawKind = edit.NewNode.RawKind)
If edit.Kind <> EditKind.Update OrElse Not AreExceptionHandlingPartsEquivalent(edit.OldNode, edit.NewNode) Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan)
End If
Next
End Sub
Private Shared Function AreExceptionHandlingPartsEquivalent(oldNode As SyntaxNode, newNode As SyntaxNode) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.TryBlock
Dim oldTryBlock = DirectCast(oldNode, TryBlockSyntax)
Dim newTryBlock = DirectCast(newNode, TryBlockSyntax)
Return SyntaxFactory.AreEquivalent(oldTryBlock.FinallyBlock, newTryBlock.FinallyBlock) AndAlso
SyntaxFactory.AreEquivalent(oldTryBlock.CatchBlocks, newTryBlock.CatchBlocks)
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
Return SyntaxFactory.AreEquivalent(oldNode, newNode)
Case Else
Throw ExceptionUtilities.UnexpectedValue(oldNode.Kind)
End Select
End Function
''' <summary>
''' An active statement (leaf or not) inside a "Catch" makes the Catch part readonly.
''' An active statement (leaf or not) inside a "Finally" makes the whole Try/Catch/Finally part read-only.
''' An active statement (non leaf) inside a "Try" makes the Catch/Finally part read-only.
''' </summary>
Protected Overrides Function GetExceptionHandlingRegion(node As SyntaxNode, <Out> ByRef coversAllChildren As Boolean) As TextSpan
Select Case node.Kind
Case SyntaxKind.TryBlock
Dim tryBlock = DirectCast(node, TryBlockSyntax)
coversAllChildren = False
If tryBlock.CatchBlocks.Count = 0 Then
Debug.Assert(tryBlock.FinallyBlock IsNot Nothing)
Return TextSpan.FromBounds(tryBlock.FinallyBlock.SpanStart, tryBlock.EndTryStatement.Span.End)
End If
Return TextSpan.FromBounds(tryBlock.CatchBlocks.First().SpanStart, tryBlock.EndTryStatement.Span.End)
Case SyntaxKind.CatchBlock
coversAllChildren = True
Return node.Span
Case SyntaxKind.FinallyBlock
coversAllChildren = True
Return DirectCast(node.Parent, TryBlockSyntax).Span
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
#End Region
#Region "State Machines"
Friend Overrides Function IsStateMachineMethod(declaration As SyntaxNode) As Boolean
Return SyntaxUtilities.IsAsyncMethodOrLambda(declaration) OrElse
SyntaxUtilities.IsIteratorMethodOrLambda(declaration)
End Function
Protected Overrides Sub GetStateMachineInfo(body As SyntaxNode, ByRef suspensionPoints As ImmutableArray(Of SyntaxNode), ByRef kind As StateMachineKinds)
' In VB declaration and body are represented by the same node for both lambdas and methods (unlike C#)
If SyntaxUtilities.IsAsyncMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetAwaitExpressions(body)
kind = StateMachineKinds.Async
ElseIf SyntaxUtilities.IsIteratorMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetYieldStatements(body)
kind = StateMachineKinds.Iterator
Else
suspensionPoints = ImmutableArray(Of SyntaxNode).Empty
kind = StateMachineKinds.None
End If
End Sub
Friend Overrides Sub ReportStateMachineSuspensionPointRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode)
' TODO: changes around suspension points (foreach, lock, using, etc.)
If newNode.IsKind(SyntaxKind.AwaitExpression) Then
Dim oldContainingStatementPart = FindContainingStatementPart(oldNode)
Dim newContainingStatementPart = FindContainingStatementPart(newNode)
' If the old statement has spilled state and the new doesn't, the edit is ok. We'll just not use the spilled state.
If Not SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) AndAlso
Not HasNoSpilledState(newNode, newContainingStatementPart) Then
diagnostics.Add(New RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span))
End If
End If
End Sub
Private Shared Function FindContainingStatementPart(node As SyntaxNode) As SyntaxNode
Dim statement = TryCast(node, StatementSyntax)
While statement Is Nothing
Select Case node.Parent.Kind()
Case SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.IfStatement,
SyntaxKind.WhileStatement,
SyntaxKind.SimpleDoStatement,
SyntaxKind.SelectStatement,
SyntaxKind.UsingStatement
Return node
End Select
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node) Then
Return node
End If
node = node.Parent
statement = TryCast(node, StatementSyntax)
End While
Return statement
End Function
Private Shared Function HasNoSpilledState(awaitExpression As SyntaxNode, containingStatementPart As SyntaxNode) As Boolean
Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression))
' There is nothing within the statement part surrounding the await expression.
If containingStatementPart Is awaitExpression Then
Return True
End If
Select Case containingStatementPart.Kind()
Case SyntaxKind.ExpressionStatement,
SyntaxKind.ReturnStatement
Dim expression = GetExpressionFromStatementPart(containingStatementPart)
' Await <expr>
' Return Await <expr>
If expression Is awaitExpression Then
Return True
End If
' <ident> = Await <expr>
' Return <ident> = Await <expr>
Return IsSimpleAwaitAssignment(expression, awaitExpression)
Case SyntaxKind.VariableDeclarator
' <ident> = Await <expr> in using, for, etc
' EqualsValue -> VariableDeclarator
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LoopUntilStatement,
SyntaxKind.LoopWhileStatement,
SyntaxKind.DoUntilStatement,
SyntaxKind.DoWhileStatement
' Until Await <expr>
' UntilClause -> LoopUntilStatement
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LocalDeclarationStatement
' Dim <ident> = Await <expr>
' EqualsValue -> VariableDeclarator -> LocalDeclarationStatement
Return awaitExpression.Parent.Parent.Parent Is containingStatementPart
End Select
Return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression)
End Function
Private Shared Function GetExpressionFromStatementPart(statement As SyntaxNode) As ExpressionSyntax
Select Case statement.Kind()
Case SyntaxKind.ExpressionStatement
Return DirectCast(statement, ExpressionStatementSyntax).Expression
Case SyntaxKind.ReturnStatement
Return DirectCast(statement, ReturnStatementSyntax).Expression
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind())
End Select
End Function
Private Shared Function IsSimpleAwaitAssignment(node As SyntaxNode, awaitExpression As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.SimpleAssignmentStatement) Then
Dim assignment = DirectCast(node, AssignmentStatementSyntax)
Return assignment.Left.IsKind(SyntaxKind.IdentifierName) AndAlso assignment.Right Is awaitExpression
End If
Return False
End Function
#End Region
#Region "Rude Edits around Active Statement"
Friend Overrides Sub ReportOtherRudeEditsAroundActiveStatement(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode,
isNonLeaf As Boolean)
Dim onErrorOrResumeStatement = FindOnErrorOrResumeStatement(match.NewRoot)
If onErrorOrResumeStatement IsNot Nothing Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, oldActiveStatement, onErrorOrResumeStatement, newActiveStatement.Span)
End If
ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement)
End Sub
Private Shared Function FindOnErrorOrResumeStatement(newDeclarationOrBody As SyntaxNode) As SyntaxNode
For Each node In newDeclarationOrBody.DescendantNodes(AddressOf ChildrenCompiledInBody)
Select Case node.Kind
Case SyntaxKind.OnErrorGoToLabelStatement,
SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return node
End Select
Next
Return Nothing
End Function
Private Sub ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode)
' Rude Edits for Using/SyncLock/With/ForEach statements that are added/updated around an active statement.
' Although such changes are technically possible, they might lead to confusion since
' the temporary variables these statements generate won't be properly initialized.
'
' We use a simple algorithm to match each New node with its old counterpart.
' If all nodes match this algorithm Is linear, otherwise it's quadratic.
'
' Unlike exception regions matching where we use LCS, we allow reordering of the statements.
ReportUnmatchedStatements(Of SyncLockBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.SyncLockBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.SyncLockStatement.Expression, n2.SyncLockStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of WithBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.WithBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.WithStatement.Expression, n2.WithStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of UsingBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.UsingBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.UsingStatement.Expression, n2.UsingStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of ForOrForEachBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.ForEachBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.ForOrForEachStatement, n2.ForOrForEachStatement),
areSimilar:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(DirectCast(n1.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable,
DirectCast(n2.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable))
End Sub
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Differencing
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue
Friend NotInheritable Class VisualBasicEditAndContinueAnalyzer
Inherits AbstractEditAndContinueAnalyzer
<ExportLanguageServiceFactory(GetType(IEditAndContinueAnalyzer), LanguageNames.VisualBasic), [Shared]>
Private NotInheritable Class Factory
Implements ILanguageServiceFactory
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
Return New VisualBasicEditAndContinueAnalyzer(testFaultInjector:=Nothing)
End Function
End Class
' Public for testing purposes
Public Sub New(Optional testFaultInjector As Action(Of SyntaxNode) = Nothing)
MyBase.New(testFaultInjector)
End Sub
#Region "Syntax Analysis"
Friend Overrides Function TryFindMemberDeclaration(rootOpt As SyntaxNode, node As SyntaxNode, <Out> ByRef declarations As OneOrMany(Of SyntaxNode)) As Boolean
Dim current = node
While current IsNot rootOpt
Select Case current.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
declarations = OneOrMany.Create(current)
Return True
Case SyntaxKind.PropertyStatement
' Property a As Integer = 1
' Property a As New T
If Not current.Parent.IsKind(SyntaxKind.PropertyBlock) Then
declarations = OneOrMany.Create(current)
Return True
End If
Case SyntaxKind.VariableDeclarator
If current.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Dim variableDeclarator = CType(current, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count = 1 Then
declarations = OneOrMany.Create(current)
Else
declarations = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) CType(n, SyntaxNode)))
End If
Return True
End If
Case SyntaxKind.ModifiedIdentifier
If current.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
declarations = OneOrMany.Create(current)
Return True
End If
End Select
current = current.Parent
End While
declarations = Nothing
Return False
End Function
''' <summary>
''' Returns true if the <see cref="ModifiedIdentifierSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As ModifiedIdentifierSyntax) As Boolean
Return node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
''' <summary>
''' Returns true if the <see cref="VariableDeclaratorSyntax"/> node represents a field declaration.
''' </summary>
Private Shared Function IsFieldDeclaration(node As VariableDeclaratorSyntax) As Boolean
Return node.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso node.Names.Count = 1
End Function
''' <returns>
''' Given a node representing a declaration or a top-level edit node returns:
''' - <see cref="MethodBlockBaseSyntax"/> for methods, constructors, operators and accessors.
''' - <see cref="ExpressionSyntax"/> for auto-properties and fields with initializer or AsNew clause.
''' - <see cref="ArgumentListSyntax"/> for fields with array initializer, e.g. "Dim a(1) As Integer".
''' A null reference otherwise.
''' </returns>
Friend Overrides Function TryGetDeclarationBody(node As SyntaxNode) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node
Case SyntaxKind.PropertyStatement
' the body is the initializer expression/new expression (if any)
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return propertyStatement.Initializer.Value
End If
If HasAsNewClause(propertyStatement) Then
Return DirectCast(propertyStatement.AsClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
If Not node.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
Dim body As SyntaxNode = Nothing
If variableDeclarator.Initializer IsNot Nothing Then
' Dim a = initializer
body = variableDeclarator.Initializer.Value
ElseIf HasAsNewClause(variableDeclarator) Then
' Dim a As New T
' Dim a,b As New T
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As T
If variableDeclarator.Names.Count = 1 Then
Dim name = variableDeclarator.Names(0)
If name.ArrayBounds IsNot Nothing Then
' Initializer and AsNew clause can't be syntactically specified at the same time, but array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, name.ArrayBounds, Nothing)
End If
End If
Return body
Case SyntaxKind.ModifiedIdentifier
If Not node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
Dim modifiedIdentifier = CType(node, ModifiedIdentifierSyntax)
Dim body As SyntaxNode = Nothing
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
' AsNew clause can be syntactically specified at the same time as array bounds can be (it's a semantic error).
' Guard against such case to maintain consistency and set body to Nothing in that case.
body = If(body Is Nothing, modifiedIdentifier.ArrayBounds, Nothing)
End If
Return body
Case Else
' Note: A method without body is represented by a SubStatement.
Return Nothing
End Select
End Function
Friend Overrides Function IsDeclarationWithSharedBody(declaration As SyntaxNode) As Boolean
If declaration.Kind = SyntaxKind.ModifiedIdentifier AndAlso declaration.Parent.Kind = SyntaxKind.VariableDeclarator Then
Dim variableDeclarator = CType(declaration.Parent, VariableDeclaratorSyntax)
Return variableDeclarator.Names.Count > 1 AndAlso variableDeclarator.Initializer IsNot Nothing OrElse HasAsNewClause(variableDeclarator)
End If
Return False
End Function
Protected Overrides Function GetCapturedVariables(model As SemanticModel, memberBody As SyntaxNode) As ImmutableArray(Of ISymbol)
Dim methodBlock = TryCast(memberBody, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
If methodBlock.Statements.IsEmpty Then
Return ImmutableArray(Of ISymbol).Empty
End If
Return model.AnalyzeDataFlow(methodBlock.Statements.First, methodBlock.Statements.Last).Captured
End If
Dim expression = TryCast(memberBody, ExpressionSyntax)
If expression IsNot Nothing Then
Return model.AnalyzeDataFlow(expression).Captured
End If
' Edge case, no need to be efficient, currently there can either be no captured variables or just "Me".
' Dim a((Function(n) n + 1).Invoke(1), (Function(n) n + 2).Invoke(2)) As Integer
Dim arrayBounds = TryCast(memberBody, ArgumentListSyntax)
If arrayBounds IsNot Nothing Then
Return ImmutableArray.CreateRange(
arrayBounds.Arguments.
SelectMany(AddressOf GetArgumentExpressions).
SelectMany(Function(expr) model.AnalyzeDataFlow(expr).Captured).
Distinct())
End If
Throw ExceptionUtilities.UnexpectedValue(memberBody)
End Function
Private Shared Iterator Function GetArgumentExpressions(argument As ArgumentSyntax) As IEnumerable(Of ExpressionSyntax)
Select Case argument.Kind
Case SyntaxKind.SimpleArgument
Yield DirectCast(argument, SimpleArgumentSyntax).Expression
Case SyntaxKind.RangeArgument
Dim range = DirectCast(argument, RangeArgumentSyntax)
Yield range.LowerBound
Yield range.UpperBound
Case SyntaxKind.OmittedArgument
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
End Function
Friend Overrides Function HasParameterClosureScope(member As ISymbol) As Boolean
Return False
End Function
Protected Overrides Function GetVariableUseSites(roots As IEnumerable(Of SyntaxNode), localOrParameter As ISymbol, model As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode)
Debug.Assert(TypeOf localOrParameter Is IParameterSymbol OrElse TypeOf localOrParameter Is ILocalSymbol OrElse TypeOf localOrParameter Is IRangeVariableSymbol)
' Not supported (it's non trivial to find all places where "this" is used):
Debug.Assert(Not localOrParameter.IsThisParameter())
Return From root In roots
From node In root.DescendantNodesAndSelf()
Where node.IsKind(SyntaxKind.IdentifierName)
Let identifier = DirectCast(node, IdentifierNameSyntax)
Where String.Equals(DirectCast(identifier.Identifier.Value, String), localOrParameter.Name, StringComparison.OrdinalIgnoreCase) AndAlso
If(model.GetSymbolInfo(identifier, cancellationToken).Symbol?.Equals(localOrParameter), False)
Select node
End Function
Private Shared Function HasAsNewClause(variableDeclarator As VariableDeclaratorSyntax) As Boolean
Return variableDeclarator.AsClause IsNot Nothing AndAlso variableDeclarator.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
Private Shared Function HasAsNewClause(propertyStatement As PropertyStatementSyntax) As Boolean
Return propertyStatement.AsClause IsNot Nothing AndAlso propertyStatement.AsClause.IsKind(SyntaxKind.AsNewClause)
End Function
''' <returns>
''' Methods, operators, constructors, property and event accessors:
''' - We need to return the entire block declaration since the Begin and End statements are covered by breakpoint spans.
''' Field declarations in form of "Dim a, b, c As New C()"
''' - Breakpoint spans cover "a", "b" and "c" and also "New C()" since the expression may contain lambdas.
''' For simplicity we don't allow moving the new expression independently of the field name.
''' Field declarations with array initializers "Dim a(n), b(n) As Integer"
''' - Breakpoint spans cover "a(n)" and "b(n)".
''' </returns>
Friend Overrides Function TryGetActiveTokens(node As SyntaxNode) As IEnumerable(Of SyntaxToken)
Select Case node.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return node.DescendantTokens()
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(node, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(If(propertyStatement.AsClause?.DescendantTokens(),
Array.Empty(Of SyntaxToken))).Concat(propertyStatement.Initializer.DescendantTokens())
End If
If HasAsNewClause(propertyStatement) Then
Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(propertyStatement.AsClause.DescendantTokens())
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax)
If Not IsFieldDeclaration(variableDeclarator) Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(node.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return variableDeclarator.DescendantTokens()
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return variableDeclarator.DescendantTokens()
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax)
If Not IsFieldDeclaration(modifiedIdentifier) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Return node.DescendantTokens().Concat(DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression.DescendantTokens())
End If
' Dim a(n), b(n) As Integer
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return node.DescendantTokens()
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Friend Overrides Function GetActiveSpanEnvelope(declaration As SyntaxNode) As (envelope As TextSpan, hole As TextSpan)
Select Case declaration.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
' the body is the Statements list of the block
Return (declaration.Span, Nothing)
Case SyntaxKind.PropertyStatement
' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause
' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
If propertyStatement.Initializer IsNot Nothing Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.Initializer.Span.End), Nothing)
End If
If HasAsNewClause(propertyStatement) Then
Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.AsClause.Span.End), Nothing)
End If
Return Nothing
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = DirectCast(declaration, VariableDeclaratorSyntax)
If Not declaration.Parent.IsKind(SyntaxKind.FieldDeclaration) OrElse variableDeclarator.Names.Count > 1 Then
Return Nothing
End If
' Field: Attributes Modifiers Declarators
Dim fieldDeclaration = DirectCast(declaration.Parent, FieldDeclarationSyntax)
If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then
Return Nothing
End If
' Dim a = initializer
If variableDeclarator.Initializer IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a As New C()
If HasAsNewClause(variableDeclarator) Then
Return (variableDeclarator.Span, Nothing)
End If
' Dim a(n) As Integer
Dim modifiedIdentifier = variableDeclarator.Names.Single()
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (variableDeclarator.Span, Nothing)
End If
Return Nothing
Case SyntaxKind.ModifiedIdentifier
If Not declaration.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
Return Nothing
End If
' Dim a, b As New C()
Dim variableDeclarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
If HasAsNewClause(variableDeclarator) Then
Dim asNewClause = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax)
Return (envelope:=TextSpan.FromBounds(declaration.Span.Start, asNewClause.NewExpression.Span.End),
hole:=TextSpan.FromBounds(declaration.Span.End, asNewClause.NewExpression.Span.Start))
End If
' Dim a(n) As Integer
' Dim a(n), b(n) As Integer
Dim modifiedIdentifier = DirectCast(declaration, ModifiedIdentifierSyntax)
If modifiedIdentifier.ArrayBounds IsNot Nothing Then
Return (declaration.Span, Nothing)
End If
Return Nothing
Case Else
Return Nothing
End Select
End Function
Protected Overrides Function GetEncompassingAncestorImpl(bodyOrMatchRoot As SyntaxNode) As SyntaxNode
' AsNewClause is a match root for field/property As New initializer
' EqualsClause is a match root for field/property initializer
If bodyOrMatchRoot.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.PropertyStatement))
Return bodyOrMatchRoot.Parent
End If
' ArgumentList is a match root for an array initialized field
If bodyOrMatchRoot.IsKind(SyntaxKind.ArgumentList) Then
Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return bodyOrMatchRoot.Parent
End If
' The following active nodes are outside of the initializer body,
' we need to return a node that encompasses them.
' Dim [|a = <<Body>>|]
' Dim [|a As Integer = <<Body>>|]
' Dim [|a As <<Body>>|]
' Dim [|a|], [|b|], [|c|] As <<Body>>
' Property [|P As Integer = <<Body>>|]
' Property [|P As <<Body>>|]
If bodyOrMatchRoot.Parent.IsKind(SyntaxKind.AsNewClause) OrElse
bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValue) Then
Return bodyOrMatchRoot.Parent.Parent
End If
Return bodyOrMatchRoot
End Function
Protected Overrides Function FindStatementAndPartner(declarationBody As SyntaxNode,
span As TextSpan,
partnerDeclarationBodyOpt As SyntaxNode,
<Out> ByRef partnerOpt As SyntaxNode,
<Out> ByRef statementPart As Integer) As SyntaxNode
Dim position = span.Start
SyntaxUtilities.AssertIsBody(declarationBody, allowLambda:=False)
Debug.Assert(partnerDeclarationBodyOpt Is Nothing OrElse partnerDeclarationBodyOpt.RawKind = declarationBody.RawKind)
' Only field and property initializers may have an [|active statement|] starting outside of the <<body>>.
' Simple field initializers: Dim [|a = <<expr>>|]
' Dim [|a As Integer = <<expr>>|]
' Dim [|a = <<expr>>|], [|b = <<expr>>|], [|c As Integer = <<expr>>|]
' Dim [|a As <<New C>>|]
' Array initialized fields: Dim [|a<<(array bounds)>>|] As Integer
' Shared initializers: Dim [|a|], [|b|] As <<New C(Function() [|...|])>>
' Property initializers: Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If position < declarationBody.SpanStart Then
If declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' Property [|p As Integer = <<body>>|]
' Property [|p As <<New C()>>|]
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
Return declarationBody.Parent.Parent
End If
If declarationBody.IsKind(SyntaxKind.ArgumentList) Then
' Dim a<<ArgumentList>> As Integer
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent
End If
Debug.Assert(declarationBody.Parent.IsKind(SyntaxKind.ModifiedIdentifier))
Return declarationBody.Parent
End If
If declarationBody.Parent.IsKind(SyntaxKind.AsNewClause) Then
Dim variableDeclarator = DirectCast(declarationBody.Parent.Parent, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
' Dim a, b, c As <<NewExpression>>
Dim nameIndex = GetItemIndexByPosition(variableDeclarator.Names, position)
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = DirectCast(partnerDeclarationBodyOpt.Parent.Parent, VariableDeclaratorSyntax).Names(nameIndex)
End If
Return variableDeclarator.Names(nameIndex)
Else
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
' Dim a As <<NewExpression>>
Return variableDeclarator
End If
End If
If declarationBody.Parent.IsKind(SyntaxKind.EqualsValue) Then
Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
declarationBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
If partnerDeclarationBodyOpt IsNot Nothing Then
partnerOpt = partnerDeclarationBodyOpt.Parent.Parent
End If
Return declarationBody.Parent.Parent
End If
End If
If Not declarationBody.FullSpan.Contains(position) Then
' invalid position, let's find a labeled node that encompasses the body:
position = declarationBody.SpanStart
End If
Dim node As SyntaxNode = Nothing
If partnerDeclarationBodyOpt IsNot Nothing Then
SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBodyOpt, node, partnerOpt)
Else
node = declarationBody.FindToken(position).Parent
partnerOpt = Nothing
End If
' In some cases active statements may start at the same position.
' Consider a nested lambda:
' Function(a) [|[|Function(b)|] a + b|]
' There are 2 active statements, one spanning the the body of the outer lambda and
' the other on the nested lambda's header.
' Find the parent whose span starts at the same position but it's length is at least as long as the active span's length.
While node.Span.Length < span.Length AndAlso node.Parent.SpanStart = position
node = node.Parent
partnerOpt = partnerOpt?.Parent
End While
Debug.Assert(node IsNot Nothing)
While node IsNot declarationBody AndAlso
Not SyntaxComparer.Statement.HasLabel(node) AndAlso
Not LambdaUtilities.IsLambdaBodyStatementOrExpression(node)
node = node.Parent
If partnerOpt IsNot Nothing Then
partnerOpt = partnerOpt.Parent
End If
End While
' In case of local variable declaration an active statement may start with a modified identifier.
' If it is a declaration with a simple initializer we want the resulting statement to be the declaration,
' not the identifier.
If node.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
node.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count = 1 Then
node = node.Parent
End If
Return node
End Function
Friend Overrides Function FindDeclarationBodyPartner(leftDeclaration As SyntaxNode, rightDeclaration As SyntaxNode, leftNode As SyntaxNode) As SyntaxNode
Debug.Assert(leftDeclaration.Kind = rightDeclaration.Kind)
' Special case modified identifiers with AsNew clause - the node we are seeking can be in the AsNew clause.
If leftDeclaration.Kind = SyntaxKind.ModifiedIdentifier Then
Dim leftDeclarator = CType(leftDeclaration.Parent, VariableDeclaratorSyntax)
Dim rightDeclarator = CType(rightDeclaration.Parent, VariableDeclaratorSyntax)
If leftDeclarator.AsClause IsNot Nothing AndAlso leftNode.SpanStart >= leftDeclarator.AsClause.SpanStart Then
Return SyntaxUtilities.FindPartner(leftDeclarator.AsClause, rightDeclarator.AsClause, leftNode)
End If
End If
Return SyntaxUtilities.FindPartner(leftDeclaration, rightDeclaration, leftNode)
End Function
Friend Overrides Function IsClosureScope(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsClosureScope(node)
End Function
Protected Overrides Function FindEnclosingLambdaBody(containerOpt As SyntaxNode, node As SyntaxNode) As SyntaxNode
Dim root As SyntaxNode = GetEncompassingAncestor(containerOpt)
While node IsNot root And node IsNot Nothing
Dim body As SyntaxNode = Nothing
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node, body) Then
Return body
End If
node = node.Parent
End While
Return Nothing
End Function
Protected Overrides Function TryGetPartnerLambdaBody(oldBody As SyntaxNode, newLambda As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetCorrespondingLambdaBody(oldBody, newLambda)
End Function
Protected Overrides Function ComputeTopLevelMatch(oldCompilationUnit As SyntaxNode, newCompilationUnit As SyntaxNode) As Match(Of SyntaxNode)
Return SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit)
End Function
Protected Overrides Function ComputeTopLevelDeclarationMatch(oldDeclaration As SyntaxNode, newDeclaration As SyntaxNode) As Match(Of SyntaxNode)
Contract.ThrowIfNull(oldDeclaration.Parent)
Contract.ThrowIfNull(newDeclaration.Parent)
' Allow matching field declarations represented by a identitifer and the whole variable declarator
' even when their node kinds do not match.
If oldDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso newDeclaration.IsKind(SyntaxKind.VariableDeclarator) Then
oldDeclaration = oldDeclaration.Parent
ElseIf oldDeclaration.IsKind(SyntaxKind.VariableDeclarator) AndAlso newDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) Then
newDeclaration = newDeclaration.Parent
End If
Dim comparer = New SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, {oldDeclaration}, {newDeclaration})
Return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent)
End Function
Protected Overrides Function ComputeBodyMatch(oldBody As SyntaxNode, newBody As SyntaxNode, knownMatches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As Match(Of SyntaxNode)
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
Debug.Assert((TypeOf oldBody.Parent Is LambdaExpressionSyntax) = (TypeOf oldBody.Parent Is LambdaExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
If TypeOf oldBody.Parent Is LambdaExpressionSyntax Then
' The root is a single/multi line sub/function lambda.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, oldBody.Parent.ChildNodes(), newBody.Parent.ChildNodes(), matchingLambdas:=True, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
If TypeOf oldBody Is ExpressionSyntax Then
' Dim a = <Expression>
' Dim a As <NewExpression>
' Dim a, b, c As <NewExpression>
' Queries: The root is a query clause, the body is the expression.
Return New SyntaxComparer(oldBody.Parent, newBody.Parent, {oldBody}, {newBody}, matchingLambdas:=False, compareStatementSyntax:=True).
ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches)
End If
' Method, accessor, operator, etc. bodies are represented by the declaring block, which is also the root.
' The body of an array initialized fields is an ArgumentListSyntax, which is the match root.
Return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches)
End Function
Protected Overrides Function TryMatchActiveStatement(oldStatement As SyntaxNode,
statementPart As Integer,
oldBody As SyntaxNode,
newBody As SyntaxNode,
<Out> ByRef newStatement As SyntaxNode) As Boolean
SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True)
SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True)
' only statements in bodies of the same kind can be matched
Debug.Assert((TypeOf oldBody Is MethodBlockBaseSyntax) = (TypeOf newBody Is MethodBlockBaseSyntax))
Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax))
Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax))
Debug.Assert((TypeOf oldBody Is LambdaHeaderSyntax) = (TypeOf newBody Is LambdaHeaderSyntax))
Debug.Assert(oldBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) = newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Debug.Assert(oldBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) = newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement))
' methods
If TypeOf oldBody Is MethodBlockBaseSyntax Then
newStatement = Nothing
Return False
End If
' lambdas
If oldBody.IsKind(SyntaxKind.FunctionLambdaHeader) OrElse oldBody.IsKind(SyntaxKind.SubLambdaHeader) Then
Dim oldSingleLineLambda = TryCast(oldBody.Parent, SingleLineLambdaExpressionSyntax)
Dim newSingleLineLambda = TryCast(newBody.Parent, SingleLineLambdaExpressionSyntax)
If oldSingleLineLambda IsNot Nothing AndAlso
newSingleLineLambda IsNot Nothing AndAlso
oldStatement Is oldSingleLineLambda.Body Then
newStatement = newSingleLineLambda.Body
Return True
End If
newStatement = Nothing
Return False
End If
' array initialized fields
If newBody.IsKind(SyntaxKind.ArgumentList) Then
' the parent ModifiedIdentifier is the active statement
If oldStatement Is oldBody.Parent Then
newStatement = newBody.Parent
Return True
End If
newStatement = Nothing
Return False
End If
' field and property initializers
If TypeOf newBody Is ExpressionSyntax Then
If newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then
' field
Dim newDeclarator = DirectCast(newBody.Parent.Parent, VariableDeclaratorSyntax)
Dim oldName As SyntaxToken
If oldStatement.IsKind(SyntaxKind.VariableDeclarator) Then
oldName = DirectCast(oldStatement, VariableDeclaratorSyntax).Names.Single.Identifier
Else
oldName = DirectCast(oldStatement, ModifiedIdentifierSyntax).Identifier
End If
For Each newName In newDeclarator.Names
If SyntaxFactory.AreEquivalent(newName.Identifier, oldName) Then
newStatement = newName
Return True
End If
Next
newStatement = Nothing
Return False
ElseIf newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then
' property
If oldStatement Is oldBody.Parent.Parent Then
newStatement = newBody.Parent.Parent
Return True
End If
newStatement = newBody
Return True
End If
End If
' queries
If oldStatement Is oldBody Then
newStatement = newBody
Return True
End If
newStatement = Nothing
Return False
End Function
#End Region
#Region "Syntax And Semantic Utils"
Protected Overrides Function GetGlobalStatementDiagnosticSpan(node As SyntaxNode) As TextSpan
Return Nothing
End Function
Protected Overrides ReadOnly Property LineDirectiveKeyword As String
Get
Return "ExternalSource"
End Get
End Property
Protected Overrides ReadOnly Property LineDirectiveSyntaxKind As UShort
Get
Return SyntaxKind.ExternalSourceDirectiveTrivia
End Get
End Property
Protected Overrides Function GetSyntaxSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit)
Return SyntaxComparer.GetSequenceEdits(oldNodes, newNodes)
End Function
Friend Overrides ReadOnly Property EmptyCompilationUnit As SyntaxNode
Get
Return SyntaxFactory.CompilationUnit()
End Get
End Property
Friend Overrides Function ExperimentalFeaturesEnabled(tree As SyntaxTree) As Boolean
' There are no experimental features at this time.
Return False
End Function
Protected Overrides Function StatementLabelEquals(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean
Return SyntaxComparer.Statement.GetLabelImpl(node1) = SyntaxComparer.Statement.GetLabelImpl(node2)
End Function
Private Shared Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer
For i = list.SeparatorCount - 1 To 0 Step -1
If position > list.GetSeparator(i).SpanStart Then
Return i + 1
End If
Next
Return 0
End Function
Private Shared Function ChildrenCompiledInBody(node As SyntaxNode) As Boolean
Return Not node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) AndAlso
Not node.IsKind(SyntaxKind.SingleLineSubLambdaExpression)
End Function
Protected Overrides Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(root, position, minLength:=0, span)
End Function
Protected Overrides Function TryGetActiveSpan(node As SyntaxNode, statementPart As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean
Return BreakpointSpans.TryGetEnclosingBreakpointSpan(node, node.SpanStart, minLength, span)
End Function
Protected Overrides Iterator Function EnumerateNearStatements(statement As SyntaxNode) As IEnumerable(Of ValueTuple(Of SyntaxNode, Integer))
Dim direction As Integer = +1
Dim nodeOrToken As SyntaxNodeOrToken = statement
Dim propertyOrFieldModifiers As SyntaxTokenList? = GetFieldOrPropertyModifiers(statement)
While True
' If the current statement is the last statement of if-block or try-block statements
' pretend there are no siblings following it.
Dim lastBlockStatement As SyntaxNode = Nothing
If nodeOrToken.Parent IsNot Nothing Then
If nodeOrToken.Parent.IsKind(SyntaxKind.MultiLineIfBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, MultiLineIfBlockSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.SingleLineIfStatement) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, SingleLineIfStatementSyntax).Statements.LastOrDefault()
ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.TryBlock) Then
lastBlockStatement = DirectCast(nodeOrToken.Parent, TryBlockSyntax).Statements.LastOrDefault()
End If
End If
If direction > 0 Then
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
Else
nodeOrToken = nodeOrToken.GetNextSibling()
End If
Else
nodeOrToken = nodeOrToken.GetPreviousSibling()
If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then
nodeOrToken = Nothing
End If
End If
If nodeOrToken.RawKind = 0 Then
Dim parent = statement.Parent
If parent Is Nothing Then
Return
End If
If direction > 0 Then
nodeOrToken = statement
direction = -1
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Yield (statement, -1)
End If
nodeOrToken = parent
statement = parent
propertyOrFieldModifiers = GetFieldOrPropertyModifiers(statement)
direction = +1
End If
Dim node = nodeOrToken.AsNode()
If node Is Nothing Then
Continue While
End If
If propertyOrFieldModifiers.HasValue Then
Dim nodeModifiers = GetFieldOrPropertyModifiers(node)
If Not nodeModifiers.HasValue OrElse
propertyOrFieldModifiers.Value.Any(SyntaxKind.SharedKeyword) <> nodeModifiers.Value.Any(SyntaxKind.SharedKeyword) Then
Continue While
End If
End If
Yield (node, DefaultStatementPart)
End While
End Function
Private Shared Function GetFieldOrPropertyModifiers(node As SyntaxNode) As SyntaxTokenList?
If node.IsKind(SyntaxKind.FieldDeclaration) Then
Return DirectCast(node, FieldDeclarationSyntax).Modifiers
ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then
Return DirectCast(node, PropertyStatementSyntax).Modifiers
Else
Return Nothing
End If
End Function
Protected Overrides Function AreEquivalent(left As SyntaxNode, right As SyntaxNode) As Boolean
Return SyntaxFactory.AreEquivalent(left, right)
End Function
Private Shared Function AreEquivalentIgnoringLambdaBodies(left As SyntaxNode, right As SyntaxNode) As Boolean
' usual case
If SyntaxFactory.AreEquivalent(left, right) Then
Return True
End If
Return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right)
End Function
Protected Overrides Function AreEquivalentActiveStatements(oldStatement As SyntaxNode, newStatement As SyntaxNode, statementPart As Integer) As Boolean
If oldStatement.RawKind <> newStatement.RawKind Then
Return False
End If
' Dim a,b,c As <NewExpression>
' We need to check the actual initializer expression in addition to the identifier.
If HasMultiInitializer(oldStatement) Then
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) AndAlso
AreEquivalentIgnoringLambdaBodies(DirectCast(oldStatement.Parent, VariableDeclaratorSyntax).AsClause,
DirectCast(newStatement.Parent, VariableDeclaratorSyntax).AsClause)
End If
Select Case oldStatement.Kind
Case SyntaxKind.SubNewStatement,
SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' Header statements are nops. Changes in the header statements are changes in top-level surface
' which should not be reported as active statement rude edits.
Return True
Case Else
Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement)
End Select
End Function
Private Shared Function HasMultiInitializer(modifiedIdentifier As SyntaxNode) As Boolean
Return modifiedIdentifier.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso
DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Names.Count > 1
End Function
Friend Overrides Function IsInterfaceDeclaration(node As SyntaxNode) As Boolean
Return node.IsKind(SyntaxKind.InterfaceBlock)
End Function
Friend Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean
' No records in VB
Return False
End Function
Friend Overrides Function TryGetContainingTypeDeclaration(node As SyntaxNode) As SyntaxNode
Return node.Parent.FirstAncestorOrSelf(Of TypeBlockSyntax)() ' TODO: EnbumBlock?
End Function
Friend Overrides Function TryGetAssociatedMemberDeclaration(node As SyntaxNode, <Out> ByRef declaration As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter) Then
Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList))
declaration = node.Parent.Parent
Return True
End If
If node.IsParentKind(SyntaxKind.PropertyBlock, SyntaxKind.EventBlock) Then
declaration = node.Parent
Return True
End If
declaration = Nothing
Return False
End Function
Friend Overrides Function HasBackingField(propertyDeclaration As SyntaxNode) As Boolean
Return SyntaxUtilities.HasBackingField(propertyDeclaration)
End Function
Friend Overrides Function IsDeclarationWithInitializer(declaration As SyntaxNode) As Boolean
Select Case declaration.Kind
Case SyntaxKind.VariableDeclarator
Dim declarator = DirectCast(declaration, VariableDeclaratorSyntax)
Return GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing OrElse
declarator.Names.Any(Function(n) n.ArrayBounds IsNot Nothing)
Case SyntaxKind.ModifiedIdentifier
Debug.Assert(declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse
declaration.Parent.IsKind(SyntaxKind.Parameter))
If Not declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
Return False
End If
Dim declarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax)
Dim identifier = DirectCast(declaration, ModifiedIdentifierSyntax)
Return identifier.ArrayBounds IsNot Nothing OrElse
GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing
Case SyntaxKind.PropertyStatement
Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax)
Return GetInitializerExpression(propertyStatement.Initializer, propertyStatement.AsClause) IsNot Nothing
Case Else
Return False
End Select
End Function
Friend Overrides Function IsRecordPrimaryConstructorParameter(declaration As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(declaration As SyntaxNode, newContainingType As INamedTypeSymbol, ByRef isFirstAccessor As Boolean) As Boolean
Return False
End Function
Private Shared Function GetInitializerExpression(equalsValue As EqualsValueSyntax, asClause As AsClauseSyntax) As ExpressionSyntax
If equalsValue IsNot Nothing Then
Return equalsValue.Value
End If
If asClause IsNot Nothing AndAlso asClause.IsKind(SyntaxKind.AsNewClause) Then
Return DirectCast(asClause, AsNewClauseSyntax).NewExpression
End If
Return Nothing
End Function
''' <summary>
''' VB symbols return references that represent the declaration statement.
''' The node that represenets the whole declaration (the block) is the parent node if it exists.
''' For example, a method with a body is represented by a SubBlock/FunctionBlock while a method without a body
''' is represented by its declaration statement.
''' </summary>
Protected Overrides Function GetSymbolDeclarationSyntax(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode
Dim syntax = reference.GetSyntax(cancellationToken)
Dim parent = syntax.Parent
Select Case syntax.Kind
' declarations that always have block
Case SyntaxKind.NamespaceStatement
Debug.Assert(parent.Kind = SyntaxKind.NamespaceBlock)
Return parent
Case SyntaxKind.ClassStatement
Debug.Assert(parent.Kind = SyntaxKind.ClassBlock)
Return parent
Case SyntaxKind.StructureStatement
Debug.Assert(parent.Kind = SyntaxKind.StructureBlock)
Return parent
Case SyntaxKind.InterfaceStatement
Debug.Assert(parent.Kind = SyntaxKind.InterfaceBlock)
Return parent
Case SyntaxKind.ModuleStatement
Debug.Assert(parent.Kind = SyntaxKind.ModuleBlock)
Return parent
Case SyntaxKind.EnumStatement
Debug.Assert(parent.Kind = SyntaxKind.EnumBlock)
Return parent
Case SyntaxKind.SubNewStatement
Debug.Assert(parent.Kind = SyntaxKind.ConstructorBlock)
Return parent
Case SyntaxKind.OperatorStatement
Debug.Assert(parent.Kind = SyntaxKind.OperatorBlock)
Return parent
Case SyntaxKind.GetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.GetAccessorBlock)
Return parent
Case SyntaxKind.SetAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.SetAccessorBlock)
Return parent
Case SyntaxKind.AddHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.AddHandlerAccessorBlock)
Return parent
Case SyntaxKind.RemoveHandlerAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RemoveHandlerAccessorBlock)
Return parent
Case SyntaxKind.RaiseEventAccessorStatement
Debug.Assert(parent.Kind = SyntaxKind.RaiseEventAccessorBlock)
Return parent
' declarations that may or may not have block
Case SyntaxKind.SubStatement
Return If(parent.Kind = SyntaxKind.SubBlock, parent, syntax)
Case SyntaxKind.FunctionStatement
Return If(parent.Kind = SyntaxKind.FunctionBlock, parent, syntax)
Case SyntaxKind.PropertyStatement
Return If(parent.Kind = SyntaxKind.PropertyBlock, parent, syntax)
Case SyntaxKind.EventStatement
Return If(parent.Kind = SyntaxKind.EventBlock, parent, syntax)
' declarations that never have a block
Case SyntaxKind.ModifiedIdentifier
Contract.ThrowIfFalse(parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
Dim variableDeclaration = CType(parent, VariableDeclaratorSyntax)
Return If(variableDeclaration.Names.Count = 1, parent, syntax)
Case SyntaxKind.VariableDeclarator
' fields are represented by ModifiedIdentifier:
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
Case Else
Return syntax
End Select
End Function
Friend Overrides Function IsConstructorWithMemberInitializers(declaration As SyntaxNode) As Boolean
Dim ctor = TryCast(declaration, ConstructorBlockSyntax)
If ctor Is Nothing Then
Return False
End If
' Constructor includes field initializers if the first statement
' isn't a call to another constructor of the declaring class or module.
If ctor.Statements.Count = 0 Then
Return True
End If
Dim firstStatement = ctor.Statements.First
If Not firstStatement.IsKind(SyntaxKind.ExpressionStatement) Then
Return True
End If
Dim expressionStatement = DirectCast(firstStatement, ExpressionStatementSyntax)
If Not expressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then
Return True
End If
Dim invocation = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax)
If Not invocation.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Return True
End If
Dim memberAccess = DirectCast(invocation.Expression, MemberAccessExpressionSyntax)
If Not memberAccess.Name.IsKind(SyntaxKind.IdentifierName) OrElse
Not memberAccess.Name.Identifier.IsKind(SyntaxKind.IdentifierToken) Then
Return True
End If
' Note that ValueText returns "New" for both New and [New]
If Not String.Equals(memberAccess.Name.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Return memberAccess.Expression.IsKind(SyntaxKind.MyBaseKeyword)
End Function
Friend Overrides Function IsPartial(type As INamedTypeSymbol) As Boolean
Dim syntaxRefs = type.DeclaringSyntaxReferences
Return syntaxRefs.Length > 1 OrElse
DirectCast(syntaxRefs.Single().GetSyntax(), TypeStatementSyntax).Modifiers.Any(SyntaxKind.PartialKeyword)
End Function
Protected Overrides Function GetSymbolEdits(
editKind As EditKind,
oldNode As SyntaxNode,
newNode As SyntaxNode,
oldModel As SemanticModel,
newModel As SemanticModel,
editMap As IReadOnlyDictionary(Of SyntaxNode, EditKind),
cancellationToken As CancellationToken) As OneOrMany(Of (oldSymbol As ISymbol, newSymbol As ISymbol, editKind As EditKind))
Dim oldSymbols As OneOrMany(Of ISymbol) = Nothing
Dim newSymbols As OneOrMany(Of ISymbol) = Nothing
If editKind = EditKind.Delete Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return oldSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(s, Nothing, editKind))
End If
If editKind = EditKind.Insert Then
If Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
Return newSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(Nothing, s, editKind))
End If
If editKind = EditKind.Update Then
If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) OrElse
Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then
Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty
End If
If oldSymbols.Count = 1 AndAlso newSymbols.Count = 1 Then
Return OneOrMany.Create((oldSymbols(0), newSymbols(0), editKind))
End If
' This only occurs when field identifiers are deleted/inserted/reordered from/to/within their variable declarator list,
' or their shared initializer is updated. The particular inserted and deleted fields will be represented by separate edits,
' but the AsNew clause of the declarator may have been updated as well, which needs to update the remaining (matching) fields.
Dim builder = ArrayBuilder(Of (ISymbol, ISymbol, EditKind)).GetInstance()
For Each oldSymbol In oldSymbols
Dim newSymbol = newSymbols.FirstOrDefault(Function(s, o) CaseInsensitiveComparison.Equals(s.Name, o.Name), oldSymbol)
If newSymbol IsNot Nothing Then
builder.Add((oldSymbol, newSymbol, editKind))
End If
Next
Return OneOrMany.Create(builder.ToImmutableAndFree())
End If
Throw ExceptionUtilities.UnexpectedValue(editKind)
End Function
Private Shared Function TryGetSyntaxNodesForEdit(
editKind As EditKind,
node As SyntaxNode,
model As SemanticModel,
<Out> ByRef symbols As OneOrMany(Of ISymbol),
cancellationToken As CancellationToken) As Boolean
Select Case node.Kind()
Case SyntaxKind.ImportsStatement,
SyntaxKind.NamespaceStatement,
SyntaxKind.NamespaceBlock
Return False
Case SyntaxKind.VariableDeclarator
Dim variableDeclarator = CType(node, VariableDeclaratorSyntax)
If variableDeclarator.Names.Count > 1 Then
symbols = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) model.GetDeclaredSymbol(n, cancellationToken)))
Return True
End If
node = variableDeclarator.Names(0)
Case SyntaxKind.FieldDeclaration
If editKind = EditKind.Update Then
Dim field = CType(node, FieldDeclarationSyntax)
If field.Declarators.Count = 1 AndAlso field.Declarators(0).Names.Count = 1 Then
node = field.Declarators(0).Names(0)
Else
symbols = OneOrMany.Create(
(From declarator In field.Declarators
From name In declarator.Names
Select model.GetDeclaredSymbol(name, cancellationToken)).ToImmutableArray())
Return True
End If
End If
End Select
Dim symbol = model.GetDeclaredSymbol(node, cancellationToken)
If symbol Is Nothing Then
Return False
End If
' Ignore partial method definition parts.
' Partial method that does not have implementation part is not emitted to metadata.
' Partial method without a definition part is a compilation error.
If symbol.Kind = SymbolKind.Method AndAlso CType(symbol, IMethodSymbol).IsPartialDefinition Then
Return False
End If
symbols = OneOrMany.Create(symbol)
Return True
End Function
Friend Overrides Function ContainsLambda(declaration As SyntaxNode) As Boolean
Return declaration.DescendantNodes().Any(AddressOf LambdaUtilities.IsLambda)
End Function
Friend Overrides Function IsLambda(node As SyntaxNode) As Boolean
Return LambdaUtilities.IsLambda(node)
End Function
Friend Overrides Function IsNestedFunction(node As SyntaxNode) As Boolean
Return TypeOf node Is LambdaExpressionSyntax
End Function
Friend Overrides Function IsLocalFunction(node As SyntaxNode) As Boolean
Return False
End Function
Friend Overrides Function TryGetLambdaBodies(node As SyntaxNode, ByRef body1 As SyntaxNode, ByRef body2 As SyntaxNode) As Boolean
Return LambdaUtilities.TryGetLambdaBodies(node, body1, body2)
End Function
Friend Overrides Function GetLambda(lambdaBody As SyntaxNode) As SyntaxNode
Return LambdaUtilities.GetLambda(lambdaBody)
End Function
Protected Overrides Function GetLambdaBodyExpressionsAndStatements(lambdaBody As SyntaxNode) As IEnumerable(Of SyntaxNode)
Return LambdaUtilities.GetLambdaBodyExpressionsAndStatements(lambdaBody)
End Function
Friend Overrides Function GetLambdaExpressionSymbol(model As SemanticModel, lambdaExpression As SyntaxNode, cancellationToken As CancellationToken) As IMethodSymbol
Dim lambdaExpressionSyntax = DirectCast(lambdaExpression, LambdaExpressionSyntax)
' The semantic model only returns the lambda symbol for positions that are within the body of the lambda (not the header)
Return DirectCast(model.GetEnclosingSymbol(lambdaExpressionSyntax.SubOrFunctionHeader.Span.End, cancellationToken), IMethodSymbol)
End Function
Friend Overrides Function GetContainingQueryExpression(node As SyntaxNode) As SyntaxNode
Return node.FirstAncestorOrSelf(Of QueryExpressionSyntax)
End Function
Friend Overrides Function QueryClauseLambdasTypeEquivalent(oldModel As SemanticModel, oldNode As SyntaxNode, newModel As SemanticModel, newNode As SyntaxNode, cancellationToken As CancellationToken) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.AggregateClause
Dim oldInfo = oldModel.GetAggregateClauseSymbolInfo(DirectCast(oldNode, AggregateClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetAggregateClauseSymbolInfo(DirectCast(newNode, AggregateClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Select1.Symbol, newInfo.Select1.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.Select2.Symbol, newInfo.Select2.Symbol)
Case SyntaxKind.CollectionRangeVariable
Dim oldInfo = oldModel.GetCollectionRangeVariableSymbolInfo(DirectCast(oldNode, CollectionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetCollectionRangeVariableSymbolInfo(DirectCast(newNode, CollectionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.AsClauseConversion.Symbol, newInfo.AsClauseConversion.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.SelectMany.Symbol, newInfo.SelectMany.Symbol) AndAlso
MemberSignaturesEquivalent(oldInfo.ToQueryableCollectionConversion.Symbol, newInfo.ToQueryableCollectionConversion.Symbol)
Case SyntaxKind.FunctionAggregation
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, FunctionAggregationSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, FunctionAggregationSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.ExpressionRangeVariable
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, ExpressionRangeVariableSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, ExpressionRangeVariableSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, OrderingSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, OrderingSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case SyntaxKind.FromClause,
SyntaxKind.WhereClause,
SyntaxKind.SkipClause,
SyntaxKind.TakeClause,
SyntaxKind.SkipWhileClause,
SyntaxKind.TakeWhileClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause,
SyntaxKind.SelectClause
Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, QueryClauseSyntax), cancellationToken)
Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, QueryClauseSyntax), cancellationToken)
Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol)
Case Else
Return True
End Select
End Function
Protected Overrides Sub ReportLocalFunctionsDeclarationRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), bodyMatch As Match(Of SyntaxNode))
' VB has no local functions so we don't have anything to report
End Sub
#End Region
#Region "Diagnostic Info"
Protected Overrides ReadOnly Property ErrorDisplayFormat As SymbolDisplayFormat
Get
Return SymbolDisplayFormat.VisualBasicShortErrorMessageFormat
End Get
End Property
Protected Overrides Function TryGetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return If(TryGetDiagnosticSpanImpl(node, editKind), node.Span)
End Function
Private Shared Function TryGetDiagnosticSpanImpl(node As SyntaxNode, editKind As EditKind) As TextSpan?
Return TryGetDiagnosticSpanImpl(node.Kind, node, editKind)
End Function
Protected Overrides Function GetBodyDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan
Return GetDiagnosticSpan(node, editKind)
End Function
' internal for testing; kind is passed explicitly for testing as well
Friend Shared Function TryGetDiagnosticSpanImpl(kind As SyntaxKind, node As SyntaxNode, editKind As EditKind) As TextSpan?
Select Case kind
Case SyntaxKind.CompilationUnit
Return New TextSpan()
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement
Return node.Span
Case SyntaxKind.NamespaceBlock
Return GetDiagnosticSpan(DirectCast(node, NamespaceBlockSyntax).NamespaceStatement)
Case SyntaxKind.NamespaceStatement
Return GetDiagnosticSpan(DirectCast(node, NamespaceStatementSyntax))
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock
Return GetDiagnosticSpan(DirectCast(node, TypeBlockSyntax).BlockStatement)
Case SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement
Return GetDiagnosticSpan(DirectCast(node, TypeStatementSyntax))
Case SyntaxKind.EnumBlock
Return TryGetDiagnosticSpanImpl(DirectCast(node, EnumBlockSyntax).EnumStatement, editKind)
Case SyntaxKind.EnumStatement
Dim enumStatement = DirectCast(node, EnumStatementSyntax)
Return GetDiagnosticSpan(enumStatement.Modifiers, enumStatement.EnumKeyword, enumStatement.Identifier)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetDiagnosticSpan(DirectCast(node, MethodBlockBaseSyntax).BlockStatement)
Case SyntaxKind.EventBlock
Return GetDiagnosticSpan(DirectCast(node, EventBlockSyntax).EventStatement)
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.EventStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return GetDiagnosticSpan(DirectCast(node, MethodBaseSyntax))
Case SyntaxKind.PropertyBlock
Return GetDiagnosticSpan(DirectCast(node, PropertyBlockSyntax).PropertyStatement)
Case SyntaxKind.PropertyStatement
Return GetDiagnosticSpan(DirectCast(node, PropertyStatementSyntax))
Case SyntaxKind.FieldDeclaration
Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax)
Return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declarators.First, fieldDeclaration.Declarators.Last)
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier,
SyntaxKind.EnumMemberDeclaration,
SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return node.Span
Case SyntaxKind.TypeParameter
Return DirectCast(node, TypeParameterSyntax).Identifier.Span
Case SyntaxKind.TypeParameterList,
SyntaxKind.ParameterList,
SyntaxKind.AttributeList,
SyntaxKind.SimpleAsClause
If editKind = EditKind.Delete Then
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Else
Return node.Span
End If
Case SyntaxKind.AttributesStatement,
SyntaxKind.Attribute
Return node.Span
Case SyntaxKind.Parameter
Dim parameter = DirectCast(node, ParameterSyntax)
Return GetDiagnosticSpan(parameter.Modifiers, parameter.Identifier, parameter)
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return GetDiagnosticSpan(DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader)
Case SyntaxKind.MultiLineIfBlock
Dim ifStatement = DirectCast(node, MultiLineIfBlockSyntax).IfStatement
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.ElseIfBlock
Dim elseIfStatement = DirectCast(node, ElseIfBlockSyntax).ElseIfStatement
Return GetDiagnosticSpan(elseIfStatement.ElseIfKeyword, elseIfStatement.Condition, elseIfStatement.ThenKeyword)
Case SyntaxKind.SingleLineIfStatement
Dim ifStatement = DirectCast(node, SingleLineIfStatementSyntax)
Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword)
Case SyntaxKind.SingleLineElseClause
Return DirectCast(node, SingleLineElseClauseSyntax).ElseKeyword.Span
Case SyntaxKind.TryBlock
Return DirectCast(node, TryBlockSyntax).TryStatement.TryKeyword.Span
Case SyntaxKind.CatchBlock
Return DirectCast(node, CatchBlockSyntax).CatchStatement.CatchKeyword.Span
Case SyntaxKind.FinallyBlock
Return DirectCast(node, FinallyBlockSyntax).FinallyStatement.FinallyKeyword.Span
Case SyntaxKind.SyncLockBlock
Return DirectCast(node, SyncLockBlockSyntax).SyncLockStatement.Span
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).WithStatement.Span
Case SyntaxKind.UsingBlock
Return DirectCast(node, UsingBlockSyntax).UsingStatement.Span
Case SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock,
SyntaxKind.DoUntilLoopBlock,
SyntaxKind.DoLoopWhileBlock,
SyntaxKind.DoLoopUntilBlock
Return DirectCast(node, DoLoopBlockSyntax).DoStatement.Span
Case SyntaxKind.WhileBlock
Return DirectCast(node, WhileBlockSyntax).WhileStatement.Span
Case SyntaxKind.ForEachBlock,
SyntaxKind.ForBlock
Return DirectCast(node, ForOrForEachBlockSyntax).ForOrForEachStatement.Span
Case SyntaxKind.AwaitExpression
Return DirectCast(node, AwaitExpressionSyntax).AwaitKeyword.Span
Case SyntaxKind.AnonymousObjectCreationExpression
Dim newWith = DirectCast(node, AnonymousObjectCreationExpressionSyntax)
Return TextSpan.FromBounds(newWith.NewKeyword.Span.Start,
newWith.Initializer.WithKeyword.Span.End)
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span
Case SyntaxKind.QueryExpression
Return TryGetDiagnosticSpanImpl(DirectCast(node, QueryExpressionSyntax).Clauses.First(), editKind)
Case SyntaxKind.WhereClause
Return DirectCast(node, WhereClauseSyntax).WhereKeyword.Span
Case SyntaxKind.SelectClause
Return DirectCast(node, SelectClauseSyntax).SelectKeyword.Span
Case SyntaxKind.FromClause
Return DirectCast(node, FromClauseSyntax).FromKeyword.Span
Case SyntaxKind.AggregateClause
Return DirectCast(node, AggregateClauseSyntax).AggregateKeyword.Span
Case SyntaxKind.LetClause
Return DirectCast(node, LetClauseSyntax).LetKeyword.Span
Case SyntaxKind.SimpleJoinClause
Return DirectCast(node, SimpleJoinClauseSyntax).JoinKeyword.Span
Case SyntaxKind.GroupJoinClause
Dim groupJoin = DirectCast(node, GroupJoinClauseSyntax)
Return TextSpan.FromBounds(groupJoin.GroupKeyword.SpanStart, groupJoin.JoinKeyword.Span.End)
Case SyntaxKind.GroupByClause
Return DirectCast(node, GroupByClauseSyntax).GroupKeyword.Span
Case SyntaxKind.FunctionAggregation
Return node.Span
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDiagnosticSpanImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause,
SyntaxKind.SkipWhileClause
Dim partition = DirectCast(node, PartitionWhileClauseSyntax)
Return TextSpan.FromBounds(partition.SkipOrTakeKeyword.SpanStart, partition.WhileKeyword.Span.End)
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return node.Span
Case SyntaxKind.JoinCondition
Return DirectCast(node, JoinConditionSyntax).EqualsKeyword.Span
Case Else
Return node.Span
End Select
End Function
Private Overloads Shared Function GetDiagnosticSpan(ifKeyword As SyntaxToken, condition As SyntaxNode, thenKeywordOpt As SyntaxToken) As TextSpan
Return TextSpan.FromBounds(ifKeyword.Span.Start,
If(thenKeywordOpt.RawKind <> 0, thenKeywordOpt.Span.End, condition.Span.End))
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As NamespaceStatementSyntax) As TextSpan
Return TextSpan.FromBounds(node.NamespaceKeyword.SpanStart, node.Name.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(node As TypeStatementSyntax) As TextSpan
Return GetDiagnosticSpan(node.Modifiers,
node.DeclarationKeyword,
If(node.TypeParameterList, CType(node.Identifier, SyntaxNodeOrToken)))
End Function
Private Overloads Shared Function GetDiagnosticSpan(modifiers As SyntaxTokenList, start As SyntaxNodeOrToken, endNode As SyntaxNodeOrToken) As TextSpan
Return TextSpan.FromBounds(If(modifiers.Count <> 0, modifiers.First.SpanStart, start.SpanStart),
endNode.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(header As MethodBaseSyntax) As TextSpan
Dim startToken As SyntaxToken
Dim endToken As SyntaxToken
If header.Modifiers.Count > 0 Then
startToken = header.Modifiers.First
Else
Select Case header.Kind
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
startToken = DirectCast(header, DelegateStatementSyntax).DelegateKeyword
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
startToken = DirectCast(header, DeclareStatementSyntax).DeclareKeyword
Case Else
startToken = header.DeclarationKeyword
End Select
End If
If header.ParameterList IsNot Nothing Then
endToken = header.ParameterList.CloseParenToken
Else
Select Case header.Kind
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
endToken = DirectCast(header, MethodStatementSyntax).Identifier
Case SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
endToken = DirectCast(header, DeclareStatementSyntax).LibraryName.Token
Case SyntaxKind.OperatorStatement
endToken = DirectCast(header, OperatorStatementSyntax).OperatorToken
Case SyntaxKind.SubNewStatement
endToken = DirectCast(header, SubNewStatementSyntax).NewKeyword
Case SyntaxKind.PropertyStatement
endToken = DirectCast(header, PropertyStatementSyntax).Identifier
Case SyntaxKind.EventStatement
endToken = DirectCast(header, EventStatementSyntax).Identifier
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
endToken = DirectCast(header, DelegateStatementSyntax).Identifier
Case SyntaxKind.SetAccessorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
endToken = header.DeclarationKeyword
Case Else
Throw ExceptionUtilities.UnexpectedValue(header.Kind)
End Select
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Private Overloads Shared Function GetDiagnosticSpan(lambda As LambdaHeaderSyntax) As TextSpan
Dim startToken = If(lambda.Modifiers.Count <> 0, lambda.Modifiers.First, lambda.DeclarationKeyword)
Dim endToken As SyntaxToken
If lambda.ParameterList IsNot Nothing Then
endToken = lambda.ParameterList.CloseParenToken
Else
endToken = lambda.DeclarationKeyword
End If
Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End)
End Function
Friend Overrides Function GetLambdaParameterDiagnosticSpan(lambda As SyntaxNode, ordinal As Integer) As TextSpan
Select Case lambda.Kind
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return DirectCast(lambda, LambdaExpressionSyntax).SubOrFunctionHeader.ParameterList.Parameters(ordinal).Identifier.Span
Case Else
Return lambda.Span
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As INamedTypeSymbol) As String
Select Case symbol.TypeKind
Case TypeKind.Structure
Return VBFeaturesResources.structure_
Case TypeKind.Module
Return VBFeaturesResources.module_
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IMethodSymbol) As String
Select Case symbol.MethodKind
Case MethodKind.StaticConstructor
Return VBFeaturesResources.Shared_constructor
Case Else
Return MyBase.GetDisplayName(symbol)
End Select
End Function
Friend Overrides Function GetDisplayName(symbol As IPropertySymbol) As String
If symbol.IsWithEvents Then
Return VBFeaturesResources.WithEvents_field
End If
Return MyBase.GetDisplayName(symbol)
End Function
Protected Overrides Function TryGetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Return TryGetDisplayNameImpl(node, editKind)
End Function
Protected Overloads Shared Function GetDisplayName(node As SyntaxNode, editKind As EditKind) As String
Dim result = TryGetDisplayNameImpl(node, editKind)
If result Is Nothing Then
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End If
Return result
End Function
Protected Overrides Function GetBodyDisplayName(node As SyntaxNode, Optional editKind As EditKind = EditKind.Update) As String
Return GetDisplayName(node, editKind)
End Function
Private Shared Function TryGetDisplayNameImpl(node As SyntaxNode, editKind As EditKind) As String
Select Case node.Kind
' top-level
Case SyntaxKind.OptionStatement
Return VBFeaturesResources.option_
Case SyntaxKind.ImportsStatement
Return VBFeaturesResources.import
Case SyntaxKind.NamespaceBlock,
SyntaxKind.NamespaceStatement
Return FeaturesResources.namespace_
Case SyntaxKind.ClassBlock,
SyntaxKind.ClassStatement
Return FeaturesResources.class_
Case SyntaxKind.StructureBlock,
SyntaxKind.StructureStatement
Return VBFeaturesResources.structure_
Case SyntaxKind.InterfaceBlock,
SyntaxKind.InterfaceStatement
Return FeaturesResources.interface_
Case SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement
Return VBFeaturesResources.module_
Case SyntaxKind.EnumBlock,
SyntaxKind.EnumStatement
Return FeaturesResources.enum_
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return FeaturesResources.delegate_
Case SyntaxKind.FieldDeclaration
Dim declaration = DirectCast(node, FieldDeclarationSyntax)
Return If(declaration.Modifiers.Any(SyntaxKind.WithEventsKeyword), VBFeaturesResources.WithEvents_field,
If(declaration.Modifiers.Any(SyntaxKind.ConstKeyword), FeaturesResources.const_field, FeaturesResources.field))
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement
Return FeaturesResources.method
Case SyntaxKind.OperatorBlock,
SyntaxKind.OperatorStatement
Return FeaturesResources.operator_
Case SyntaxKind.ConstructorBlock
Return If(CType(node, ConstructorBlockSyntax).SubNewStatement.Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.SubNewStatement
Return If(CType(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor)
Case SyntaxKind.PropertyBlock
Return FeaturesResources.property_
Case SyntaxKind.PropertyStatement
Return If(node.IsParentKind(SyntaxKind.PropertyBlock),
FeaturesResources.property_,
FeaturesResources.auto_property)
Case SyntaxKind.EventBlock,
SyntaxKind.EventStatement
Return FeaturesResources.event_
Case SyntaxKind.EnumMemberDeclaration
Return FeaturesResources.enum_value
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
Return FeaturesResources.property_accessor
Case SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return FeaturesResources.event_accessor
Case SyntaxKind.TypeParameterSingleConstraintClause,
SyntaxKind.TypeParameterMultipleConstraintClause,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint
Return FeaturesResources.type_constraint
Case SyntaxKind.SimpleAsClause
Return VBFeaturesResources.as_clause
Case SyntaxKind.TypeParameterList
Return VBFeaturesResources.type_parameters
Case SyntaxKind.TypeParameter
Return FeaturesResources.type_parameter
Case SyntaxKind.ParameterList
Return VBFeaturesResources.parameters
Case SyntaxKind.Parameter
Return FeaturesResources.parameter
Case SyntaxKind.AttributeList,
SyntaxKind.AttributesStatement
Return VBFeaturesResources.attributes
Case SyntaxKind.Attribute
Return FeaturesResources.attribute
' statement-level
Case SyntaxKind.TryBlock
Return VBFeaturesResources.Try_block
Case SyntaxKind.CatchBlock
Return VBFeaturesResources.Catch_clause
Case SyntaxKind.FinallyBlock
Return VBFeaturesResources.Finally_clause
Case SyntaxKind.UsingBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.Using_statement, VBFeaturesResources.Using_block)
Case SyntaxKind.WithBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.With_statement, VBFeaturesResources.With_block)
Case SyntaxKind.SyncLockBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.SyncLock_statement, VBFeaturesResources.SyncLock_block)
Case SyntaxKind.ForEachBlock
Return If(editKind = EditKind.Update, VBFeaturesResources.For_Each_statement, VBFeaturesResources.For_Each_block)
Case SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.OnErrorGoToLabelStatement
Return VBFeaturesResources.On_Error_statement
Case SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return VBFeaturesResources.Resume_statement
Case SyntaxKind.YieldStatement
Return VBFeaturesResources.Yield_statement
Case SyntaxKind.AwaitExpression
Return VBFeaturesResources.Await_expression
Case SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader
Return VBFeaturesResources.Lambda
Case SyntaxKind.WhereClause
Return VBFeaturesResources.Where_clause
Case SyntaxKind.SelectClause
Return VBFeaturesResources.Select_clause
Case SyntaxKind.FromClause
Return VBFeaturesResources.From_clause
Case SyntaxKind.AggregateClause
Return VBFeaturesResources.Aggregate_clause
Case SyntaxKind.LetClause
Return VBFeaturesResources.Let_clause
Case SyntaxKind.SimpleJoinClause
Return VBFeaturesResources.Join_clause
Case SyntaxKind.GroupJoinClause
Return VBFeaturesResources.Group_Join_clause
Case SyntaxKind.GroupByClause
Return VBFeaturesResources.Group_By_clause
Case SyntaxKind.FunctionAggregation
Return VBFeaturesResources.Function_aggregation
Case SyntaxKind.CollectionRangeVariable,
SyntaxKind.ExpressionRangeVariable
Return TryGetDisplayNameImpl(node.Parent, editKind)
Case SyntaxKind.TakeWhileClause
Return VBFeaturesResources.Take_While_clause
Case SyntaxKind.SkipWhileClause
Return VBFeaturesResources.Skip_While_clause
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return VBFeaturesResources.Ordering_clause
Case SyntaxKind.JoinCondition
Return VBFeaturesResources.Join_condition
Case Else
Return Nothing
End Select
End Function
#End Region
#Region "Top-level Syntactic Rude Edits"
Private Structure EditClassifier
Private ReadOnly _analyzer As VisualBasicEditAndContinueAnalyzer
Private ReadOnly _diagnostics As ArrayBuilder(Of RudeEditDiagnostic)
Private ReadOnly _match As Match(Of SyntaxNode)
Private ReadOnly _oldNode As SyntaxNode
Private ReadOnly _newNode As SyntaxNode
Private ReadOnly _kind As EditKind
Private ReadOnly _span As TextSpan?
Public Sub New(analyzer As VisualBasicEditAndContinueAnalyzer,
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
oldNode As SyntaxNode,
newNode As SyntaxNode,
kind As EditKind,
Optional match As Match(Of SyntaxNode) = Nothing,
Optional span As TextSpan? = Nothing)
_analyzer = analyzer
_diagnostics = diagnostics
_oldNode = oldNode
_newNode = newNode
_kind = kind
_span = span
_match = match
End Sub
Private Sub ReportError(kind As RudeEditKind)
ReportError(kind, {GetDisplayName(If(_newNode, _oldNode), EditKind.Update)})
End Sub
Private Sub ReportError(kind As RudeEditKind, args As String())
_diagnostics.Add(New RudeEditDiagnostic(kind, GetSpan(), If(_newNode, _oldNode), args))
End Sub
Private Sub ReportError(kind As RudeEditKind, spanNode As SyntaxNode, displayNode As SyntaxNode)
_diagnostics.Add(New RudeEditDiagnostic(kind, GetDiagnosticSpan(spanNode, _kind), displayNode, {GetDisplayName(displayNode, EditKind.Update)}))
End Sub
Private Function GetSpan() As TextSpan
If _span.HasValue Then
Return _span.Value
End If
If _newNode Is Nothing Then
Return _analyzer.GetDeletedNodeDiagnosticSpan(_match.Matches, _oldNode)
Else
Return GetDiagnosticSpan(_newNode, _kind)
End If
End Function
Public Sub ClassifyEdit()
Select Case _kind
Case EditKind.Delete
ClassifyDelete(_oldNode)
Return
Case EditKind.Update
ClassifyUpdate(_oldNode, _newNode)
Return
Case EditKind.Move
ClassifyMove(_newNode)
Return
Case EditKind.Insert
ClassifyInsert(_newNode)
Return
Case EditKind.Reorder
ClassifyReorder(_oldNode, _newNode)
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(_kind)
End Select
End Sub
#Region "Move and Reorder"
Private Sub ClassifyMove(newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
ReportError(RudeEditKind.Move)
End Select
End Sub
Private Sub ClassifyReorder(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.ImportsStatement,
SyntaxKind.AttributesStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.EnumBlock,
SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.DeclareSubStatement,
SyntaxKind.DeclareFunctionStatement,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.EventBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock,
SyntaxKind.ClassConstraint,
SyntaxKind.StructureConstraint,
SyntaxKind.NewConstraint,
SyntaxKind.TypeConstraint,
SyntaxKind.AttributeList,
SyntaxKind.Attribute
' We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection.
Return
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
' Interface methods. We could allow reordering of non-COM interface methods.
Debug.Assert(oldNode.Parent.IsKind(SyntaxKind.InterfaceBlock) AndAlso newNode.Parent.IsKind(SyntaxKind.InterfaceBlock))
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.PropertyStatement,
SyntaxKind.FieldDeclaration,
SyntaxKind.EventStatement
' Maybe we could allow changing order of field declarations unless the containing type layout is sequential,
' and it's not a COM interface.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.EnumMemberDeclaration
' To allow this change we would need to check that values of all fields of the enum
' are preserved, or make sure we can update all method bodies that accessed those that changed.
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.TypeParameter,
SyntaxKind.Parameter
ReportError(RudeEditKind.Move)
Return
Case SyntaxKind.ModifiedIdentifier,
SyntaxKind.VariableDeclarator
' Identifier can be moved within the same type declaration.
' Determine validity of such change in semantic analysis.
Return
Case Else
Throw ExceptionUtilities.UnexpectedValue(newNode.Kind)
End Select
End Sub
#End Region
#Region "Insert"
Private Sub ClassifyInsert(node As SyntaxNode)
Select Case node.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.AttributesStatement
' Module/assembly attribute
ReportError(RudeEditKind.Insert)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude
If node.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude
If node.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Delete"
Private Sub ClassifyDelete(oldNode As SyntaxNode)
Select Case oldNode.Kind
Case SyntaxKind.OptionStatement,
SyntaxKind.NamespaceBlock,
SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Delete)
Return
Case SyntaxKind.AttributeList
' Only module/assembly attributes are rude edits
If oldNode.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If oldNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Insert)
End If
Return
End Select
End Sub
#End Region
#Region "Update"
Private Sub ClassifyUpdate(oldNode As SyntaxNode, newNode As SyntaxNode)
Select Case newNode.Kind
Case SyntaxKind.OptionStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.NamespaceStatement
ClassifyUpdate(DirectCast(oldNode, NamespaceStatementSyntax), DirectCast(newNode, NamespaceStatementSyntax))
Return
Case SyntaxKind.AttributesStatement
ReportError(RudeEditKind.Update)
Return
Case SyntaxKind.Attribute
' Only module/assembly attributes are rude edits
If newNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then
ReportError(RudeEditKind.Update)
End If
Return
End Select
End Sub
Private Sub ClassifyUpdate(oldNode As NamespaceStatementSyntax, newNode As NamespaceStatementSyntax)
Debug.Assert(Not SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name))
ReportError(RudeEditKind.Renamed)
End Sub
Public Sub ClassifyDeclarationBodyRudeUpdates(newDeclarationOrBody As SyntaxNode)
For Each node In newDeclarationOrBody.DescendantNodesAndSelf()
Select Case node.Kind
Case SyntaxKind.AggregateClause,
SyntaxKind.GroupByClause,
SyntaxKind.SimpleJoinClause,
SyntaxKind.GroupJoinClause
ReportError(RudeEditKind.ComplexQueryExpression, node, Me._newNode)
Return
Case SyntaxKind.LocalDeclarationStatement
Dim declaration = DirectCast(node, LocalDeclarationStatementSyntax)
If declaration.Modifiers.Any(SyntaxKind.StaticKeyword) Then
ReportError(RudeEditKind.UpdateStaticLocal)
End If
End Select
Next
End Sub
#End Region
End Structure
Friend Overrides Sub ReportTopLevelSyntacticRudeEdits(
diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
edit As Edit(Of SyntaxNode),
editMap As Dictionary(Of SyntaxNode, EditKind))
' For most nodes we ignore Insert and Delete edits if their parent was also inserted or deleted, respectively.
' For ModifiedIdentifiers though we check the grandparent instead because variables can move across
' VariableDeclarators. Moving a variable from a VariableDeclarator that only has a single variable results in
' deletion of that declarator. We don't want to report that delete. Similarly for moving to a new VariableDeclarator.
If edit.Kind = EditKind.Delete AndAlso
edit.OldNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.OldNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.OldNode.Parent.Parent, EditKind.Delete) Then
Return
End If
ElseIf edit.Kind = EditKind.Insert AndAlso
edit.NewNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso
edit.NewNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then
If HasEdit(editMap, edit.NewNode.Parent.Parent, EditKind.Insert) Then
Return
End If
ElseIf HasParentEdit(editMap, edit) Then
Return
End If
Dim classifier = New EditClassifier(Me, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match)
classifier.ClassifyEdit()
End Sub
Friend Overrides Sub ReportMemberBodyUpdateRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newMember As SyntaxNode, span As TextSpan?)
Dim classifier = New EditClassifier(Me, diagnostics, Nothing, newMember, EditKind.Update, span:=span)
classifier.ClassifyDeclarationBodyRudeUpdates(newMember)
End Sub
#End Region
#Region "Semantic Rude Edits"
Protected Overrides Function AreHandledEventsEqual(oldMethod As IMethodSymbol, newMethod As IMethodSymbol) As Boolean
Return oldMethod.HandledEvents.SequenceEqual(
newMethod.HandledEvents,
Function(x, y)
Return x.HandlesKind = y.HandlesKind AndAlso
SymbolsEquivalent(x.EventContainer, y.EventContainer) AndAlso
SymbolsEquivalent(x.EventSymbol, y.EventSymbol) AndAlso
SymbolsEquivalent(x.WithEventsSourceProperty, y.WithEventsSourceProperty)
End Function)
End Function
Friend Overrides Sub ReportInsertedMemberSymbolRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newSymbol As ISymbol, newNode As SyntaxNode, insertingIntoExistingContainingType As Boolean)
Dim kind = GetInsertedMemberSymbolRudeEditKind(newSymbol, insertingIntoExistingContainingType)
If kind <> RudeEditKind.None Then
diagnostics.Add(New RudeEditDiagnostic(
kind,
GetDiagnosticSpan(newNode, EditKind.Insert),
newNode,
arguments:={GetDisplayName(newNode, EditKind.Insert)}))
End If
End Sub
Private Shared Function GetInsertedMemberSymbolRudeEditKind(newSymbol As ISymbol, insertingIntoExistingContainingType As Boolean) As RudeEditKind
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting P/Invoke into a new or existing type is not allowed.
If method.GetDllImportData() IsNot Nothing Then
Return RudeEditKind.InsertDllImport
End If
' Inserting method with handles clause into a new or existing type is not allowed.
If Not method.HandledEvents.IsEmpty Then
Return RudeEditKind.InsertHandlesClause
End If
Case SymbolKind.NamedType
Dim type = CType(newSymbol, INamedTypeSymbol)
' Inserting module is not allowed.
If type.TypeKind = TypeKind.Module Then
Return RudeEditKind.Insert
End If
End Select
' All rude edits below only apply when inserting into an existing type (not when the type itself is inserted):
If Not insertingIntoExistingContainingType Then
Return RudeEditKind.None
End If
If newSymbol.ContainingType.Arity > 0 AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertIntoGenericType
End If
' Inserting virtual or interface member is not allowed.
If (newSymbol.IsVirtual Or newSymbol.IsOverride Or newSymbol.IsAbstract) AndAlso newSymbol.Kind <> SymbolKind.NamedType Then
Return RudeEditKind.InsertVirtual
End If
Select Case newSymbol.Kind
Case SymbolKind.Method
Dim method = DirectCast(newSymbol, IMethodSymbol)
' Inserting generic method into an existing type is not allowed.
If method.Arity > 0 Then
Return RudeEditKind.InsertGenericMethod
End If
' Inserting operator to an existing type is not allowed.
If method.MethodKind = MethodKind.Conversion OrElse method.MethodKind = MethodKind.UserDefinedOperator Then
Return RudeEditKind.InsertOperator
End If
Return RudeEditKind.None
Case SymbolKind.Field
' Inserting a field into an enum is not allowed.
If newSymbol.ContainingType.TypeKind = TypeKind.Enum Then
Return RudeEditKind.Insert
End If
Return RudeEditKind.None
End Select
Return RudeEditKind.None
End Function
#End Region
#Region "Exception Handling Rude Edits"
Protected Overrides Function GetExceptionHandlingAncestors(node As SyntaxNode, isNonLeaf As Boolean) As List(Of SyntaxNode)
Dim result = New List(Of SyntaxNode)()
While node IsNot Nothing
Dim kind = node.Kind
Select Case kind
Case SyntaxKind.TryBlock
If isNonLeaf Then
result.Add(node)
End If
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
result.Add(node)
Debug.Assert(node.Parent.Kind = SyntaxKind.TryBlock)
node = node.Parent
Case SyntaxKind.ClassBlock,
SyntaxKind.StructureBlock
' stop at type declaration
Exit While
End Select
' stop at lambda
If LambdaUtilities.IsLambda(node) Then
Exit While
End If
node = node.Parent
End While
Return result
End Function
Friend Overrides Sub ReportEnclosingExceptionHandlingRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
exceptionHandlingEdits As IEnumerable(Of Edit(Of SyntaxNode)),
oldStatement As SyntaxNode,
newStatementSpan As TextSpan)
For Each edit In exceptionHandlingEdits
Debug.Assert(edit.Kind <> EditKind.Update OrElse edit.OldNode.RawKind = edit.NewNode.RawKind)
If edit.Kind <> EditKind.Update OrElse Not AreExceptionHandlingPartsEquivalent(edit.OldNode, edit.NewNode) Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan)
End If
Next
End Sub
Private Shared Function AreExceptionHandlingPartsEquivalent(oldNode As SyntaxNode, newNode As SyntaxNode) As Boolean
Select Case oldNode.Kind
Case SyntaxKind.TryBlock
Dim oldTryBlock = DirectCast(oldNode, TryBlockSyntax)
Dim newTryBlock = DirectCast(newNode, TryBlockSyntax)
Return SyntaxFactory.AreEquivalent(oldTryBlock.FinallyBlock, newTryBlock.FinallyBlock) AndAlso
SyntaxFactory.AreEquivalent(oldTryBlock.CatchBlocks, newTryBlock.CatchBlocks)
Case SyntaxKind.CatchBlock,
SyntaxKind.FinallyBlock
Return SyntaxFactory.AreEquivalent(oldNode, newNode)
Case Else
Throw ExceptionUtilities.UnexpectedValue(oldNode.Kind)
End Select
End Function
''' <summary>
''' An active statement (leaf or not) inside a "Catch" makes the Catch part readonly.
''' An active statement (leaf or not) inside a "Finally" makes the whole Try/Catch/Finally part read-only.
''' An active statement (non leaf) inside a "Try" makes the Catch/Finally part read-only.
''' </summary>
Protected Overrides Function GetExceptionHandlingRegion(node As SyntaxNode, <Out> ByRef coversAllChildren As Boolean) As TextSpan
Select Case node.Kind
Case SyntaxKind.TryBlock
Dim tryBlock = DirectCast(node, TryBlockSyntax)
coversAllChildren = False
If tryBlock.CatchBlocks.Count = 0 Then
Debug.Assert(tryBlock.FinallyBlock IsNot Nothing)
Return TextSpan.FromBounds(tryBlock.FinallyBlock.SpanStart, tryBlock.EndTryStatement.Span.End)
End If
Return TextSpan.FromBounds(tryBlock.CatchBlocks.First().SpanStart, tryBlock.EndTryStatement.Span.End)
Case SyntaxKind.CatchBlock
coversAllChildren = True
Return node.Span
Case SyntaxKind.FinallyBlock
coversAllChildren = True
Return DirectCast(node.Parent, TryBlockSyntax).Span
Case Else
Throw ExceptionUtilities.UnexpectedValue(node.Kind)
End Select
End Function
#End Region
#Region "State Machines"
Friend Overrides Function IsStateMachineMethod(declaration As SyntaxNode) As Boolean
Return SyntaxUtilities.IsAsyncMethodOrLambda(declaration) OrElse
SyntaxUtilities.IsIteratorMethodOrLambda(declaration)
End Function
Protected Overrides Sub GetStateMachineInfo(body As SyntaxNode, ByRef suspensionPoints As ImmutableArray(Of SyntaxNode), ByRef kind As StateMachineKinds)
' In VB declaration and body are represented by the same node for both lambdas and methods (unlike C#)
If SyntaxUtilities.IsAsyncMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetAwaitExpressions(body)
kind = StateMachineKinds.Async
ElseIf SyntaxUtilities.IsIteratorMethodOrLambda(body) Then
suspensionPoints = SyntaxUtilities.GetYieldStatements(body)
kind = StateMachineKinds.Iterator
Else
suspensionPoints = ImmutableArray(Of SyntaxNode).Empty
kind = StateMachineKinds.None
End If
End Sub
Friend Overrides Sub ReportStateMachineSuspensionPointRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode)
' TODO: changes around suspension points (foreach, lock, using, etc.)
If newNode.IsKind(SyntaxKind.AwaitExpression) Then
Dim oldContainingStatementPart = FindContainingStatementPart(oldNode)
Dim newContainingStatementPart = FindContainingStatementPart(newNode)
' If the old statement has spilled state and the new doesn't, the edit is ok. We'll just not use the spilled state.
If Not SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) AndAlso
Not HasNoSpilledState(newNode, newContainingStatementPart) Then
diagnostics.Add(New RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span))
End If
End If
End Sub
Private Shared Function FindContainingStatementPart(node As SyntaxNode) As SyntaxNode
Dim statement = TryCast(node, StatementSyntax)
While statement Is Nothing
Select Case node.Parent.Kind()
Case SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.IfStatement,
SyntaxKind.WhileStatement,
SyntaxKind.SimpleDoStatement,
SyntaxKind.SelectStatement,
SyntaxKind.UsingStatement
Return node
End Select
If LambdaUtilities.IsLambdaBodyStatementOrExpression(node) Then
Return node
End If
node = node.Parent
statement = TryCast(node, StatementSyntax)
End While
Return statement
End Function
Private Shared Function HasNoSpilledState(awaitExpression As SyntaxNode, containingStatementPart As SyntaxNode) As Boolean
Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression))
' There is nothing within the statement part surrounding the await expression.
If containingStatementPart Is awaitExpression Then
Return True
End If
Select Case containingStatementPart.Kind()
Case SyntaxKind.ExpressionStatement,
SyntaxKind.ReturnStatement
Dim expression = GetExpressionFromStatementPart(containingStatementPart)
' Await <expr>
' Return Await <expr>
If expression Is awaitExpression Then
Return True
End If
' <ident> = Await <expr>
' Return <ident> = Await <expr>
Return IsSimpleAwaitAssignment(expression, awaitExpression)
Case SyntaxKind.VariableDeclarator
' <ident> = Await <expr> in using, for, etc
' EqualsValue -> VariableDeclarator
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LoopUntilStatement,
SyntaxKind.LoopWhileStatement,
SyntaxKind.DoUntilStatement,
SyntaxKind.DoWhileStatement
' Until Await <expr>
' UntilClause -> LoopUntilStatement
Return awaitExpression.Parent.Parent Is containingStatementPart
Case SyntaxKind.LocalDeclarationStatement
' Dim <ident> = Await <expr>
' EqualsValue -> VariableDeclarator -> LocalDeclarationStatement
Return awaitExpression.Parent.Parent.Parent Is containingStatementPart
End Select
Return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression)
End Function
Private Shared Function GetExpressionFromStatementPart(statement As SyntaxNode) As ExpressionSyntax
Select Case statement.Kind()
Case SyntaxKind.ExpressionStatement
Return DirectCast(statement, ExpressionStatementSyntax).Expression
Case SyntaxKind.ReturnStatement
Return DirectCast(statement, ReturnStatementSyntax).Expression
Case Else
Throw ExceptionUtilities.UnexpectedValue(statement.Kind())
End Select
End Function
Private Shared Function IsSimpleAwaitAssignment(node As SyntaxNode, awaitExpression As SyntaxNode) As Boolean
If node.IsKind(SyntaxKind.SimpleAssignmentStatement) Then
Dim assignment = DirectCast(node, AssignmentStatementSyntax)
Return assignment.Left.IsKind(SyntaxKind.IdentifierName) AndAlso assignment.Right Is awaitExpression
End If
Return False
End Function
#End Region
#Region "Rude Edits around Active Statement"
Friend Overrides Sub ReportOtherRudeEditsAroundActiveStatement(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode,
isNonLeaf As Boolean)
Dim onErrorOrResumeStatement = FindOnErrorOrResumeStatement(match.NewRoot)
If onErrorOrResumeStatement IsNot Nothing Then
AddAroundActiveStatementRudeDiagnostic(diagnostics, oldActiveStatement, onErrorOrResumeStatement, newActiveStatement.Span)
End If
ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement)
End Sub
Private Shared Function FindOnErrorOrResumeStatement(newDeclarationOrBody As SyntaxNode) As SyntaxNode
For Each node In newDeclarationOrBody.DescendantNodes(AddressOf ChildrenCompiledInBody)
Select Case node.Kind
Case SyntaxKind.OnErrorGoToLabelStatement,
SyntaxKind.OnErrorGoToMinusOneStatement,
SyntaxKind.OnErrorGoToZeroStatement,
SyntaxKind.OnErrorResumeNextStatement,
SyntaxKind.ResumeStatement,
SyntaxKind.ResumeNextStatement,
SyntaxKind.ResumeLabelStatement
Return node
End Select
Next
Return Nothing
End Function
Private Sub ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics As ArrayBuilder(Of RudeEditDiagnostic),
match As Match(Of SyntaxNode),
oldActiveStatement As SyntaxNode,
newActiveStatement As SyntaxNode)
' Rude Edits for Using/SyncLock/With/ForEach statements that are added/updated around an active statement.
' Although such changes are technically possible, they might lead to confusion since
' the temporary variables these statements generate won't be properly initialized.
'
' We use a simple algorithm to match each New node with its old counterpart.
' If all nodes match this algorithm Is linear, otherwise it's quadratic.
'
' Unlike exception regions matching where we use LCS, we allow reordering of the statements.
ReportUnmatchedStatements(Of SyncLockBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.SyncLockBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.SyncLockStatement.Expression, n2.SyncLockStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of WithBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.WithBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.WithStatement.Expression, n2.WithStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of UsingBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.UsingBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.UsingStatement.Expression, n2.UsingStatement.Expression),
areSimilar:=Nothing)
ReportUnmatchedStatements(Of ForOrForEachBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.ForEachBlock), oldActiveStatement, newActiveStatement,
areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.ForOrForEachStatement, n2.ForOrForEachStatement),
areSimilar:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(DirectCast(n1.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable,
DirectCast(n2.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable))
End Sub
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Parser/ParseInterpolatedString.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory
'
'============ Methods for parsing portions of executable statements ==
'
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Parser
Private Function ParseInterpolatedStringExpression() As InterpolatedStringExpressionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.DollarSignDoubleQuoteToken, "ParseInterpolatedStringExpression called on the wrong token.")
ResetCurrentToken(ScannerState.InterpolatedStringPunctuation)
Debug.Assert(CurrentToken.Kind = SyntaxKind.DollarSignDoubleQuoteToken, "Rescanning $"" failed.")
Dim dollarSignDoubleQuoteToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.InterpolatedStringContent)
Dim contentBuilder = _pool.Allocate(Of InterpolatedStringContentSyntax)
Dim doubleQuoteToken As PunctuationSyntax
Dim skipped As SyntaxListBuilder(Of SyntaxToken) = Nothing
Do
Dim content As InterpolatedStringContentSyntax
Select Case CurrentToken.Kind
Case SyntaxKind.InterpolatedStringTextToken
Dim textToken = DirectCast(CurrentToken, InterpolatedStringTextTokenSyntax)
' At this point we're either right before an {, an } (error), or a "".
GetNextToken(ScannerState.InterpolatedStringPunctuation)
Debug.Assert(CurrentToken.Kind <> SyntaxKind.InterpolatedStringTextToken,
"Two interpolated string text literal tokens encountered back-to-back. " &
"Scanner should have scanned these as a single token.")
content = SyntaxFactory.InterpolatedStringText(textToken)
Case SyntaxKind.OpenBraceToken
content = ParseInterpolatedStringInterpolation()
Case SyntaxKind.CloseBraceToken
If skipped.IsNull Then
skipped = _pool.Allocate(Of SyntaxToken)
End If
skipped.Add(CurrentToken)
GetNextToken(ScannerState.InterpolatedStringContent)
Continue Do
Case SyntaxKind.DoubleQuoteToken
doubleQuoteToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken()
Exit Do
Case SyntaxKind.EndOfInterpolatedStringToken
doubleQuoteToken = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.DoubleQuoteToken)
GetNextToken(ScannerState.VB)
Exit Do
Case Else
doubleQuoteToken = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.DoubleQuoteToken)
Exit Do
End Select
If Not skipped.IsNull Then
content = AddLeadingSyntax(content, _pool.ToListAndFree(skipped), ERRID.ERR_Syntax)
skipped = Nothing
End If
contentBuilder.Add(content)
Loop
If Not skipped.IsNull Then
doubleQuoteToken = AddLeadingSyntax(doubleQuoteToken, _pool.ToListAndFree(skipped), ERRID.ERR_Syntax)
skipped = Nothing
End If
Dim node = SyntaxFactory.InterpolatedStringExpression(dollarSignDoubleQuoteToken,
_pool.ToListAndFree(contentBuilder),
doubleQuoteToken)
Return CheckFeatureAvailability(Feature.InterpolatedStrings, node)
End Function
Private Function ParseInterpolatedStringInterpolation() As InterpolationSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.OpenBraceToken, "ParseInterpolatedStringEmbeddedExpression called on the wrong token.")
Dim colonToken As PunctuationSyntax = Nothing
Dim excessText As String = Nothing
Dim openBraceToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.VB)
Dim expression As ExpressionSyntax
If CurrentToken.Kind = SyntaxKind.ColonToken Then
openBraceToken = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(openBraceToken, colonToken, excessText), PunctuationSyntax)
expression = ReportSyntaxError(InternalSyntaxFactory.MissingExpression(), ERRID.ERR_ExpectedExpression)
Else
expression = ParseExpressionCore()
' Scanned this as a terminator. Fix it.
If CurrentToken.Kind = SyntaxKind.ColonToken Then
expression = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(expression, colonToken, excessText), ExpressionSyntax)
End If
End If
Dim alignmentClauseOpt As InterpolationAlignmentClauseSyntax
If CurrentToken.Kind = SyntaxKind.CommaToken Then
Debug.Assert(colonToken Is Nothing)
Dim commaToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.VB)
If CurrentToken.Kind = SyntaxKind.ColonToken Then
commaToken = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(commaToken, colonToken, excessText), PunctuationSyntax)
End If
Dim signTokenOpt As PunctuationSyntax
If CurrentToken.Kind = SyntaxKind.MinusToken OrElse
CurrentToken.Kind = SyntaxKind.PlusToken Then
signTokenOpt = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.VB)
If CurrentToken.Kind = SyntaxKind.ColonToken Then
signTokenOpt = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(signTokenOpt, colonToken, excessText), PunctuationSyntax)
End If
Else
signTokenOpt = Nothing
End If
Dim widthToken As IntegerLiteralTokenSyntax
If CurrentToken.Kind = SyntaxKind.IntegerLiteralToken Then
widthToken = DirectCast(CurrentToken, IntegerLiteralTokenSyntax)
GetNextToken(ScannerState.VB)
If CurrentToken.Kind = SyntaxKind.ColonToken Then
widthToken = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(widthToken, colonToken, excessText), IntegerLiteralTokenSyntax)
End If
Else
widthToken = ReportSyntaxError(InternalSyntaxFactory.MissingIntegerLiteralToken(), ERRID.ERR_ExpectedIntLiteral)
End If
Dim valueExpression As ExpressionSyntax = SyntaxFactory.NumericLiteralExpression(widthToken)
If signTokenOpt IsNot Nothing Then
valueExpression = SyntaxFactory.UnaryExpression(
If(signTokenOpt.Kind = SyntaxKind.PlusToken, SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression),
signTokenOpt,
valueExpression)
End If
alignmentClauseOpt = SyntaxFactory.InterpolationAlignmentClause(commaToken, valueExpression)
Else
alignmentClauseOpt = Nothing
End If
Dim formatStringClauseOpt As InterpolationFormatClauseSyntax
If CurrentToken.Kind = SyntaxKind.ColonToken AndAlso colonToken IsNot Nothing Then
' If colonToken IsNot Nothing we were able to recovery.
GetNextToken(ScannerState.InterpolatedStringFormatString)
Dim formatStringToken As InterpolatedStringTextTokenSyntax
If CurrentToken.Kind = SyntaxKind.InterpolatedStringTextToken Then
formatStringToken = DirectCast(CurrentToken, InterpolatedStringTextTokenSyntax)
GetNextToken(ScannerState.InterpolatedStringPunctuation)
If excessText IsNot Nothing Then
formatStringToken = InternalSyntaxFactory.InterpolatedStringTextToken(excessText & formatStringToken.Text,
excessText & formatStringToken.Value,
formatStringToken.GetLeadingTrivia(),
formatStringToken.GetTrailingTrivia())
End If
Else
If excessText IsNot Nothing Then
formatStringToken = InternalSyntaxFactory.InterpolatedStringTextToken(excessText,
excessText,
Nothing,
Nothing)
Else
formatStringToken = Nothing
End If
End If
If formatStringToken Is Nothing Then
formatStringToken = DirectCast(InternalSyntaxFactory.MissingToken(SyntaxKind.InterpolatedStringTextToken), InterpolatedStringTextTokenSyntax)
formatStringToken = ReportSyntaxError(formatStringToken, ERRID.ERR_Syntax)
ElseIf formatStringToken.GetTrailingTrivia() IsNot Nothing Then
formatStringToken = ReportSyntaxError(formatStringToken, ERRID.ERR_InterpolationFormatWhitespace)
End If
formatStringClauseOpt = SyntaxFactory.InterpolationFormatClause(colonToken, formatStringToken)
Else
formatStringClauseOpt = Nothing
If CurrentToken.Kind = SyntaxKind.ColonToken Then
' But if colonToken is null we weren't able to gracefully recover.
GetNextToken(ScannerState.InterpolatedStringFormatString)
End If
End If
Dim closeBraceToken As PunctuationSyntax
If CurrentToken.Kind = SyntaxKind.CloseBraceToken Then
' Must rescan this with interpolated string rules for trailing trivia.
' Specifically, any trailing trivia attached to the closing brace is actually interpolated string content.
ResetCurrentToken(ScannerState.InterpolatedStringPunctuation)
closeBraceToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.InterpolatedStringContent)
ElseIf CurrentToken.Kind = SyntaxKind.EndOfInterpolatedStringToken Then
GetNextToken(ScannerState.VB)
closeBraceToken = DirectCast(HandleUnexpectedToken(SyntaxKind.CloseBraceToken), PunctuationSyntax)
Else
' Content rules will either resync at a } or at the closing ".
If Not IsValidStatementTerminator(CurrentToken) Then
ResetCurrentToken(ScannerState.InterpolatedStringFormatString)
End If
Debug.Assert(CurrentToken.Kind <> SyntaxKind.CloseBraceToken)
closeBraceToken = DirectCast(HandleUnexpectedToken(SyntaxKind.CloseBraceToken), PunctuationSyntax)
If CurrentToken.Kind = SyntaxKind.InterpolatedStringTextToken Then
ResetCurrentToken(ScannerState.InterpolatedStringContent)
GetNextToken(ScannerState.InterpolatedStringContent)
End If
End If
Return SyntaxFactory.Interpolation(openBraceToken, expression, alignmentClauseOpt, formatStringClauseOpt, closeBraceToken)
End Function
Private Shared Function RemoveTrailingColonTriviaAndConvertToColonToken(
token As SyntaxToken,
<Out> ByRef colonToken As PunctuationSyntax,
<Out> ByRef excessText As String
) As SyntaxToken
If Not token.HasTrailingTrivia Then
colonToken = Nothing
excessText = Nothing
Return token
End If
Dim triviaList As New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(token.GetTrailingTrivia())
Dim indexOfFirstColon As Integer = -1
Dim newTrailingTrivia As GreenNode
If triviaList.Count = 1 Then
indexOfFirstColon = 0
newTrailingTrivia = Nothing
excessText = Nothing
ElseIf triviaList(0).Kind = SyntaxKind.ColonTrivia
indexOfFirstColon = 0
newTrailingTrivia = Nothing
excessText = triviaList.GetEndOfTrivia(1).Node.ToFullString()
Else
For i = 0 To triviaList.Count - 1
If triviaList(i).Kind = SyntaxKind.ColonTrivia Then
indexOfFirstColon = i
Exit For
End If
Next
newTrailingTrivia = triviaList.GetStartOfTrivia(indexOfFirstColon).Node
If indexOfFirstColon = triviaList.Count - 1 Then
excessText = Nothing
Else
excessText = triviaList.GetEndOfTrivia(indexOfFirstColon + 1).Node.ToFullString()
Debug.Assert(triviaList.GetEndOfTrivia(indexOfFirstColon + 1).AnyAndOnly(SyntaxKind.ColonTrivia, SyntaxKind.WhitespaceTrivia))
End If
End If
Dim firstColonTrivia = DirectCast(triviaList(indexOfFirstColon), SyntaxTrivia)
colonToken = New PunctuationSyntax(SyntaxKind.ColonToken, firstColonTrivia.Text, Nothing, Nothing)
Return DirectCast(token.WithTrailingTrivia(newTrailingTrivia), SyntaxToken)
End Function
Private Function RemoveTrailingColonTriviaAndConvertToColonToken(
node As VisualBasicSyntaxNode,
<Out> ByRef colonToken As PunctuationSyntax,
<Out> ByRef excessText As String
) As VisualBasicSyntaxNode
Dim lastNonMissing = DirectCast(node.GetLastToken(), SyntaxToken)
Dim newLastNonMissing = RemoveTrailingColonTriviaAndConvertToColonToken(lastNonMissing, colonToken, excessText)
Dim newNode = LastTokenReplacer.Replace(node, Function(t) If(t Is lastNonMissing, newLastNonMissing, t))
' If no token was replaced we have failed to recover; let high contexts deal with it.
If newNode Is node Then
colonToken = Nothing
excessText = Nothing
End If
Return newNode
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory
'
'============ Methods for parsing portions of executable statements ==
'
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Parser
Private Function ParseInterpolatedStringExpression() As InterpolatedStringExpressionSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.DollarSignDoubleQuoteToken, "ParseInterpolatedStringExpression called on the wrong token.")
ResetCurrentToken(ScannerState.InterpolatedStringPunctuation)
Debug.Assert(CurrentToken.Kind = SyntaxKind.DollarSignDoubleQuoteToken, "Rescanning $"" failed.")
Dim dollarSignDoubleQuoteToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.InterpolatedStringContent)
Dim contentBuilder = _pool.Allocate(Of InterpolatedStringContentSyntax)
Dim doubleQuoteToken As PunctuationSyntax
Dim skipped As SyntaxListBuilder(Of SyntaxToken) = Nothing
Do
Dim content As InterpolatedStringContentSyntax
Select Case CurrentToken.Kind
Case SyntaxKind.InterpolatedStringTextToken
Dim textToken = DirectCast(CurrentToken, InterpolatedStringTextTokenSyntax)
' At this point we're either right before an {, an } (error), or a "".
GetNextToken(ScannerState.InterpolatedStringPunctuation)
Debug.Assert(CurrentToken.Kind <> SyntaxKind.InterpolatedStringTextToken,
"Two interpolated string text literal tokens encountered back-to-back. " &
"Scanner should have scanned these as a single token.")
content = SyntaxFactory.InterpolatedStringText(textToken)
Case SyntaxKind.OpenBraceToken
content = ParseInterpolatedStringInterpolation()
Case SyntaxKind.CloseBraceToken
If skipped.IsNull Then
skipped = _pool.Allocate(Of SyntaxToken)
End If
skipped.Add(CurrentToken)
GetNextToken(ScannerState.InterpolatedStringContent)
Continue Do
Case SyntaxKind.DoubleQuoteToken
doubleQuoteToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken()
Exit Do
Case SyntaxKind.EndOfInterpolatedStringToken
doubleQuoteToken = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.DoubleQuoteToken)
GetNextToken(ScannerState.VB)
Exit Do
Case Else
doubleQuoteToken = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.DoubleQuoteToken)
Exit Do
End Select
If Not skipped.IsNull Then
content = AddLeadingSyntax(content, _pool.ToListAndFree(skipped), ERRID.ERR_Syntax)
skipped = Nothing
End If
contentBuilder.Add(content)
Loop
If Not skipped.IsNull Then
doubleQuoteToken = AddLeadingSyntax(doubleQuoteToken, _pool.ToListAndFree(skipped), ERRID.ERR_Syntax)
skipped = Nothing
End If
Dim node = SyntaxFactory.InterpolatedStringExpression(dollarSignDoubleQuoteToken,
_pool.ToListAndFree(contentBuilder),
doubleQuoteToken)
Return CheckFeatureAvailability(Feature.InterpolatedStrings, node)
End Function
Private Function ParseInterpolatedStringInterpolation() As InterpolationSyntax
Debug.Assert(CurrentToken.Kind = SyntaxKind.OpenBraceToken, "ParseInterpolatedStringEmbeddedExpression called on the wrong token.")
Dim colonToken As PunctuationSyntax = Nothing
Dim excessText As String = Nothing
Dim openBraceToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.VB)
Dim expression As ExpressionSyntax
If CurrentToken.Kind = SyntaxKind.ColonToken Then
openBraceToken = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(openBraceToken, colonToken, excessText), PunctuationSyntax)
expression = ReportSyntaxError(InternalSyntaxFactory.MissingExpression(), ERRID.ERR_ExpectedExpression)
Else
expression = ParseExpressionCore()
' Scanned this as a terminator. Fix it.
If CurrentToken.Kind = SyntaxKind.ColonToken Then
expression = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(expression, colonToken, excessText), ExpressionSyntax)
End If
End If
Dim alignmentClauseOpt As InterpolationAlignmentClauseSyntax
If CurrentToken.Kind = SyntaxKind.CommaToken Then
Debug.Assert(colonToken Is Nothing)
Dim commaToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.VB)
If CurrentToken.Kind = SyntaxKind.ColonToken Then
commaToken = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(commaToken, colonToken, excessText), PunctuationSyntax)
End If
Dim signTokenOpt As PunctuationSyntax
If CurrentToken.Kind = SyntaxKind.MinusToken OrElse
CurrentToken.Kind = SyntaxKind.PlusToken Then
signTokenOpt = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.VB)
If CurrentToken.Kind = SyntaxKind.ColonToken Then
signTokenOpt = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(signTokenOpt, colonToken, excessText), PunctuationSyntax)
End If
Else
signTokenOpt = Nothing
End If
Dim widthToken As IntegerLiteralTokenSyntax
If CurrentToken.Kind = SyntaxKind.IntegerLiteralToken Then
widthToken = DirectCast(CurrentToken, IntegerLiteralTokenSyntax)
GetNextToken(ScannerState.VB)
If CurrentToken.Kind = SyntaxKind.ColonToken Then
widthToken = DirectCast(RemoveTrailingColonTriviaAndConvertToColonToken(widthToken, colonToken, excessText), IntegerLiteralTokenSyntax)
End If
Else
widthToken = ReportSyntaxError(InternalSyntaxFactory.MissingIntegerLiteralToken(), ERRID.ERR_ExpectedIntLiteral)
End If
Dim valueExpression As ExpressionSyntax = SyntaxFactory.NumericLiteralExpression(widthToken)
If signTokenOpt IsNot Nothing Then
valueExpression = SyntaxFactory.UnaryExpression(
If(signTokenOpt.Kind = SyntaxKind.PlusToken, SyntaxKind.UnaryPlusExpression, SyntaxKind.UnaryMinusExpression),
signTokenOpt,
valueExpression)
End If
alignmentClauseOpt = SyntaxFactory.InterpolationAlignmentClause(commaToken, valueExpression)
Else
alignmentClauseOpt = Nothing
End If
Dim formatStringClauseOpt As InterpolationFormatClauseSyntax
If CurrentToken.Kind = SyntaxKind.ColonToken AndAlso colonToken IsNot Nothing Then
' If colonToken IsNot Nothing we were able to recovery.
GetNextToken(ScannerState.InterpolatedStringFormatString)
Dim formatStringToken As InterpolatedStringTextTokenSyntax
If CurrentToken.Kind = SyntaxKind.InterpolatedStringTextToken Then
formatStringToken = DirectCast(CurrentToken, InterpolatedStringTextTokenSyntax)
GetNextToken(ScannerState.InterpolatedStringPunctuation)
If excessText IsNot Nothing Then
formatStringToken = InternalSyntaxFactory.InterpolatedStringTextToken(excessText & formatStringToken.Text,
excessText & formatStringToken.Value,
formatStringToken.GetLeadingTrivia(),
formatStringToken.GetTrailingTrivia())
End If
Else
If excessText IsNot Nothing Then
formatStringToken = InternalSyntaxFactory.InterpolatedStringTextToken(excessText,
excessText,
Nothing,
Nothing)
Else
formatStringToken = Nothing
End If
End If
If formatStringToken Is Nothing Then
formatStringToken = DirectCast(InternalSyntaxFactory.MissingToken(SyntaxKind.InterpolatedStringTextToken), InterpolatedStringTextTokenSyntax)
formatStringToken = ReportSyntaxError(formatStringToken, ERRID.ERR_Syntax)
ElseIf formatStringToken.GetTrailingTrivia() IsNot Nothing Then
formatStringToken = ReportSyntaxError(formatStringToken, ERRID.ERR_InterpolationFormatWhitespace)
End If
formatStringClauseOpt = SyntaxFactory.InterpolationFormatClause(colonToken, formatStringToken)
Else
formatStringClauseOpt = Nothing
If CurrentToken.Kind = SyntaxKind.ColonToken Then
' But if colonToken is null we weren't able to gracefully recover.
GetNextToken(ScannerState.InterpolatedStringFormatString)
End If
End If
Dim closeBraceToken As PunctuationSyntax
If CurrentToken.Kind = SyntaxKind.CloseBraceToken Then
' Must rescan this with interpolated string rules for trailing trivia.
' Specifically, any trailing trivia attached to the closing brace is actually interpolated string content.
ResetCurrentToken(ScannerState.InterpolatedStringPunctuation)
closeBraceToken = DirectCast(CurrentToken, PunctuationSyntax)
GetNextToken(ScannerState.InterpolatedStringContent)
ElseIf CurrentToken.Kind = SyntaxKind.EndOfInterpolatedStringToken Then
GetNextToken(ScannerState.VB)
closeBraceToken = DirectCast(HandleUnexpectedToken(SyntaxKind.CloseBraceToken), PunctuationSyntax)
Else
' Content rules will either resync at a } or at the closing ".
If Not IsValidStatementTerminator(CurrentToken) Then
ResetCurrentToken(ScannerState.InterpolatedStringFormatString)
End If
Debug.Assert(CurrentToken.Kind <> SyntaxKind.CloseBraceToken)
closeBraceToken = DirectCast(HandleUnexpectedToken(SyntaxKind.CloseBraceToken), PunctuationSyntax)
If CurrentToken.Kind = SyntaxKind.InterpolatedStringTextToken Then
ResetCurrentToken(ScannerState.InterpolatedStringContent)
GetNextToken(ScannerState.InterpolatedStringContent)
End If
End If
Return SyntaxFactory.Interpolation(openBraceToken, expression, alignmentClauseOpt, formatStringClauseOpt, closeBraceToken)
End Function
Private Shared Function RemoveTrailingColonTriviaAndConvertToColonToken(
token As SyntaxToken,
<Out> ByRef colonToken As PunctuationSyntax,
<Out> ByRef excessText As String
) As SyntaxToken
If Not token.HasTrailingTrivia Then
colonToken = Nothing
excessText = Nothing
Return token
End If
Dim triviaList As New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(token.GetTrailingTrivia())
Dim indexOfFirstColon As Integer = -1
Dim newTrailingTrivia As GreenNode
If triviaList.Count = 1 Then
indexOfFirstColon = 0
newTrailingTrivia = Nothing
excessText = Nothing
ElseIf triviaList(0).Kind = SyntaxKind.ColonTrivia
indexOfFirstColon = 0
newTrailingTrivia = Nothing
excessText = triviaList.GetEndOfTrivia(1).Node.ToFullString()
Else
For i = 0 To triviaList.Count - 1
If triviaList(i).Kind = SyntaxKind.ColonTrivia Then
indexOfFirstColon = i
Exit For
End If
Next
newTrailingTrivia = triviaList.GetStartOfTrivia(indexOfFirstColon).Node
If indexOfFirstColon = triviaList.Count - 1 Then
excessText = Nothing
Else
excessText = triviaList.GetEndOfTrivia(indexOfFirstColon + 1).Node.ToFullString()
Debug.Assert(triviaList.GetEndOfTrivia(indexOfFirstColon + 1).AnyAndOnly(SyntaxKind.ColonTrivia, SyntaxKind.WhitespaceTrivia))
End If
End If
Dim firstColonTrivia = DirectCast(triviaList(indexOfFirstColon), SyntaxTrivia)
colonToken = New PunctuationSyntax(SyntaxKind.ColonToken, firstColonTrivia.Text, Nothing, Nothing)
Return DirectCast(token.WithTrailingTrivia(newTrailingTrivia), SyntaxToken)
End Function
Private Function RemoveTrailingColonTriviaAndConvertToColonToken(
node As VisualBasicSyntaxNode,
<Out> ByRef colonToken As PunctuationSyntax,
<Out> ByRef excessText As String
) As VisualBasicSyntaxNode
Dim lastNonMissing = DirectCast(node.GetLastToken(), SyntaxToken)
Dim newLastNonMissing = RemoveTrailingColonTriviaAndConvertToColonToken(lastNonMissing, colonToken, excessText)
Dim newNode = LastTokenReplacer.Replace(node, Function(t) If(t Is lastNonMissing, newLastNonMissing, t))
' If no token was replaced we have failed to recover; let high contexts deal with it.
If newNode Is node Then
colonToken = Nothing
excessText = Nothing
End If
Return newNode
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/XmlElementHighlighter.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 XmlElementHighlighter
Inherits AbstractKeywordHighlighter(Of XmlNodeSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As XmlNodeSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
Dim xmlElement = node.GetAncestor(Of XmlElementSyntax)()
With xmlElement
If xmlElement IsNot Nothing AndAlso
Not .ContainsDiagnostics AndAlso
Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then
With .StartTag
If .Attributes.Count = 0 Then
highlights.Add(.Span)
Else
highlights.Add(TextSpan.FromBounds(.LessThanToken.SpanStart, .Name.Span.End))
highlights.Add(.GreaterThanToken.Span)
End If
End With
highlights.Add(.EndTag.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 XmlElementHighlighter
Inherits AbstractKeywordHighlighter(Of XmlNodeSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As XmlNodeSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
Dim xmlElement = node.GetAncestor(Of XmlElementSyntax)()
With xmlElement
If xmlElement IsNot Nothing AndAlso
Not .ContainsDiagnostics AndAlso
Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then
With .StartTag
If .Attributes.Count = 0 Then
highlights.Add(.Span)
Else
highlights.Add(TextSpan.FromBounds(.LessThanToken.SpanStart, .Name.Span.End))
highlights.Add(.GreaterThanToken.Span)
End If
End With
highlights.Add(.EndTag.Span)
End If
End With
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenDelegateCreation.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.Reflection
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenDelegateCreation
Inherits BasicTestBase
<Fact>
Public Sub DelegateMethods()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
' delegate as type
Delegate Function FuncDel(param1 as Integer, param2 as String) as Char
Class C2
public intMember as Integer
End Class
Class C1
' delegate as nested type
Delegate Sub SubDel(param1 as Integer, ByRef param2 as String)
Delegate Sub SubGenDel(Of T)(param1 as T)
Delegate Function FuncGenDel(Of T)(param1 as integer) as T
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(c1, symbolValidator:=
Sub([module])
' Note: taking dev10 metadata as golden results, not the ECMA spec.
Dim reader = (DirectCast([module], PEModuleSymbol)).Module.GetMetadataReader()
Dim expectedMethodMethodFlags = MethodAttributes.Public Or MethodAttributes.NewSlot Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride
Dim expectedConstructorMethodFlags = MethodAttributes.Public Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName
' --- test SubDel methods -----------------------------------------------------------------------------------------------
Dim subDel = [module].GlobalNamespace.GetTypeMembers("C1").Single().GetTypeMembers("SubDel").Single()
' test .ctor
'.method public specialname rtspecialname instance void .ctor(object Instance, native int Method) runtime managed {}
Dim ctor = subDel.GetMembers(".ctor").OfType(Of MethodSymbol)().Single()
Assert.True(ctor.IsSub())
Assert.Equal("System.Void", ctor.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, ctor.Parameters.Length)
Assert.Equal("System.Object", ctor.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("TargetObject", ctor.Parameters(0).Name)
Assert.Equal("System.IntPtr", ctor.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("TargetMethod", ctor.Parameters(1).Name)
Dim methodDef = CType(ctor, PEMethodSymbol).Handle
Dim methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedConstructorMethodFlags, methodFlags)
Dim methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
Dim expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(ctor, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(ctor, PEMethodSymbol).IsRuntimeImplemented)
' test Invoke
' .method public newslot strict virtual instance void Invoke(int32 param1, string& param2) runtime managed {}
Dim invoke = subDel.GetMembers("Invoke").OfType(Of MethodSymbol)().Single()
Assert.True(invoke.IsSub())
Assert.Equal("System.Void", invoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, invoke.Parameters.Length)
Assert.Equal("System.Int32", invoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", invoke.Parameters(0).Name)
Assert.False(invoke.Parameters(0).IsByRef)
Assert.Equal("System.String", invoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", invoke.Parameters(1).Name)
Assert.True(invoke.Parameters(1).IsByRef)
methodDef = CType(invoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(invoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(invoke, PEMethodSymbol).IsRuntimeImplemented)
' test BeginInvoke
' .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult
' BeginInvoke(int32 param1,
' string& param2,
' class [mscorlib]System.AsyncCallback DelegateCallback,
' object DelegateAsyncState) runtime managed {}
Dim beginInvoke = subDel.GetMembers("BeginInvoke").OfType(Of MethodSymbol)().Single()
Assert.False(beginInvoke.IsSub())
Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(4, beginInvoke.Parameters.Length)
Assert.Equal("System.Int32", beginInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", beginInvoke.Parameters(0).Name)
Assert.False(beginInvoke.Parameters(0).IsByRef)
Assert.Equal("System.String", beginInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", beginInvoke.Parameters(1).Name)
Assert.True(beginInvoke.Parameters(1).IsByRef)
Assert.Equal("System.AsyncCallback", beginInvoke.Parameters(2).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateCallback", beginInvoke.Parameters(2).Name)
Assert.False(beginInvoke.Parameters(2).IsByRef)
Assert.Equal("System.Object", beginInvoke.Parameters(3).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncState", beginInvoke.Parameters(3).Name)
Assert.False(beginInvoke.Parameters(3).IsByRef)
methodDef = CType(beginInvoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(beginInvoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(beginInvoke, PEMethodSymbol).IsRuntimeImplemented)
' test EndInvoke
' .method public newslot strict virtual instance
' void EndInvoke(string& param2, class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed {}
Dim endInvoke = subDel.GetMembers("EndInvoke").OfType(Of MethodSymbol)().Single()
Assert.True(endInvoke.IsSub())
Assert.Equal("System.Void", endInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, endInvoke.Parameters.Length)
Assert.Equal("System.String", endInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", endInvoke.Parameters(0).Name)
Assert.True(endInvoke.Parameters(0).IsByRef)
Assert.Equal("System.IAsyncResult", endInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncResult", endInvoke.Parameters(1).Name)
Assert.False(endInvoke.Parameters(1).IsByRef)
methodDef = CType(endInvoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(endInvoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(endInvoke, PEMethodSymbol).IsRuntimeImplemented)
' --- test FuncDel methods ----------------------------------------------------------------------------------------------
Dim funcDel = [module].GlobalNamespace.GetTypeMembers("FuncDel").Single()
' test Invoke
' .method public newslot strict virtual instance char Invoke(int32 param1, string param2) runtime managed
invoke = funcDel.GetMembers("Invoke").OfType(Of MethodSymbol)().Single()
Assert.False(invoke.IsSub())
Assert.Equal("System.Char", invoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, invoke.Parameters.Length)
Assert.Equal("System.Int32", invoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", invoke.Parameters(0).Name)
Assert.False(invoke.Parameters(0).IsByRef)
Assert.Equal("System.String", invoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", invoke.Parameters(1).Name)
Assert.False(invoke.Parameters(1).IsByRef)
methodDef = CType(invoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(invoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
' test EndInvoke
' .method public newslot strict virtual instance
' charEndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed {}
endInvoke = funcDel.GetMembers("EndInvoke").OfType(Of MethodSymbol)().Single()
Assert.False(endInvoke.IsSub())
Assert.Equal("System.Char", endInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(1, endInvoke.Parameters.Length)
Assert.Equal("System.IAsyncResult", endInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncResult", endInvoke.Parameters(0).Name)
Assert.False(endInvoke.Parameters(0).IsByRef)
methodDef = CType(endInvoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(endInvoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
' --- test FuncGenDel methods -------------------------------------------------------------------------------------------
Dim subGenDel = [module].GlobalNamespace.GetTypeMembers("C1").Single().GetTypeMembers("SubGenDel").Single()
' test Invoke
' .method public newslot strict virtual instance char Invoke(int32 param1, string param2) runtime managed
invoke = subGenDel.GetMembers("Invoke").OfType(Of MethodSymbol)().Single()
Assert.True(invoke.IsSub())
Assert.Equal(1, invoke.Parameters.Length)
Assert.Equal("T", invoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", invoke.Parameters(0).Name)
Assert.False(invoke.Parameters(0).IsByRef)
Assert.True(CType(invoke, PEMethodSymbol).IsRuntimeImplemented)
End Sub)
Next
End Sub
' Test module method, shared method, instance method, constructor, property with valid args for both function and sub delegate
<Fact>
Public Sub ValidDelegateAddressOfTest()
For Each optionValue In {"On", "Off"}
Dim source = <compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub SubDel(p As String)
Delegate function FuncDel(p As String) as Integer
Module M1
Public Sub ds1(p As String)
End Sub
Public Function df1(p As String) As Integer
return 23
End Function
End Module
Class C1
Public Sub ds2(p As String)
End Sub
Public Function df2(p As String) As Integer
return 23
End Function
Public Shared Sub ds3(p As String)
End Sub
Public Shared Function df3(p As String) As Integer
return 23
End Function
End Class
Class C2
Public Sub AssignDelegates()
Dim ci As New C1()
Dim ds As SubDel
ds = AddressOf M1.ds1
Console.WriteLine(ds)
ds = AddressOf ci.ds2
Console.WriteLine(ds)
ds = AddressOf C1.ds3
Console.WriteLine(ds)
End Sub
End Class
Module Program
Sub Main(args As String())
Dim c as new C2()
c.AssignDelegates()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
SubDel
SubDel
SubDel
]]>).
VerifyIL("C2.AssignDelegates",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 3
IL_0000: newobj "Sub C1..ctor()"
IL_0005: ldnull
IL_0006: ldftn "Sub M1.ds1(String)"
IL_000c: newobj "Sub SubDel..ctor(Object, System.IntPtr)"
IL_0011: call "Sub System.Console.WriteLine(Object)"
IL_0016: ldftn "Sub C1.ds2(String)"
IL_001c: newobj "Sub SubDel..ctor(Object, System.IntPtr)"
IL_0021: call "Sub System.Console.WriteLine(Object)"
IL_0026: ldnull
IL_0027: ldftn "Sub C1.ds3(String)"
IL_002d: newobj "Sub SubDel..ctor(Object, System.IntPtr)"
IL_0032: call "Sub System.Console.WriteLine(Object)"
IL_0037: ret
}
]]>)
Next
End Sub
''' Bug 5987 "Target parameter of a delegate instantiation is not boxed in case of a structure"
<Fact>
Public Sub DelegateInvocationStructureTests()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub SubDel(p As String)
Delegate function FuncDel(p As String) as Integer
Structure S1
Public Sub ds4(p As String)
Console.WriteLine("S1.ds4 " + p)
End Sub
Public Function df4(p As String) As Integer
return 4
End Function
Public Shared Sub ds5(p As String)
Console.WriteLine("S1.ds5 " + p)
End Sub
Public Shared Function df5(p As String) As Integer
return 5
End Function
End Structure
Module Program
Sub Main(args As String())
Dim ds As SubDel
Dim s as new S1()
ds = AddressOf s.ds4
ds.Invoke("(passed arg)")
ds = AddressOf S1.ds5
ds.Invoke("(passed arg)")
Moo("Hi")
Moo(42)
End Sub
Sub Moo(of T)(x as T)
Dim f as Func(of String) = AddressOf x.ToString
Console.WriteLine(f.Invoke())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
S1.ds4 (passed arg)
S1.ds5 (passed arg)
Hi
42
]]>)
Next
End Sub
<Fact>
Public Sub DelegateInvocationTests()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub SubDel(Of T)(p As T)
Delegate function FuncDel(p As Integer) as Integer
Module M1
Public Sub ds1(p As String)
Console.WriteLine("M1.ds1 " + p)
End Sub
Public Function df1(p As Integer) As Integer
return 1 + p
End Function
End Module
Class C1
Public Sub ds2(p As String)
Console.WriteLine("C1.ds2 " + p)
End Sub
Public Function df2(p As Integer) As Integer
return 2 + p
End Function
Public Shared Sub ds3(p As String)
Console.WriteLine("C1.ds3 " + p)
End Sub
Public Shared Function df3(p As Integer) As Integer
return 3 + p
End Function
End Class
Module Program
Sub Main(args As String())
Dim ds As SubDel(of string)
ds = AddressOf M1.ds1
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim ci As New C1()
ds = AddressOf ci.ds2
ds.Invoke("(passed arg)")
ds("(passed arg)")
ds = AddressOf C1.ds3
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim df As FuncDel
Dim target as Integer
df = AddressOf M1.df1
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf ci.df2
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf C1.df3
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
M1.ds1 (passed arg)
M1.ds1 (passed arg)
C1.ds2 (passed arg)
C1.ds2 (passed arg)
C1.ds3 (passed arg)
C1.ds3 (passed arg)
42
42
43
43
44
44
]]>)
Next
End Sub
<Fact>
Public Sub DelegateInvocationDelegatesFromMetadataTests()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Module M1
Public Sub ds1(p$)
Console.WriteLine("M1.ds1 " + p)
End Sub
Public Function df1(p%) As Integer
Return 1 + p
End Function
End Module
Class C1
Public Sub ds2(p As String)
Console.WriteLine("C1.ds2 " + p)
End Sub
Public Function df2%(p As Integer)
Return 2 + p
End Function
Public Shared Sub ds3(p As String)
Console.WriteLine("C1.ds3 " + p)
End Sub
Public Shared Function df3(p As Integer) As Integer
Return 3 + p
End Function
End Class
Module Program
Sub Main(args As String())
Dim ds As Action(Of String)
ds = AddressOf M1.ds1
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim ci As New C1()
ds = AddressOf ci.ds2
ds.Invoke("(passed arg)")
ds("(passed arg)")
ds = AddressOf C1.ds3
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim df As Func(Of Integer, Integer)
Dim target As Integer
df = AddressOf M1.df1
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf ci.df2
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf C1.df3
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
M1.ds1 (passed arg)
M1.ds1 (passed arg)
C1.ds2 (passed arg)
C1.ds2 (passed arg)
C1.ds3 (passed arg)
C1.ds3 (passed arg)
42
42
43
43
44
44
]]>)
Next
End Sub
<Fact>
Public Sub Error_ERR_AddressOfNotCreatableDelegate1()
Dim source = <compilation>
<file name="a.vb">
Imports System
Delegate Sub SubDel(p As String)
Class C2
Public Shared Sub goo(p as string)
end sub
Public Sub AssignDelegates()
Dim v1 As System.Delegate = AddressOf goo
Dim v2 As System.MulticastDelegate = AddressOf C2.goo
End Sub
End Class
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected>
BC30939: 'AddressOf' expression cannot be converted to '[Delegate]' because type '[Delegate]' is declared 'MustInherit' and cannot be created.
Dim v1 As System.Delegate = AddressOf goo
~~~~~~~~~~~~~
BC30939: 'AddressOf' expression cannot be converted to 'MulticastDelegate' because type 'MulticastDelegate' is declared 'MustInherit' and cannot be created.
Dim v2 As System.MulticastDelegate = AddressOf C2.goo
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NewDelegateWithAddressOf()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
IMPORTS SYStEM
Delegate Sub D()
Class C1
public field as string = ""
public sub new(param as string)
field = param
end sub
public sub goo()
console.writeline("Hello " & Me.field)
end sub
public shared sub goo2()
console.writeline("... and again.")
end sub
end class
Module Program
Sub Main(args As String())
Dim x As D
x = New D(AddressOf Method)
x
Dim c as new C1("again.")
Dim y as new D(addressof c.goo)
y
Dim z as new D(addressof C1.goo2)
z
End Sub
Public Sub Method()
console.writeline("Hello.")
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello.
Hello again.
... and again.
]]>)
Next
End Sub
<Fact>
Public Sub WideningArgumentsDelegateSubRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub WideningNumericDelegate(p as Byte)
Delegate Sub WideningStringDelegate(p as Char)
Delegate Sub WideningNullableDelegate(p as Byte?)
Delegate Sub WideningReferenceDelegate(p as Derived)
Delegate Sub WideningArrayDelegate(p() as Derived)
Delegate Sub WideningValueDelegate(p as S1)
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Sub WideningNumericSub(p as Integer)
console.writeline("Hello from instance WideningNumericDelegate " & p.ToString() )
End Sub
Public Sub WideningStringSub(p as String)
console.writeline("Hello from instance WideningStringDelegate " & p.ToString() )
End Sub
Public Sub WideningNullableSub(p as Integer?)
console.writeline("Hello from instance WideningNullableDelegate " & p.ToString() )
End Sub
Public Sub WideningReferenceSub(p as Base)
console.writeline("Hello from instance WideningReferenceDelegate " & p.ToString() )
End Sub
Public Sub WideningArraySub(p() as Base)
console.writeline("Hello from instance WideningArrayDelegate " & p.ToString() )
End Sub
Public Sub WideningValueSub(p as Object)
console.writeline("Hello from instance WideningValueDelegate " & p.ToString() )
End Sub
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
Dim ci as new C()
Dim d1 as new WideningNumericDelegate(AddressOf ci.WideningNumericSub)
d1(23)
Dim d2 as new WideningStringDelegate(AddressOf ci.WideningStringSub)
d2("c"c)
'Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableSub)
'd3(n)
Dim d4 as new WideningReferenceDelegate(AddressOf ci.WideningReferenceSub)
d4(new Derived())
Dim d5 as new WideningArrayDelegate(AddressOf ci.WideningArraySub)
d5( arr )
Dim d6 as new WideningValueDelegate(AddressOf ci.WideningValueSub)
d6(new S1())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNumericDelegate 23
Hello from instance WideningStringDelegate c
Hello from instance WideningReferenceDelegate Derived
Hello from instance WideningArrayDelegate Derived[]
Hello from instance WideningValueDelegate S1
]]>)
Next
End Sub
''' Bug 7191: "Lambda rewriter does not work for widening conversions of byref params with option strict off"
<Fact>
Public Sub WideningArgumentsDelegateSubRelaxationByRefStrictOff()
For Each optionValue In {"Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub WideningNumericDelegate(byref p as Byte)
Delegate Sub WideningStringDelegate(byref p as Char)
Delegate Sub WideningNullableDelegate(byref p as Byte?)
Delegate Sub WideningReferenceDelegate(byref p as Derived)
Delegate Sub WideningArrayDelegate(byref p() as Derived)
Delegate Sub WideningValueDelegate(byref p as S1)
Structure S1
public field as integer
Public sub New(p as integer)
field = p
end sub
End Structure
Class Base
public field as integer
End Class
Class Derived
Inherits Base
Public sub New(p as integer)
field = p
end sub
End Class
Class C
Public Sub WideningNumericSub(byref p as Integer)
console.writeline("Hello from instance WideningNumericDelegate " & p.ToString() )
p = 42
End Sub
Public Sub WideningStringSub(byref p as String)
console.writeline("Hello from instance WideningStringDelegate " & p.ToString() )
p = "touched"
End Sub
'Public Sub WideningNullableSub(byref p as Integer?)
' console.writeline("Hello from instance WideningNullableDelegate " & p.ToString() )
' p = 42
'End Sub
Public Sub WideningReferenceSub(byref p as Base)
console.writeline("Hello from instance WideningReferenceDelegate " & p.ToString() )
p = new Derived(42)
End Sub
Public Sub WideningArraySub(byref p() as Base)
console.writeline("Hello from instance WideningArrayDelegate " & p.ToString() )
Dim arr(1) as Derived
arr(0) = new Derived(23)
arr(1) = new Derived(42)
p = arr
End Sub
Public Sub WideningValueSub(byref p as Object)
console.writeline("Hello from instance WideningValueDelegate " & p.ToString() )
p = new S1(42)
End Sub
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived(1)
arr(1) = new Derived(2)
Dim ci as new C()
Dim d1 as new WideningNumericDelegate(AddressOf ci.WideningNumericSub)
dim pbyte as byte = 23
d1(pbyte)
console.writeline(pbyte)
Dim d2 as new WideningStringDelegate(AddressOf ci.WideningStringSub)
dim pchar as char = "c"c
d2(pchar)
console.writeline(pchar)
'Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableSub)
'd3(n)
'console.writeline(n.Value)
Dim d4 as new WideningReferenceDelegate(AddressOf ci.WideningReferenceSub)
dim pderived as Derived = new Derived(23)
d4(pderived)
console.writeline(pderived.field)
Dim d5 as new WideningArrayDelegate(AddressOf ci.WideningArraySub)
d5( arr )
console.writeline(arr(0).field & " " & arr(1).field)
Dim d6 as new WideningValueDelegate(AddressOf ci.WideningValueSub)
dim ps1 as S1 = new S1(23)
d6(ps1)
console.writeline(ps1.field)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNumericDelegate 23
42
Hello from instance WideningStringDelegate c
t
Hello from instance WideningReferenceDelegate Derived
42
Hello from instance WideningArrayDelegate Derived[]
23 42
Hello from instance WideningValueDelegate S1
42
]]>)
Next
End Sub
<Fact()>
Public Sub WideningArgumentsDelegateSubRelaxation_nullable()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub WideningNullableDelegate(p as Byte?)
Class C
Public Sub WideningNullableSub(p as Integer?)
console.writeline("Hello from instance WideningNullableDelegate " & p.Value.ToString() )
End Sub
End Class
Module Program
Sub Main(args As String())
Dim n? As Byte = 23
Dim ci as new C()
Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableSub)
d3(n)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNullableDelegate 23
]]>)
Next
End Sub
<Fact>
Public Sub IdentityArgumentsDelegateSubRelaxationByRef()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub IdentityNumericDelegate(byref p as Byte)
Delegate Sub IdentityStringDelegate(byref p as Char)
Delegate Sub IdentityNullableDelegate(byref p as Byte?)
Delegate Sub IdentityReferenceDelegate(byref p as Derived)
Delegate Sub IdentityArrayDelegate(byref p() as Derived)
Delegate Sub IdentityValueDelegate(byref p as S1)
Structure S1
public field as integer
Public sub New(p as integer)
field = p
end sub
End Structure
Class Base
public field as integer
End Class
Class Derived
Inherits Base
Public sub New(p as integer)
field = p
end sub
End Class
Class C
Public Sub IdentityNumericSub(byref p as Byte)
console.writeline("Hello from instance IdentityNumericDelegate " & p.ToString() )
p = 42
End Sub
Public Sub IdentityStringSub(byref p as Char)
console.writeline("Hello from instance IdentityStringDelegate " & p.ToString() )
p = "t"c
End Sub
'Public Sub IdentityNullableSub(byref p as Byte?)
' console.writeline("Hello from instance IdentityNullableDelegate " & p.ToString() )
' p = 42
'End Sub
Public Sub IdentityReferenceSub(byref p as Derived)
console.writeline("Hello from instance IdentityReferenceDelegate " & p.ToString() )
p = new Derived(42)
End Sub
Public Sub IdentityArraySub(byref p() as Derived)
console.writeline("Hello from instance IdentityArrayDelegate " & p.ToString() )
Dim arr(1) as Derived
arr(0) = new Derived(23)
arr(1) = new Derived(42)
p = arr
End Sub
Public Sub IdentityValueSub(byref p as S1)
console.writeline("Hello from instance IdentityValueDelegate " & p.ToString() )
p = new S1(42)
End Sub
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived(1)
arr(1) = new Derived(2)
Dim ci as new C()
Dim d1 as new IdentityNumericDelegate(AddressOf ci.IdentityNumericSub)
dim pbyte as byte = 23
d1(pbyte)
console.writeline(pbyte)
Dim d2 as new IdentityStringDelegate(AddressOf ci.IdentityStringSub)
dim pchar as char = "c"c
d2(pchar)
console.writeline(pchar)
'Dim d3 as new IdentityNullableDelegate(AddressOf ci.IdentityNullableSub)
'd3(n)
'console.writeline(n.Value)
Dim d4 as new IdentityReferenceDelegate(AddressOf ci.IdentityReferenceSub)
dim pderived as Derived = new Derived(23)
d4(pderived)
console.writeline(pderived.field)
Dim d5 as new IdentityArrayDelegate(AddressOf ci.IdentityArraySub)
d5( arr )
console.writeline(arr(0).field & " " & arr(1).field)
Dim d6 as new IdentityValueDelegate(AddressOf ci.IdentityValueSub)
dim ps1 as S1 = new S1(23)
d6(ps1)
console.writeline(ps1.field)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance IdentityNumericDelegate 23
42
Hello from instance IdentityStringDelegate c
t
Hello from instance IdentityReferenceDelegate Derived
42
Hello from instance IdentityArrayDelegate Derived[]
23 42
Hello from instance IdentityValueDelegate S1
42
]]>)
Next
End Sub
<Fact>
Public Sub WideningArgumentsDelegateFunctionRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningNumericDelegate(p as byte, p as Byte) as integer
Delegate Function WideningStringDelegate(p as Char) as String
Delegate Function WideningNullableDelegate(p as Byte?) as integer
Delegate Function WideningReferenceDelegate(p as Derived) as integer
Delegate Function WideningArrayDelegate(p() as Derived) as integer
Delegate Function WideningValueDelegate(p as S1) as integer
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Function WideningNumericFunction(i as integer, p as Integer) as integer
console.writeline("Hello from instance WideningNumericDelegate ")
return 23
End Function
Public Function WideningStringFunction$(p as String)
console.writeline("Hello from instance WideningStringDelegate ")
return "24"
End Function
Public Function WideningNullableFunction(p as Integer?) as integer
console.writeline("Hello from instance WideningNullableDelegate ")
return 25
End Function
Public Function WideningReferenceFunction(p as Base) as integer
console.writeline("Hello from instance WideningReferenceDelegate ")
return 26
End Function
Public Function WideningArrayFunction(p() as Base) as integer
console.writeline("Hello from instance WideningArrayDelegate ")
return 27
End Function
Public Function WideningValueFunction(p as Object) as integer
console.writeline("Hello from instance WideningValueDelegate ")
return 28
End Function
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
Dim ci as new C()
Dim d1 as new WideningNumericDelegate(AddressOf ci.WideningNumericFunction)
console.writeline( d1(1, 23) )
Dim d2 as new WideningStringDelegate(AddressOf ci.WideningStringFunction)
console.writeline( d2("c"c) )
'Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableFunction)
'console.writeline( d3(n) )
Dim d4 as new WideningReferenceDelegate(AddressOf ci.WideningReferenceFunction)
console.writeline( d4(new Derived()) )
Dim d5 as new WideningArrayDelegate(AddressOf ci.WideningArrayFunction)
console.writeline( d5(arr) )
Dim d6 as new WideningValueDelegate(AddressOf ci.WideningValueFunction)
console.writeline( d6(new S1()) )
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNumericDelegate
23
Hello from instance WideningStringDelegate
24
Hello from instance WideningReferenceDelegate
26
Hello from instance WideningArrayDelegate
27
Hello from instance WideningValueDelegate
28
]]>)
Next
End Sub
<Fact()>
Public Sub WideningArgumentsDelegateFunctionRelaxation_nullable()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningNullableDelegate(p as Byte?) as integer
Class C
Public Function WideningNullableFunction(p as Integer?) as integer
console.writeline("Hello from instance WideningNullableDelegate ")
return 25
End Function
End Class
Module Program
Sub Main(args As String())
Dim n? As Byte = 23
Dim ci as new C()
Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableFunction)
console.writeline( d3(n) )
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNullableDelegate
25
]]>)
Next
End Sub
<Fact>
Public Sub WideningReturnValueDelegateFunctionRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningReturnNumericDelegate() as Integer
Delegate Function WideningReturnStringDelegate() as String
'Delegate Function WideningReturnNullableDelegate() as Integer?
Delegate Function WideningReturnReferenceDelegate() as Base
Delegate Function WideningReturnArrayDelegate() as Base()
Delegate Function WideningReturnValueDelegate() as Object
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Function WideningReturnNumericFunction() as Byte
console.writeline("Hello from instance WideningReturnNumericFunction ")
return 23
End Function
Public Function WideningReturnStringFunction() as Char
console.writeline("Hello from instance WideningReturnStringFunction ")
return "A"c
End Function
'Public Function WideningReturnNullableFunction() as Byte?
' console.writeline("Hello from instance WideningReturnNullableFunction ")
' return 25
'End Function
Public Function WideningReturnReferenceFunction() as Derived
console.writeline("Hello from instance WideningReturnReferenceFunction ")
return new Derived()
End Function
Public Function WideningReturnArrayFunction() as Derived()
console.writeline("Hello from instance WideningReturnArrayFunction ")
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
return arr
End Function
Public Function WideningReturnValueFunction() as S1
console.writeline("Hello from instance WideningReturnValueFunction ")
return new S1()
End Function
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim ci as new C()
Dim d1 as new WideningReturnNumericDelegate(AddressOf ci.WideningReturnNumericFunction)
console.writeline( d1() )
Dim d2 as new WideningReturnStringDelegate(AddressOf ci.WideningReturnStringFunction)
console.writeline( d2() )
'Dim d3 as new WideningReturnNullableDelegate(AddressOf ci.WideningReturnNullableFunction)
'console.writeline( d3(n) )
Dim d4 as new WideningReturnReferenceDelegate(AddressOf ci.WideningReturnReferenceFunction)
console.writeline( d4() )
Dim d5 as new WideningReturnArrayDelegate(AddressOf ci.WideningReturnArrayFunction)
console.writeline( d5() )
Dim d6 as new WideningReturnValueDelegate(AddressOf ci.WideningReturnValueFunction)
console.writeline( d6() )
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningReturnNumericFunction
23
Hello from instance WideningReturnStringFunction
A
Hello from instance WideningReturnReferenceFunction
Derived
Hello from instance WideningReturnArrayFunction
Derived[]
Hello from instance WideningReturnValueFunction
S1
]]>)
Next
End Sub
<Fact()>
Public Sub WideningReturnValueDelegateFunctionRelaxation_nullable()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningReturnNullableDelegate() As Integer?
Class C
Public Function WideningReturnNullableFunction() As Byte?
console.writeline("Hello from instance WideningReturnNullableFunction ")
Return 25
End Function
End Class
Module Program
Sub Main(args As String())
Dim ci As New C()
Dim d3 As New WideningReturnNullableDelegate(AddressOf ci.WideningReturnNullableFunction)
Console.WriteLine((d3()).Value())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningReturnNullableFunction
25
]]>)
Next
End Sub
<Fact>
Public Sub NarrowingArgumentsDelegateSubRelaxation()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Delegate Sub NarrowingNumericDelegate(pdel as Integer)
Delegate Sub NarrowingStringDelegate(pdel as String)
Delegate Sub NarrowingNullableDelegate(pdel as Integer?)
Delegate Sub NarrowingReferenceDelegate(pdel as Base)
Delegate Sub NarrowingArrayDelegate(pdel() as Base)
Delegate Sub NarrowingValueDelegate(pdel as Object)
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Sub NarrowingNumericSub(psub as Byte)
console.writeline("Hello from instance NarrowingNumericDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingStringSub(psub as Char)
console.writeline("Hello from instance NarrowingStringDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingNullableSub(psub as Byte?)
console.writeline("Hello from instance NarrowingNullableDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingReferenceSub(psub as Derived)
console.writeline("Hello from instance NarrowingReferenceDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingArraySub(psub() as Derived)
console.writeline("Hello from instance NarrowingArrayDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingValueSub(psub as S1)
console.writeline("Hello from instance NarrowingValueDelegate")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
Dim ci as new C()
Dim d1 as new NarrowingNumericDelegate(AddressOf ci.NarrowingNumericSub)
d1(23)
Dim d2 as new NarrowingStringDelegate(AddressOf ci.NarrowingStringSub)
d2("c")
'Dim d3 as new NarrowingNullableDelegate(AddressOf ci.NarrowingNullableSub)
'd3(n)
Dim d4 as new NarrowingReferenceDelegate(AddressOf ci.NarrowingReferenceSub)
d4(new Derived())
Dim d5 as new NarrowingArrayDelegate(AddressOf ci.NarrowingArraySub)
d5(arr)
Dim d6 as new NarrowingValueDelegate(AddressOf ci.NarrowingValueSub)
d6(new S1())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance NarrowingNumericDelegate 23
Hello from instance NarrowingStringDelegate c
Hello from instance NarrowingReferenceDelegate Derived
Hello from instance NarrowingArrayDelegate Derived[]
Hello from instance NarrowingValueDelegate
]]>)
End Sub
<Fact()>
Public Sub NarrowingArgumentsDelegateSubRelaxation_nullable()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Delegate Sub NarrowingNullableDelegate(p as Integer?)
Class C
Public Sub NarrowingNullableSub(p as Byte?)
console.writeline("Hello from instance NarrowingNullableDelegate " & p.Value.ToString() )
End Sub
End Class
Module Program
Sub Main(args As String())
Dim n? As Integer = 23
Dim ci as new C()
Dim d3 as new NarrowingNullableDelegate(AddressOf ci.NarrowingNullableSub)
d3(n)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance NarrowingNullableDelegate 23
]]>)
End Sub
<Fact>
Public Sub OmittingArgumentsDelegateSubRelaxation_strictoff()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Delegate Sub OmittingArgumentsDelegate(p as Integer)
Class C
Public Sub OmittingArgumentsSub()
console.writeline("Hello from instance OmittingArgumentsDelegate.")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new OmittingArgumentsDelegate(AddressOf ci.OmittingArgumentsSub)
d1(23)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingArgumentsDelegate.
]]>)
End Sub
<Fact()>
Public Sub OmittingArgumentsDelegateSubRelaxation_lambda()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Delegate Sub OmittingArgumentsDelegate(p as Integer)
Module Program
Sub Main(args As String())
Dim d1 as new OmittingArgumentsDelegate(Sub() console.writeline("Hello from instance OmittingArgumentsDelegate."))
d1(23)
d1 = Sub() console.writeline("Hello from instance OmittingArgumentsDelegate.")
d1.Invoke(23)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingArgumentsDelegate.
Hello from instance OmittingArgumentsDelegate.
]]>)
End Sub
<Fact>
Public Sub OmittingReturnValueDelegateFunctionRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub OmittingReturnValueDelegate(p as Integer)
Class C
Public Function OmittingReturnValueSub(p as Integer) as Integer
console.writeline("Hello from instance OmittingReturnValueSub.")
return 23
End Function
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new OmittingReturnValueDelegate(AddressOf ci.OmittingReturnValueSub)
d1(23)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingReturnValueSub.
]]>)
Next
End Sub
<Fact()>
Public Sub OmittingOptionalParameter()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub OmittingOptionalParameter1Delegate(p as Integer, p as Integer)
Delegate Sub OmittingOptionalParameter2Delegate(p as Integer)
Delegate Sub OmittingOptionalParameter3Delegate()
Class C
Public Sub OmittingOptionalParameter1Sub(optional a as integer = 23, optional b as integer = 42)
console.writeline("Hello from instance OmittingOptionalParameter1Sub.")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new OmittingOptionalParameter1Delegate(AddressOf ci.OmittingOptionalParameter1Sub)
d1(23, 23)
Dim d2 as new OmittingOptionalParameter2Delegate(AddressOf ci.OmittingOptionalParameter1Sub)
d2(23)
Dim d3 as new OmittingOptionalParameter3Delegate(AddressOf ci.OmittingOptionalParameter1Sub)
d3()
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingOptionalParameter1Sub.
Hello from instance OmittingOptionalParameter1Sub.
Hello from instance OmittingOptionalParameter1Sub.
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation1()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub ParamArrayInSubPerfectMatch1Delegate(pdel as Integer, pdel as Integer)
Delegate Sub ParamArrayInSubPerfectMatch2Delegate(p as Base, p as Base)
Delegate Sub ParamArrayInSubPerfectMatch3Delegate()
Delegate Sub ParamArrayInSubWideningMatch1Delegate(p as Integer, p as Byte)
Class Base
End Class
Class Derived
Inherits Base
end Class
Class C
Public Sub ParamArrayInSubPerfectMatch1Sub(paramarray p() as Integer)
console.writeline("Hello from instance ParamArrayInSubPerfectMatch1Sub.")
End Sub
Public Sub ParamArrayInSubPerfectMatch2Sub(paramarray p() as Base)
console.writeline("Hello from instance ParamArrayInSubPerfectMatch2Sub.")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new ParamArrayInSubPerfectMatch1Delegate(AddressOf ci.ParamArrayInSubPerfectMatch1Sub)
d1(23, 23)
Dim d2 as new ParamArrayInSubPerfectMatch2Delegate(AddressOf ci.ParamArrayInSubPerfectMatch2Sub)
d2(new Derived(), new Derived())
Dim d3 as new ParamArrayInSubPerfectMatch3Delegate(AddressOf ci.ParamArrayInSubPerfectMatch2Sub)
d3()
Dim d4 as new ParamArrayInSubPerfectMatch3Delegate(AddressOf ci.ParamArrayInSubPerfectMatch1Sub)
d4()
Dim d5 as new ParamArrayInSubWideningMatch1Delegate(AddressOf ci.ParamArrayInSubPerfectMatch1Sub)
d5(23,42)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArrayInSubPerfectMatch1Sub.
Hello from instance ParamArrayInSubPerfectMatch2Sub.
Hello from instance ParamArrayInSubPerfectMatch2Sub.
Hello from instance ParamArrayInSubPerfectMatch1Sub.
Hello from instance ParamArrayInSubPerfectMatch1Sub.
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation2()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub ParamArrayDelegateRelaxation1Delegate(p() as Integer)
Class C
Public Sub ParamArrayDelegateRelaxation1Sub(paramarray b() as integer)
console.writeline("Hello from instance ParamArrayDelegateRelaxation1Sub.")
console.writeline(b(0) & " " & b(1))
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim arr(1) as integer
arr(0) = 23
arr(1) = 42
Dim d2 as new ParamArrayDelegateRelaxation1Delegate(AddressOf ci.ParamArrayDelegateRelaxation1Sub)
d2(arr)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArrayDelegateRelaxation1Sub.
23 42
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation4()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub ExpandedParamArrayDelegate(b as byte, b as byte, b as byte)
Class C
Public Sub ParamArraySub(b as byte, paramarray p() as Byte)
console.writeline("Hello from instance ParamArraySub.")
console.writeline(p)
console.writeline(p(0))
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d2 as new ExpandedParamArrayDelegate(AddressOf ci.ParamArraySub)
d2(1,2,3)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArraySub.
System.Byte[]
2
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation5()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Class Base
End Class
Class Derived
Inherits Base
End Class
Delegate Sub ExpandedParamArrayDelegate1(b as byte, b as Integer, b as Byte)
Delegate Sub ExpandedParamArrayDelegate2(b as byte, b as Base, b as Derived)
Class C
Public Sub ParamArraySub1(b as byte, paramarray p() as Integer)
console.writeline("Hello from instance ParamArraySub.")
console.writeline(p)
console.writeline(p(0))
console.writeline(p(1))
End Sub
Public Sub ParamArraySub2(b as byte, paramarray p() as Base)
console.writeline("Hello from instance ParamArraySub.")
console.writeline(p)
console.writeline(p(0))
console.writeline(p(1))
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new ExpandedParamArrayDelegate1(AddressOf ci.ParamArraySub1)
d1(1,2,3)
Dim d2 as new ExpandedParamArrayDelegate2(AddressOf ci.ParamArraySub2)
d2(1,new Derived(), new Derived())
d2(1,new Base(), new Derived())
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArraySub.
System.Int32[]
2
3
Hello from instance ParamArraySub.
Base[]
Derived
Derived
Hello from instance ParamArraySub.
Base[]
Base
Derived
]]>)
Next
End Sub
<Fact>
Public Sub ByRefParamArraysFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module M
Public Sub Main()
Dim d1 as DelegateByRefParamArray.DelegateSubWithParamArrayOfReferenceTypes = AddressOf SubWithParamArray
Dim bases(1) as DelegateByRefParamArray_Base
bases(0) = new DelegateByRefParamArray_Base(1)
bases(1) = new DelegateByRefParamArray_Base(2)
' does not work.
' d1(new DelegateByRefParamArray_Base(1), new DelegateByRefParamArray_Base(2))
d1(bases)
Console.WriteLine("SubWithParamArray returned: " & bases(0).field & " " & bases(1).field)
Dim d2 as DelegateByRefParamArray.DelegateSubWithByRefParamArrayOfReferenceTypes = AddressOf DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_2
' byref is ignored when calling through the delegate.
d2(bases)
Console.WriteLine("SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: " & bases(0).field & " " & bases(1).field)
' byref is also ignored when calling the method directly.
DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_2(bases)
Console.WriteLine("SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: " & bases(0).field & " " & bases(1).field)
End Sub
Public Sub SubWithParamArray(ParamArray p() as DelegateByRefParamArray_Base)
Console.WriteLine("Called SubWithParamArray: " & p(0).field & " " & p(1).field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
Called SubWithParamArray: 1 2
SubWithParamArray returned: 1 2
Called SubWithByRefParamArrayOfReferenceTypes_Identify_2.
SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: 1 2
Called SubWithByRefParamArrayOfReferenceTypes_Identify_2.
SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: 1 2
]]>)
End Sub
<Fact>
Public Sub ByRefParamArraysFromMetadataNarrowingBack()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module M
Delegate Sub ByRefArrayOfDerived(ByRef x as DelegateByRefParamArray_Derived())
Delegate Sub ByRefArrayOfBase(ByRef x as DelegateByRefParamArray_Base())
Public Sub Main()
' Testing:
' Delegate Sub (ByRef x as Derived())
' Sub TargetMethod(ByRef ParamArray x As Base())
' dev 10 does not create a stub and uses byval here.
Dim d3 as ByRefArrayOfDerived = AddressOf DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_1
Dim derived(1) as DelegateByRefParamArray_Derived
derived(0) = new DelegateByRefParamArray_Derived(1)
derived(1) = new DelegateByRefParamArray_Derived(2)
d3(derived)
Console.WriteLine("SubWithByRefParamArrayOfReferenceTypes_Identify_1 returned: " & derived(0).field & " " & derived(1).field)
' same as above, this time, delegate's last parameter is paramarray as well.
'
dim d4 as DelegateByRefParamArray.DelegateSubWithRefParamArrayOfReferenceTypesDerived = addressof DelegateByRefParamArray.ByRefParamArraySubOfBase
Dim arr2(1) as DelegateByRefParamArray_Derived
arr2(0) = new DelegateByRefParamArray_Derived(1)
arr2(1) = new DelegateByRefParamArray_Derived(2)
d4(arr2)
Console.WriteLine("ByRefParamArraySubOfBase returned: " & arr2(0).field & " " & arr2(1).field)
' testing Delegate Sub(ByRef x as Base()) with
' Sub goo (ByRef ParamArray x as Base())
dim d5 as ByRefArrayOfBase = addressof DelegateByRefParamArray.ByRefParamArraySubOfBase
Dim arr3(1) as DelegateByRefParamArray_Base
arr3(0) = new DelegateByRefParamArray_Base(1)
arr3(1) = new DelegateByRefParamArray_Base(2)
d5(arr3)
Console.WriteLine("ByRefParamArraySubOfBase returned: " & arr3(0).field & " " & arr3(1).field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
Called SubWithByRefParamArrayOfReferenceTypes_Identify_1.
SubWithByRefParamArrayOfReferenceTypes_Identify_1 returned: 1 2
ByRefParamArraySubOfBase returned: 1 2
ByRefParamArraySubOfBase returned: 23 42
]]>)
End Sub
<Fact>
Public Sub DelegatesWithParamArraysFromMetadataExpandParameters()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Module M
Public Sub Main()
Dim d1 as DelegateByRefParamArray.DelegateSubWithParamArrayOfReferenceTypes = AddressOf SubWithParamArray
d1(new DelegateByRefParamArray_Base(1), new DelegateByRefParamArray_Base(2))
Dim d2 as DelegateByRefParamArray.DelegateSubWithByRefParamArrayOfReferenceTypes = AddressOf DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_2
d2(new DelegateByRefParamArray_Base(1), new DelegateByRefParamArray_Base(2))
End Sub
Public Sub SubWithParamArray(ParamArray p() as DelegateByRefParamArray_Base)
Console.WriteLine("Called SubWithParamArray: " & p(0).field & " " & p(1).field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
Called SubWithParamArray: 1 2
Called SubWithByRefParamArrayOfReferenceTypes_Identify_2.
]]>)
Next
End Sub
<Fact>
Public Sub IgnoringTypeCharactersInAddressOf()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub MySub()
console.writeline("Ignored type characters ...")
End Sub
Function MyFunction() As String
console.writeline("Really ignored type characters ...")
Return ""
End Function
Sub Main()
Dim d1 As Action = AddressOf MySub%
Dim d2 As Func(Of String) = AddressOf MyFunction%
d1()
d2()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Ignored type characters ...
Really ignored type characters ...
]]>)
End Sub
<Fact>
Public Sub ConversionsOfUnexpandedParamArrays()
Dim source =
<compilation>
<file name="a.vb">
imports system
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Module1
Sub M1(paramarray x() As Base)
console.writeline("Hello from Delegate.")
End Sub
Sub M2(x As Action(Of Base()))
console.writeline("Sub M2(x As Action(Of Base())) called.")
Dim arr(0) as Base
arr(0) = new Derived()
x(arr)
End Sub
Sub M2(x As Action(Of Derived()))
console.writeline("Sub M2(x As Action(Of Derived())) called.")
Dim arr(0) as Derived
arr(0) = new Derived()
x(arr)
End Sub
Sub Main()
Dim x1 As Action(Of Base) = AddressOf M1
x1(new Derived())
Dim x2 As Action(Of Derived) = AddressOf M1
x2(new Derived())
M2(AddressOf M1)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from Delegate.
Hello from Delegate.
Sub M2(x As Action(Of Base())) called.
Hello from Delegate.
]]>)
End Sub
<Fact>
Public Sub NarrowingWarningForOptionStrictCustomReturnValues()
Dim source =
<compilation>
<file name="a.vb">
Imports system
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Module1
Delegate Function MyDelegate() as Derived
Public Function goo() as Base
return new Derived()
End Function
Sub Main()
Dim x1 As new MyDelegate(AddressOf goo)
Console.WriteLine(x1())
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom),
expectedOutput:=<![CDATA[
Derived
]]>)
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)).
AssertTheseDiagnostics(<expected>
BC42016: Implicit conversion from 'Base' to 'Derived'.
Dim x1 As new MyDelegate(AddressOf goo)
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NewDelegateWithLambdaExpression()
For Each OptionStrict In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
option strict <%= OptionStrict %>
IMPORTS SYStEM
Delegate Sub D1()
Delegate Function D2() as String
Module Program
Sub Main(args As String())
Dim x As New D1(Sub() Console.WriteLine("Hello from lambda."))
x
Dim y As New D2(Function() "Hello from lambda 2.")
console.writeline(y.Invoke())
Dim z as Func(Of String) = Function() "Hello from lambda 3."
console.writeline(z.Invoke())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from lambda.
Hello from lambda 2.
Hello from lambda 3.
]]>)
Next
End Sub
''' bug 7319
<Fact>
Public Sub AddressOfAndGenerics1()
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Bar(Of T)(ByVal x As T)
Console.WriteLine(x)
End Sub
Delegate Sub Goo(p as Byte)
Sub Main()
Dim x As new Goo(AddressOf Bar(Of String))
x.Invoke(23)
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(comp1, expectedOutput:="23")
End Sub
<Fact>
Public Sub ConversionsOptBackExceedTargetParameter()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Program
Delegate Sub DelByRefExpanded(ByRef a as DelegateByRefParamArray_Derived, ByRef b as DelegateByRefParamArray_Derived, ByRef b as DelegateByRefParamArray_Derived)
Sub Main()
' this does crash in Dev10. The bug was resolved as won't fix.
Dim x As DelByRefExpanded = addressof DelegateByRefParamArray.ByRefParamAndParamArraySubOfBase
dim derived0 as new DelegateByRefParamArray_Derived(1)
dim derived1 as new DelegateByRefParamArray_Derived(2)
dim derived2 as new DelegateByRefParamArray_Derived(3)
x(derived0, derived1, derived2)
Console.WriteLine("ByRefParamArraySubOfBase returned: " & derived0.field & " " & derived1.field & " " & derived2.field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
ByRefParamArraySubOfBase returned: 23 2 3
]]>)
End Sub
<Fact>
Public Sub CaptureReceiverUsedByStub()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Test1()
Test2()
Test3()
Test4()
Dim x As New C1()
x.Test5()
x.Test6()
Dim y As New S1()
y.Test7()
y.Test8()
Test11()
Test12()
Test13()
Test14()
Test15()
Test16()
Test17()
End Sub
Sub Test1()
System.Console.WriteLine("-- Test1 --")
Dim d As Func(Of Integer) = AddressOf SideEffect1().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test2()
System.Console.WriteLine("-- Test2 --")
Dim d As Func(Of Long) = AddressOf SideEffect1().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test3()
System.Console.WriteLine("-- Test3 --")
Dim d As Func(Of Integer) = AddressOf SideEffect2().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test4()
System.Console.WriteLine("-- Test4 --")
Dim d As Func(Of Long) = AddressOf SideEffect2().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test11()
System.Console.WriteLine("-- Test11 --")
Dim d As Func(Of Integer) = AddressOf SideEffect1().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test12()
System.Console.WriteLine("-- Test12 --")
Dim d As Func(Of Long) = AddressOf SideEffect1().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test13()
System.Console.WriteLine("-- Test13 --")
Dim d As Func(Of Integer) = AddressOf SideEffect2().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test14()
System.Console.WriteLine("-- Test14 --")
Dim d As Func(Of Long) = AddressOf SideEffect2().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test15()
System.Console.WriteLine("-- Test15 --")
Dim s As Object = New S1()
Dim d As Func(Of Integer) = AddressOf s.GetHashCode
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test16()
System.Console.WriteLine("-- Test16 --")
Dim s As Object = New S1()
Dim d As Func(Of Long) = AddressOf s.GetHashCode
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Public ReadOnly Property P1 As C1
Get
System.Console.WriteLine("P1")
Return New C1()
End Get
End Property
Sub Test17()
System.Console.WriteLine("-- Test17 --")
Dim d As Func(Of Integer) = AddressOf P1.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Function SideEffect1() As C1
System.Console.WriteLine("SideEffect1")
Return New C1()
End Function
Function SideEffect2() As S1
System.Console.WriteLine("SideEffect2")
Return New S1()
End Function
End Module
Class C1
Public f As Integer
Function F1() As Integer
f = f + 1
Return f
End Function
Shared Function F2() As Integer
Return 100
End Function
Sub Test5()
System.Console.WriteLine("-- Test5 --")
Dim d As Func(Of Integer) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
Sub Test6()
System.Console.WriteLine("-- Test6 --")
Dim d As Func(Of Long) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
End Class
Structure S1
Public f As Integer
Function F1() As Integer
f = f - 1
Return f
End Function
Shared Function F2() As Integer
Return -100
End Function
Sub Test7()
System.Console.WriteLine("-- Test7 --")
Dim d As Func(Of Integer) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
Sub Test8()
System.Console.WriteLine("-- Test8 --")
Dim d As Func(Of Long) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
Public Overrides Function GetHashCode() As Integer
f = f - 10
Return f
End Function
End Structure
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
-- Test1 --
SideEffect1
1
2
-- Test2 --
SideEffect1
1
2
-- Test3 --
SideEffect2
-1
-2
-- Test4 --
SideEffect2
-1
-2
-- Test5 --
1
2
2
-- Test6 --
3
4
4
-- Test7 --
-1
-2
0
-- Test8 --
-1
-2
0
-- Test11 --
100
100
-- Test12 --
100
100
-- Test13 --
-100
-100
-- Test14 --
-100
-100
-- Test15 --
-10
-20
-- Test16 --
-10
-20
-- Test17 --
P1
1
2
]]>)
End Sub
<WorkItem(9029, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub DelegateRelaxationConversions_Simple()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Test
Sub goo(x As Func(Of Exception, Exception), y As Func(Of Exception, ArgumentException), z As Func(Of Exception, ArgumentException), a As Func(Of Exception, Exception), b As Func(Of ArgumentException, Exception), c As Func(Of ArgumentException, Exception))
Console.WriteLine("goo")
End Sub
Sub Main()
Dim f1 As Func(Of Exception, ArgumentException) = Function(a As Exception) New ArgumentException()
Dim f2 As Func(Of ArgumentException, Exception) = Function(a As ArgumentException) New ArgumentException()
Dim f As Func(Of Exception, Exception) = Function(a As Exception) New ArgumentException
f = f2
f = f1
f1 = f2
f2 = f1
goo(f1, f1, f1, f1, f2, f2)
End Sub
End Module
</file>
</compilation>
Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
CompilationUtils.AssertTheseDiagnostics(c,
<expected>
BC42016: Implicit conversion from 'Func(Of ArgumentException, Exception)' to 'Func(Of Exception, Exception)'; this conversion may fail because 'Exception' is not derived from 'ArgumentException', as required for the 'In' generic parameter 'T' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f = f2
~~
BC42016: Implicit conversion from 'Func(Of ArgumentException, Exception)' to 'Func(Of Exception, ArgumentException)'; this conversion may fail because 'Exception' is not derived from 'ArgumentException', as required for the 'Out' generic parameter 'TResult' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f1 = f2
~~
</expected>)
c = c.WithOptions(c.Options.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(c,
<expected>
BC36755: 'Func(Of ArgumentException, Exception)' cannot be converted to 'Func(Of Exception, Exception)' because 'Exception' is not derived from 'ArgumentException', as required for the 'In' generic parameter 'T' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f = f2
~~
BC36754: 'Func(Of ArgumentException, Exception)' cannot be converted to 'Func(Of Exception, ArgumentException)' because 'Exception' is not derived from 'ArgumentException', as required for the 'Out' generic parameter 'TResult' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f1 = f2
~~
</expected>)
End Sub
<WorkItem(542068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542068")>
<Fact>
Public Sub DelegateBindingForGenericMethods01()
For Each OptionStrict In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= OptionStrict %>
Imports System
Imports System.Collections.Generic
' VB has different behavior between whether the below class is generic
' or non-generic. The below code produces no errors. However, if I get
' rid of the "(Of T, U)" bit in the below line, the code suddenly
' starts reporting error BC30794 (No 'goo' is most specific).
Public Class Runner(Of T, U)
Delegate Function Del1(Of TT, UU)(
x As TT,
y As List(Of TT),
z As Dictionary(Of List(Of TT), UU)) As UU
Delegate Sub Del2(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
'Most specific overload in Dev10 VB
'In Dev10 C# this overload is less specific - but in Dev10 VB this is (strangely) more specific
Sub goo(Of TT, UU, VV)(
xx As TT,
yy As UU,
zz As VV)
Console.Write("pass")
End Sub
'Can bind to this overload - but above overload is more specific in Dev10 VB
'In Dev10 C# this overload is more specific - but in Dev10 VB this is (strangely) less specific
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
Console.Write("fail")
End Sub
'Unrelated overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
Console.Write("fail2")
End Sub
Public Sub Run(Of AA, BB, CC)()
Dim d As Del2(Of AA, BB, CC) = AddressOf goo
Dim d2 As Del2(Of Long, Long, Long) = AddressOf goo
d(Nothing, Nothing, Nothing)
d2(Nothing, Nothing, Nothing)
End Sub
End Class
Module Runner
Sub Main()
Dim t As New Runner(Of Long, Long)
t.Run(Of Long, Long, Long)()
End Sub
End Module
</file>
</compilation>
Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
CompilationUtils.AssertNoErrors(c)
CompileAndVerify(c, expectedOutput:="passpass")
Next
End Sub
<Fact>
Public Sub DelegateBindingForGenericMethods02()
For Each OptionStrict In {"Off", "On"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= OptionStrict %>
Imports System
Imports System.Collections.Generic
Class Runner(Of T, U)
Delegate Function Del1(Of TT, UU)(
x As TT,
y As List(Of TT),
z As Dictionary(Of List(Of TT), UU)) As UU
Delegate Sub Del2(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
'Should bind to this overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
Console.Write("pass")
End Sub
'Unrelated overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
Console.Write("fail")
End Sub
Public Sub Run(Of AA, BB, CC)()
Dim d As Del2(Of AA, BB, CC) = AddressOf goo
Dim d2 As Del2(Of Long, Long, Long) = AddressOf goo
d(Nothing, Nothing, Nothing)
d2(Nothing, Nothing, Nothing)
End Sub
End Class
Module Test
Sub Main()
Dim t As New Runner(Of Long, Long)
t.Run(Of Long, Long, Long)()
End Sub
End Module
</file>
</compilation>
Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
CompilationUtils.AssertNoErrors(c)
CompileAndVerify(c, expectedOutput:="passpass")
Next
End Sub
<Fact>
Public Sub DelegateBindingForGenericMethods03()
For Each OptionStrict In {"Off", "On"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= OptionStrict %>
Imports System
Imports System.Collections.Generic
Class Runner(Of T, U)
Delegate Function Del1(Of TT, UU)(
x As TT,
y As List(Of TT),
z As Dictionary(Of List(Of TT), UU)) As UU
Delegate Sub Del2(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
'Should bind to this overload
Sub goo(Of TT, UU, VV)(
xx As TT,
yy As UU,
zz As VV)
Console.Write("pass")
End Sub
'Unrelated overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
Console.Write("fail")
End Sub
Public Sub Run(Of AA, BB, CC)()
Dim d As Del2(Of AA, BB, CC) = AddressOf goo
Dim d2 As Del2(Of Long, Long, Long) = AddressOf goo
d(Nothing, Nothing, Nothing)
d2(Nothing, Nothing, Nothing)
End Sub
End Class
Module Test
Sub Main()
Dim t As New Runner(Of Long, Long)
t.Run(Of Long, Long, Long)()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="passpass").VerifyDiagnostics()
Next
End Sub
<Fact()>
Public Sub ZeroArgumentRelaxationVsOtherNarrowing_1()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Test
Sub Test111(x As Integer)
System.Console.WriteLine("Test111(x As Integer)")
End Sub
Sub Test111(x As Byte)
System.Console.WriteLine("Test111(x As Byte)")
End Sub
Sub Test111()
System.Console.WriteLine("Test111()")
End Sub
Sub Main()
Dim ttt1 As Action(Of Long)
ttt1 = AddressOf Test111
ttt1(2)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="Test111()").VerifyDiagnostics()
End Sub
<WorkItem(544065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544065")>
<Fact()>
Public Sub Bug12211()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Class C1
Public Shared Narrowing Operator CType(ByVal arg As Long) As c1
Return New c1
End Operator
End Class
Class C3
Public Shared Sub goo(Optional ByVal y As C1 = Nothing)
res1 = "Correct Method called"
if y is nothing then
res1 = res1 & " and no parameter was passed."
end if
End Sub
Public shared sub goo(arg as integer)
End Sub
End Class
Delegate Sub goo6(ByVal arg As Long)
Friend Module DelOverl0020mod
Public res1 As String
Sub Main()
Dim d6 As goo6 = AddressOf c3.goo
d6(5L)
System.Console.WriteLine(res1)
End Sub
End Module
</file>
</compilation>
#If False Then
CompileAndVerify(source, expectedOutput:="Correct Method called and no parameter was passed.").VerifyDiagnostics().VerifyIL("DelOverl0020mod.Main",
<![CDATA[
{
// Code size 32 (0x20)
.maxstack 2
.locals init (goo6 V_0) //d6
IL_0000: ldnull
IL_0001: ldftn "Sub DelOverl0020mod._Lambda$__1(Long)"
IL_0007: newobj "Sub goo6..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.5
IL_000f: conv.i8
IL_0010: callvirt "Sub goo6.Invoke(Long)"
IL_0015: ldsfld "DelOverl0020mod.res1 As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>).VerifyIL("DelOverl0020mod._Lambda$__1",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: call "Sub C3.goo(C1)"
IL_0006: ret
}
]]>)
#Else
' According to the spec, zero argument relaxation can be used only when target method has NO parameters.
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30950: No accessible method 'goo' has a signature compatible with delegate 'Delegate Sub goo6(arg As Long)':
'Public Shared Sub goo([y As C1 = Nothing])': Argument matching parameter 'y' narrows from 'Long' to 'C1'.
'Public Shared Sub goo(arg As Integer)': Argument matching parameter 'arg' narrows from 'Long' to 'Integer'.
Dim d6 As goo6 = AddressOf c3.goo
~~~~~~
</expected>)
#End If
End Sub
<Fact(), WorkItem(545253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545253")>
Public Sub Bug13571()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C1
Event e As Action(Of Exception)
Sub Goo(ParamArray x() As Integer) Handles MyClass.e
End Sub
Sub Test()
Dim e1 As Action(Of Exception) = AddressOf Goo
End Sub
End Class
Class C2
Event e As Action(Of Exception)
Sub Goo(Optional x As Integer = 2) Handles MyClass.e
End Sub
Sub Test()
Dim e1 As Action(Of Exception) = AddressOf Goo
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC31029: Method 'Goo' cannot handle event 'e' because they do not have a compatible signature.
Sub Goo(ParamArray x() As Integer) Handles MyClass.e
~
BC31143: Method 'Public Sub Goo(ParamArray x As Integer())' does not have a signature compatible with delegate 'Delegate Sub Action(Of Exception)(obj As Exception)'.
Dim e1 As Action(Of Exception) = AddressOf Goo
~~~
BC31029: Method 'Goo' cannot handle event 'e' because they do not have a compatible signature.
Sub Goo(Optional x As Integer = 2) Handles MyClass.e
~
BC31143: Method 'Public Sub Goo([x As Integer = 2])' does not have a signature compatible with delegate 'Delegate Sub Action(Of Exception)(obj As Exception)'.
Dim e1 As Action(Of Exception) = AddressOf Goo
~~~
</expected>)
End Sub
<Fact>
Public Sub DelegateMethodDelegates()
Dim source =
<compilation>
<file>
Imports System
Class C
Dim invoke As Action
Dim beginInvoke As Func(Of AsyncCallback, Object, IAsyncResult)
Dim endInvoke As Action(Of IAsyncResult)
Dim dynamicInvoke As Func(Of Object(), Object)
Dim clone As Func(Of Object)
Dim eql As Func(Of Object, Boolean)
Sub M()
Dim a = New Action(AddressOf M)
invoke = New Action(AddressOf a.Invoke)
beginInvoke = New Func(Of AsyncCallback, Object, IAsyncResult)(AddressOf a.BeginInvoke)
endInvoke = New Action(Of IAsyncResult)(AddressOf a.EndInvoke)
dynamicInvoke = New Func(Of Object(), Object)(AddressOf a.DynamicInvoke)
clone = New Func(Of Object)(AddressOf a.Clone)
eql = New Func(Of Object, Boolean)(AddressOf a.Equals)
End Sub
End Class
</file>
</compilation>
' Dev11 emits ldvirtftn, we emit ldftn
CompileAndVerify(source).VerifyIL("C.M", <![CDATA[
{
// Code size 124 (0x7c)
.maxstack 3
.locals init (System.Action V_0) //a
IL_0000: ldarg.0
IL_0001: ldftn "Sub C.M()"
IL_0007: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldloc.0
IL_000f: ldftn "Sub System.Action.Invoke()"
IL_0015: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_001a: stfld "C.invoke As System.Action"
IL_001f: ldarg.0
IL_0020: ldloc.0
IL_0021: ldftn "Function System.Action.BeginInvoke(System.AsyncCallback, Object) As System.IAsyncResult"
IL_0027: newobj "Sub System.Func(Of System.AsyncCallback, Object, System.IAsyncResult)..ctor(Object, System.IntPtr)"
IL_002c: stfld "C.beginInvoke As System.Func(Of System.AsyncCallback, Object, System.IAsyncResult)"
IL_0031: ldarg.0
IL_0032: ldloc.0
IL_0033: ldftn "Sub System.Action.EndInvoke(System.IAsyncResult)"
IL_0039: newobj "Sub System.Action(Of System.IAsyncResult)..ctor(Object, System.IntPtr)"
IL_003e: stfld "C.endInvoke As System.Action(Of System.IAsyncResult)"
IL_0043: ldarg.0
IL_0044: ldloc.0
IL_0045: ldftn "Function System.Delegate.DynamicInvoke(ParamArray Object()) As Object"
IL_004b: newobj "Sub System.Func(Of Object(), Object)..ctor(Object, System.IntPtr)"
IL_0050: stfld "C.dynamicInvoke As System.Func(Of Object(), Object)"
IL_0055: ldarg.0
IL_0056: ldloc.0
IL_0057: dup
IL_0058: ldvirtftn "Function System.Delegate.Clone() As Object"
IL_005e: newobj "Sub System.Func(Of Object)..ctor(Object, System.IntPtr)"
IL_0063: stfld "C.clone As System.Func(Of Object)"
IL_0068: ldarg.0
IL_0069: ldloc.0
IL_006a: dup
IL_006b: ldvirtftn "Function System.MulticastDelegate.Equals(Object) As Boolean"
IL_0071: newobj "Sub System.Func(Of Object, Boolean)..ctor(Object, System.IntPtr)"
IL_0076: stfld "C.eql As System.Func(Of Object, Boolean)"
IL_007b: ret
}
]]>)
End Sub
<Fact(), WorkItem(629369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629369")>
Public Sub DelegateConversionOfNothing()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim f As Func(Of Integer, Integer)
Dim f2 = Function(x As Integer) x
f2 = Nothing
f = f2
Console.WriteLine(If(f Is Nothing, "pass", "fail"))
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="pass").VerifyDiagnostics()
End Sub
<Fact(), WorkItem(629369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629369")>
Public Sub DelegateConversionOfNothing_02()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim f As Func(Of Integer, Integer)
Dim f2 = Function(x As Integer) CShort(x)
f2 = Nothing
f = f2
Console.WriteLine(If(f Is Nothing, "pass", "fail"))
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="pass").VerifyDiagnostics()
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.Reflection
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenDelegateCreation
Inherits BasicTestBase
<Fact>
Public Sub DelegateMethods()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
' delegate as type
Delegate Function FuncDel(param1 as Integer, param2 as String) as Char
Class C2
public intMember as Integer
End Class
Class C1
' delegate as nested type
Delegate Sub SubDel(param1 as Integer, ByRef param2 as String)
Delegate Sub SubGenDel(Of T)(param1 as T)
Delegate Function FuncGenDel(Of T)(param1 as integer) as T
Shared Sub Main()
End Sub
End Class
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(c1, symbolValidator:=
Sub([module])
' Note: taking dev10 metadata as golden results, not the ECMA spec.
Dim reader = (DirectCast([module], PEModuleSymbol)).Module.GetMetadataReader()
Dim expectedMethodMethodFlags = MethodAttributes.Public Or MethodAttributes.NewSlot Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride
Dim expectedConstructorMethodFlags = MethodAttributes.Public Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName
' --- test SubDel methods -----------------------------------------------------------------------------------------------
Dim subDel = [module].GlobalNamespace.GetTypeMembers("C1").Single().GetTypeMembers("SubDel").Single()
' test .ctor
'.method public specialname rtspecialname instance void .ctor(object Instance, native int Method) runtime managed {}
Dim ctor = subDel.GetMembers(".ctor").OfType(Of MethodSymbol)().Single()
Assert.True(ctor.IsSub())
Assert.Equal("System.Void", ctor.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, ctor.Parameters.Length)
Assert.Equal("System.Object", ctor.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("TargetObject", ctor.Parameters(0).Name)
Assert.Equal("System.IntPtr", ctor.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("TargetMethod", ctor.Parameters(1).Name)
Dim methodDef = CType(ctor, PEMethodSymbol).Handle
Dim methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedConstructorMethodFlags, methodFlags)
Dim methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
Dim expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(ctor, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(ctor, PEMethodSymbol).IsRuntimeImplemented)
' test Invoke
' .method public newslot strict virtual instance void Invoke(int32 param1, string& param2) runtime managed {}
Dim invoke = subDel.GetMembers("Invoke").OfType(Of MethodSymbol)().Single()
Assert.True(invoke.IsSub())
Assert.Equal("System.Void", invoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, invoke.Parameters.Length)
Assert.Equal("System.Int32", invoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", invoke.Parameters(0).Name)
Assert.False(invoke.Parameters(0).IsByRef)
Assert.Equal("System.String", invoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", invoke.Parameters(1).Name)
Assert.True(invoke.Parameters(1).IsByRef)
methodDef = CType(invoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(invoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(invoke, PEMethodSymbol).IsRuntimeImplemented)
' test BeginInvoke
' .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult
' BeginInvoke(int32 param1,
' string& param2,
' class [mscorlib]System.AsyncCallback DelegateCallback,
' object DelegateAsyncState) runtime managed {}
Dim beginInvoke = subDel.GetMembers("BeginInvoke").OfType(Of MethodSymbol)().Single()
Assert.False(beginInvoke.IsSub())
Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(4, beginInvoke.Parameters.Length)
Assert.Equal("System.Int32", beginInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", beginInvoke.Parameters(0).Name)
Assert.False(beginInvoke.Parameters(0).IsByRef)
Assert.Equal("System.String", beginInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", beginInvoke.Parameters(1).Name)
Assert.True(beginInvoke.Parameters(1).IsByRef)
Assert.Equal("System.AsyncCallback", beginInvoke.Parameters(2).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateCallback", beginInvoke.Parameters(2).Name)
Assert.False(beginInvoke.Parameters(2).IsByRef)
Assert.Equal("System.Object", beginInvoke.Parameters(3).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncState", beginInvoke.Parameters(3).Name)
Assert.False(beginInvoke.Parameters(3).IsByRef)
methodDef = CType(beginInvoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(beginInvoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(beginInvoke, PEMethodSymbol).IsRuntimeImplemented)
' test EndInvoke
' .method public newslot strict virtual instance
' void EndInvoke(string& param2, class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed {}
Dim endInvoke = subDel.GetMembers("EndInvoke").OfType(Of MethodSymbol)().Single()
Assert.True(endInvoke.IsSub())
Assert.Equal("System.Void", endInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, endInvoke.Parameters.Length)
Assert.Equal("System.String", endInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", endInvoke.Parameters(0).Name)
Assert.True(endInvoke.Parameters(0).IsByRef)
Assert.Equal("System.IAsyncResult", endInvoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncResult", endInvoke.Parameters(1).Name)
Assert.False(endInvoke.Parameters(1).IsByRef)
methodDef = CType(endInvoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(endInvoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
Assert.True(CType(endInvoke, PEMethodSymbol).IsRuntimeImplemented)
' --- test FuncDel methods ----------------------------------------------------------------------------------------------
Dim funcDel = [module].GlobalNamespace.GetTypeMembers("FuncDel").Single()
' test Invoke
' .method public newslot strict virtual instance char Invoke(int32 param1, string param2) runtime managed
invoke = funcDel.GetMembers("Invoke").OfType(Of MethodSymbol)().Single()
Assert.False(invoke.IsSub())
Assert.Equal("System.Char", invoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(2, invoke.Parameters.Length)
Assert.Equal("System.Int32", invoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", invoke.Parameters(0).Name)
Assert.False(invoke.Parameters(0).IsByRef)
Assert.Equal("System.String", invoke.Parameters(1).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param2", invoke.Parameters(1).Name)
Assert.False(invoke.Parameters(1).IsByRef)
methodDef = CType(invoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(invoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
' test EndInvoke
' .method public newslot strict virtual instance
' charEndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed {}
endInvoke = funcDel.GetMembers("EndInvoke").OfType(Of MethodSymbol)().Single()
Assert.False(endInvoke.IsSub())
Assert.Equal("System.Char", endInvoke.ReturnType.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal(1, endInvoke.Parameters.Length)
Assert.Equal("System.IAsyncResult", endInvoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("DelegateAsyncResult", endInvoke.Parameters(0).Name)
Assert.False(endInvoke.Parameters(0).IsByRef)
methodDef = CType(endInvoke, PEMethodSymbol).Handle
methodFlags = reader.GetMethodDefinition(methodDef).Attributes
Assert.Equal(expectedMethodMethodFlags, methodFlags)
methodImplFlags = reader.GetMethodDefinition(methodDef).ImplAttributes
expectedMethodImplFlags = MethodImplAttributes.Runtime
Assert.Equal(expectedMethodImplFlags, methodImplFlags)
'Assert.True(CType(endInvoke, PEMethodSymbol).IsImplicitlyDeclared) ' does not work for PEMethodSymbols
' --- test FuncGenDel methods -------------------------------------------------------------------------------------------
Dim subGenDel = [module].GlobalNamespace.GetTypeMembers("C1").Single().GetTypeMembers("SubGenDel").Single()
' test Invoke
' .method public newslot strict virtual instance char Invoke(int32 param1, string param2) runtime managed
invoke = subGenDel.GetMembers("Invoke").OfType(Of MethodSymbol)().Single()
Assert.True(invoke.IsSub())
Assert.Equal(1, invoke.Parameters.Length)
Assert.Equal("T", invoke.Parameters(0).Type.ToDisplayString(SymbolDisplayFormat.TestFormat))
Assert.Equal("param1", invoke.Parameters(0).Name)
Assert.False(invoke.Parameters(0).IsByRef)
Assert.True(CType(invoke, PEMethodSymbol).IsRuntimeImplemented)
End Sub)
Next
End Sub
' Test module method, shared method, instance method, constructor, property with valid args for both function and sub delegate
<Fact>
Public Sub ValidDelegateAddressOfTest()
For Each optionValue In {"On", "Off"}
Dim source = <compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub SubDel(p As String)
Delegate function FuncDel(p As String) as Integer
Module M1
Public Sub ds1(p As String)
End Sub
Public Function df1(p As String) As Integer
return 23
End Function
End Module
Class C1
Public Sub ds2(p As String)
End Sub
Public Function df2(p As String) As Integer
return 23
End Function
Public Shared Sub ds3(p As String)
End Sub
Public Shared Function df3(p As String) As Integer
return 23
End Function
End Class
Class C2
Public Sub AssignDelegates()
Dim ci As New C1()
Dim ds As SubDel
ds = AddressOf M1.ds1
Console.WriteLine(ds)
ds = AddressOf ci.ds2
Console.WriteLine(ds)
ds = AddressOf C1.ds3
Console.WriteLine(ds)
End Sub
End Class
Module Program
Sub Main(args As String())
Dim c as new C2()
c.AssignDelegates()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
SubDel
SubDel
SubDel
]]>).
VerifyIL("C2.AssignDelegates",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 3
IL_0000: newobj "Sub C1..ctor()"
IL_0005: ldnull
IL_0006: ldftn "Sub M1.ds1(String)"
IL_000c: newobj "Sub SubDel..ctor(Object, System.IntPtr)"
IL_0011: call "Sub System.Console.WriteLine(Object)"
IL_0016: ldftn "Sub C1.ds2(String)"
IL_001c: newobj "Sub SubDel..ctor(Object, System.IntPtr)"
IL_0021: call "Sub System.Console.WriteLine(Object)"
IL_0026: ldnull
IL_0027: ldftn "Sub C1.ds3(String)"
IL_002d: newobj "Sub SubDel..ctor(Object, System.IntPtr)"
IL_0032: call "Sub System.Console.WriteLine(Object)"
IL_0037: ret
}
]]>)
Next
End Sub
''' Bug 5987 "Target parameter of a delegate instantiation is not boxed in case of a structure"
<Fact>
Public Sub DelegateInvocationStructureTests()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub SubDel(p As String)
Delegate function FuncDel(p As String) as Integer
Structure S1
Public Sub ds4(p As String)
Console.WriteLine("S1.ds4 " + p)
End Sub
Public Function df4(p As String) As Integer
return 4
End Function
Public Shared Sub ds5(p As String)
Console.WriteLine("S1.ds5 " + p)
End Sub
Public Shared Function df5(p As String) As Integer
return 5
End Function
End Structure
Module Program
Sub Main(args As String())
Dim ds As SubDel
Dim s as new S1()
ds = AddressOf s.ds4
ds.Invoke("(passed arg)")
ds = AddressOf S1.ds5
ds.Invoke("(passed arg)")
Moo("Hi")
Moo(42)
End Sub
Sub Moo(of T)(x as T)
Dim f as Func(of String) = AddressOf x.ToString
Console.WriteLine(f.Invoke())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
S1.ds4 (passed arg)
S1.ds5 (passed arg)
Hi
42
]]>)
Next
End Sub
<Fact>
Public Sub DelegateInvocationTests()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub SubDel(Of T)(p As T)
Delegate function FuncDel(p As Integer) as Integer
Module M1
Public Sub ds1(p As String)
Console.WriteLine("M1.ds1 " + p)
End Sub
Public Function df1(p As Integer) As Integer
return 1 + p
End Function
End Module
Class C1
Public Sub ds2(p As String)
Console.WriteLine("C1.ds2 " + p)
End Sub
Public Function df2(p As Integer) As Integer
return 2 + p
End Function
Public Shared Sub ds3(p As String)
Console.WriteLine("C1.ds3 " + p)
End Sub
Public Shared Function df3(p As Integer) As Integer
return 3 + p
End Function
End Class
Module Program
Sub Main(args As String())
Dim ds As SubDel(of string)
ds = AddressOf M1.ds1
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim ci As New C1()
ds = AddressOf ci.ds2
ds.Invoke("(passed arg)")
ds("(passed arg)")
ds = AddressOf C1.ds3
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim df As FuncDel
Dim target as Integer
df = AddressOf M1.df1
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf ci.df2
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf C1.df3
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
M1.ds1 (passed arg)
M1.ds1 (passed arg)
C1.ds2 (passed arg)
C1.ds2 (passed arg)
C1.ds3 (passed arg)
C1.ds3 (passed arg)
42
42
43
43
44
44
]]>)
Next
End Sub
<Fact>
Public Sub DelegateInvocationDelegatesFromMetadataTests()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Module M1
Public Sub ds1(p$)
Console.WriteLine("M1.ds1 " + p)
End Sub
Public Function df1(p%) As Integer
Return 1 + p
End Function
End Module
Class C1
Public Sub ds2(p As String)
Console.WriteLine("C1.ds2 " + p)
End Sub
Public Function df2%(p As Integer)
Return 2 + p
End Function
Public Shared Sub ds3(p As String)
Console.WriteLine("C1.ds3 " + p)
End Sub
Public Shared Function df3(p As Integer) As Integer
Return 3 + p
End Function
End Class
Module Program
Sub Main(args As String())
Dim ds As Action(Of String)
ds = AddressOf M1.ds1
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim ci As New C1()
ds = AddressOf ci.ds2
ds.Invoke("(passed arg)")
ds("(passed arg)")
ds = AddressOf C1.ds3
ds.Invoke("(passed arg)")
ds("(passed arg)")
Dim df As Func(Of Integer, Integer)
Dim target As Integer
df = AddressOf M1.df1
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf ci.df2
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
df = AddressOf C1.df3
target = df.Invoke(41)
Console.WriteLine(target)
target = df(41)
Console.WriteLine(target)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
M1.ds1 (passed arg)
M1.ds1 (passed arg)
C1.ds2 (passed arg)
C1.ds2 (passed arg)
C1.ds3 (passed arg)
C1.ds3 (passed arg)
42
42
43
43
44
44
]]>)
Next
End Sub
<Fact>
Public Sub Error_ERR_AddressOfNotCreatableDelegate1()
Dim source = <compilation>
<file name="a.vb">
Imports System
Delegate Sub SubDel(p As String)
Class C2
Public Shared Sub goo(p as string)
end sub
Public Sub AssignDelegates()
Dim v1 As System.Delegate = AddressOf goo
Dim v2 As System.MulticastDelegate = AddressOf C2.goo
End Sub
End Class
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected>
BC30939: 'AddressOf' expression cannot be converted to '[Delegate]' because type '[Delegate]' is declared 'MustInherit' and cannot be created.
Dim v1 As System.Delegate = AddressOf goo
~~~~~~~~~~~~~
BC30939: 'AddressOf' expression cannot be converted to 'MulticastDelegate' because type 'MulticastDelegate' is declared 'MustInherit' and cannot be created.
Dim v2 As System.MulticastDelegate = AddressOf C2.goo
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NewDelegateWithAddressOf()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
IMPORTS SYStEM
Delegate Sub D()
Class C1
public field as string = ""
public sub new(param as string)
field = param
end sub
public sub goo()
console.writeline("Hello " & Me.field)
end sub
public shared sub goo2()
console.writeline("... and again.")
end sub
end class
Module Program
Sub Main(args As String())
Dim x As D
x = New D(AddressOf Method)
x
Dim c as new C1("again.")
Dim y as new D(addressof c.goo)
y
Dim z as new D(addressof C1.goo2)
z
End Sub
Public Sub Method()
console.writeline("Hello.")
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello.
Hello again.
... and again.
]]>)
Next
End Sub
<Fact>
Public Sub WideningArgumentsDelegateSubRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub WideningNumericDelegate(p as Byte)
Delegate Sub WideningStringDelegate(p as Char)
Delegate Sub WideningNullableDelegate(p as Byte?)
Delegate Sub WideningReferenceDelegate(p as Derived)
Delegate Sub WideningArrayDelegate(p() as Derived)
Delegate Sub WideningValueDelegate(p as S1)
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Sub WideningNumericSub(p as Integer)
console.writeline("Hello from instance WideningNumericDelegate " & p.ToString() )
End Sub
Public Sub WideningStringSub(p as String)
console.writeline("Hello from instance WideningStringDelegate " & p.ToString() )
End Sub
Public Sub WideningNullableSub(p as Integer?)
console.writeline("Hello from instance WideningNullableDelegate " & p.ToString() )
End Sub
Public Sub WideningReferenceSub(p as Base)
console.writeline("Hello from instance WideningReferenceDelegate " & p.ToString() )
End Sub
Public Sub WideningArraySub(p() as Base)
console.writeline("Hello from instance WideningArrayDelegate " & p.ToString() )
End Sub
Public Sub WideningValueSub(p as Object)
console.writeline("Hello from instance WideningValueDelegate " & p.ToString() )
End Sub
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
Dim ci as new C()
Dim d1 as new WideningNumericDelegate(AddressOf ci.WideningNumericSub)
d1(23)
Dim d2 as new WideningStringDelegate(AddressOf ci.WideningStringSub)
d2("c"c)
'Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableSub)
'd3(n)
Dim d4 as new WideningReferenceDelegate(AddressOf ci.WideningReferenceSub)
d4(new Derived())
Dim d5 as new WideningArrayDelegate(AddressOf ci.WideningArraySub)
d5( arr )
Dim d6 as new WideningValueDelegate(AddressOf ci.WideningValueSub)
d6(new S1())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNumericDelegate 23
Hello from instance WideningStringDelegate c
Hello from instance WideningReferenceDelegate Derived
Hello from instance WideningArrayDelegate Derived[]
Hello from instance WideningValueDelegate S1
]]>)
Next
End Sub
''' Bug 7191: "Lambda rewriter does not work for widening conversions of byref params with option strict off"
<Fact>
Public Sub WideningArgumentsDelegateSubRelaxationByRefStrictOff()
For Each optionValue In {"Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub WideningNumericDelegate(byref p as Byte)
Delegate Sub WideningStringDelegate(byref p as Char)
Delegate Sub WideningNullableDelegate(byref p as Byte?)
Delegate Sub WideningReferenceDelegate(byref p as Derived)
Delegate Sub WideningArrayDelegate(byref p() as Derived)
Delegate Sub WideningValueDelegate(byref p as S1)
Structure S1
public field as integer
Public sub New(p as integer)
field = p
end sub
End Structure
Class Base
public field as integer
End Class
Class Derived
Inherits Base
Public sub New(p as integer)
field = p
end sub
End Class
Class C
Public Sub WideningNumericSub(byref p as Integer)
console.writeline("Hello from instance WideningNumericDelegate " & p.ToString() )
p = 42
End Sub
Public Sub WideningStringSub(byref p as String)
console.writeline("Hello from instance WideningStringDelegate " & p.ToString() )
p = "touched"
End Sub
'Public Sub WideningNullableSub(byref p as Integer?)
' console.writeline("Hello from instance WideningNullableDelegate " & p.ToString() )
' p = 42
'End Sub
Public Sub WideningReferenceSub(byref p as Base)
console.writeline("Hello from instance WideningReferenceDelegate " & p.ToString() )
p = new Derived(42)
End Sub
Public Sub WideningArraySub(byref p() as Base)
console.writeline("Hello from instance WideningArrayDelegate " & p.ToString() )
Dim arr(1) as Derived
arr(0) = new Derived(23)
arr(1) = new Derived(42)
p = arr
End Sub
Public Sub WideningValueSub(byref p as Object)
console.writeline("Hello from instance WideningValueDelegate " & p.ToString() )
p = new S1(42)
End Sub
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived(1)
arr(1) = new Derived(2)
Dim ci as new C()
Dim d1 as new WideningNumericDelegate(AddressOf ci.WideningNumericSub)
dim pbyte as byte = 23
d1(pbyte)
console.writeline(pbyte)
Dim d2 as new WideningStringDelegate(AddressOf ci.WideningStringSub)
dim pchar as char = "c"c
d2(pchar)
console.writeline(pchar)
'Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableSub)
'd3(n)
'console.writeline(n.Value)
Dim d4 as new WideningReferenceDelegate(AddressOf ci.WideningReferenceSub)
dim pderived as Derived = new Derived(23)
d4(pderived)
console.writeline(pderived.field)
Dim d5 as new WideningArrayDelegate(AddressOf ci.WideningArraySub)
d5( arr )
console.writeline(arr(0).field & " " & arr(1).field)
Dim d6 as new WideningValueDelegate(AddressOf ci.WideningValueSub)
dim ps1 as S1 = new S1(23)
d6(ps1)
console.writeline(ps1.field)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNumericDelegate 23
42
Hello from instance WideningStringDelegate c
t
Hello from instance WideningReferenceDelegate Derived
42
Hello from instance WideningArrayDelegate Derived[]
23 42
Hello from instance WideningValueDelegate S1
42
]]>)
Next
End Sub
<Fact()>
Public Sub WideningArgumentsDelegateSubRelaxation_nullable()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub WideningNullableDelegate(p as Byte?)
Class C
Public Sub WideningNullableSub(p as Integer?)
console.writeline("Hello from instance WideningNullableDelegate " & p.Value.ToString() )
End Sub
End Class
Module Program
Sub Main(args As String())
Dim n? As Byte = 23
Dim ci as new C()
Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableSub)
d3(n)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNullableDelegate 23
]]>)
Next
End Sub
<Fact>
Public Sub IdentityArgumentsDelegateSubRelaxationByRef()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub IdentityNumericDelegate(byref p as Byte)
Delegate Sub IdentityStringDelegate(byref p as Char)
Delegate Sub IdentityNullableDelegate(byref p as Byte?)
Delegate Sub IdentityReferenceDelegate(byref p as Derived)
Delegate Sub IdentityArrayDelegate(byref p() as Derived)
Delegate Sub IdentityValueDelegate(byref p as S1)
Structure S1
public field as integer
Public sub New(p as integer)
field = p
end sub
End Structure
Class Base
public field as integer
End Class
Class Derived
Inherits Base
Public sub New(p as integer)
field = p
end sub
End Class
Class C
Public Sub IdentityNumericSub(byref p as Byte)
console.writeline("Hello from instance IdentityNumericDelegate " & p.ToString() )
p = 42
End Sub
Public Sub IdentityStringSub(byref p as Char)
console.writeline("Hello from instance IdentityStringDelegate " & p.ToString() )
p = "t"c
End Sub
'Public Sub IdentityNullableSub(byref p as Byte?)
' console.writeline("Hello from instance IdentityNullableDelegate " & p.ToString() )
' p = 42
'End Sub
Public Sub IdentityReferenceSub(byref p as Derived)
console.writeline("Hello from instance IdentityReferenceDelegate " & p.ToString() )
p = new Derived(42)
End Sub
Public Sub IdentityArraySub(byref p() as Derived)
console.writeline("Hello from instance IdentityArrayDelegate " & p.ToString() )
Dim arr(1) as Derived
arr(0) = new Derived(23)
arr(1) = new Derived(42)
p = arr
End Sub
Public Sub IdentityValueSub(byref p as S1)
console.writeline("Hello from instance IdentityValueDelegate " & p.ToString() )
p = new S1(42)
End Sub
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived(1)
arr(1) = new Derived(2)
Dim ci as new C()
Dim d1 as new IdentityNumericDelegate(AddressOf ci.IdentityNumericSub)
dim pbyte as byte = 23
d1(pbyte)
console.writeline(pbyte)
Dim d2 as new IdentityStringDelegate(AddressOf ci.IdentityStringSub)
dim pchar as char = "c"c
d2(pchar)
console.writeline(pchar)
'Dim d3 as new IdentityNullableDelegate(AddressOf ci.IdentityNullableSub)
'd3(n)
'console.writeline(n.Value)
Dim d4 as new IdentityReferenceDelegate(AddressOf ci.IdentityReferenceSub)
dim pderived as Derived = new Derived(23)
d4(pderived)
console.writeline(pderived.field)
Dim d5 as new IdentityArrayDelegate(AddressOf ci.IdentityArraySub)
d5( arr )
console.writeline(arr(0).field & " " & arr(1).field)
Dim d6 as new IdentityValueDelegate(AddressOf ci.IdentityValueSub)
dim ps1 as S1 = new S1(23)
d6(ps1)
console.writeline(ps1.field)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance IdentityNumericDelegate 23
42
Hello from instance IdentityStringDelegate c
t
Hello from instance IdentityReferenceDelegate Derived
42
Hello from instance IdentityArrayDelegate Derived[]
23 42
Hello from instance IdentityValueDelegate S1
42
]]>)
Next
End Sub
<Fact>
Public Sub WideningArgumentsDelegateFunctionRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningNumericDelegate(p as byte, p as Byte) as integer
Delegate Function WideningStringDelegate(p as Char) as String
Delegate Function WideningNullableDelegate(p as Byte?) as integer
Delegate Function WideningReferenceDelegate(p as Derived) as integer
Delegate Function WideningArrayDelegate(p() as Derived) as integer
Delegate Function WideningValueDelegate(p as S1) as integer
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Function WideningNumericFunction(i as integer, p as Integer) as integer
console.writeline("Hello from instance WideningNumericDelegate ")
return 23
End Function
Public Function WideningStringFunction$(p as String)
console.writeline("Hello from instance WideningStringDelegate ")
return "24"
End Function
Public Function WideningNullableFunction(p as Integer?) as integer
console.writeline("Hello from instance WideningNullableDelegate ")
return 25
End Function
Public Function WideningReferenceFunction(p as Base) as integer
console.writeline("Hello from instance WideningReferenceDelegate ")
return 26
End Function
Public Function WideningArrayFunction(p() as Base) as integer
console.writeline("Hello from instance WideningArrayDelegate ")
return 27
End Function
Public Function WideningValueFunction(p as Object) as integer
console.writeline("Hello from instance WideningValueDelegate ")
return 28
End Function
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
Dim ci as new C()
Dim d1 as new WideningNumericDelegate(AddressOf ci.WideningNumericFunction)
console.writeline( d1(1, 23) )
Dim d2 as new WideningStringDelegate(AddressOf ci.WideningStringFunction)
console.writeline( d2("c"c) )
'Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableFunction)
'console.writeline( d3(n) )
Dim d4 as new WideningReferenceDelegate(AddressOf ci.WideningReferenceFunction)
console.writeline( d4(new Derived()) )
Dim d5 as new WideningArrayDelegate(AddressOf ci.WideningArrayFunction)
console.writeline( d5(arr) )
Dim d6 as new WideningValueDelegate(AddressOf ci.WideningValueFunction)
console.writeline( d6(new S1()) )
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNumericDelegate
23
Hello from instance WideningStringDelegate
24
Hello from instance WideningReferenceDelegate
26
Hello from instance WideningArrayDelegate
27
Hello from instance WideningValueDelegate
28
]]>)
Next
End Sub
<Fact()>
Public Sub WideningArgumentsDelegateFunctionRelaxation_nullable()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningNullableDelegate(p as Byte?) as integer
Class C
Public Function WideningNullableFunction(p as Integer?) as integer
console.writeline("Hello from instance WideningNullableDelegate ")
return 25
End Function
End Class
Module Program
Sub Main(args As String())
Dim n? As Byte = 23
Dim ci as new C()
Dim d3 as new WideningNullableDelegate(AddressOf ci.WideningNullableFunction)
console.writeline( d3(n) )
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningNullableDelegate
25
]]>)
Next
End Sub
<Fact>
Public Sub WideningReturnValueDelegateFunctionRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningReturnNumericDelegate() as Integer
Delegate Function WideningReturnStringDelegate() as String
'Delegate Function WideningReturnNullableDelegate() as Integer?
Delegate Function WideningReturnReferenceDelegate() as Base
Delegate Function WideningReturnArrayDelegate() as Base()
Delegate Function WideningReturnValueDelegate() as Object
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Function WideningReturnNumericFunction() as Byte
console.writeline("Hello from instance WideningReturnNumericFunction ")
return 23
End Function
Public Function WideningReturnStringFunction() as Char
console.writeline("Hello from instance WideningReturnStringFunction ")
return "A"c
End Function
'Public Function WideningReturnNullableFunction() as Byte?
' console.writeline("Hello from instance WideningReturnNullableFunction ")
' return 25
'End Function
Public Function WideningReturnReferenceFunction() as Derived
console.writeline("Hello from instance WideningReturnReferenceFunction ")
return new Derived()
End Function
Public Function WideningReturnArrayFunction() as Derived()
console.writeline("Hello from instance WideningReturnArrayFunction ")
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
return arr
End Function
Public Function WideningReturnValueFunction() as S1
console.writeline("Hello from instance WideningReturnValueFunction ")
return new S1()
End Function
End Class
Module Program
Sub Main(args As String())
'Dim n? As Integer' = 23
Dim ci as new C()
Dim d1 as new WideningReturnNumericDelegate(AddressOf ci.WideningReturnNumericFunction)
console.writeline( d1() )
Dim d2 as new WideningReturnStringDelegate(AddressOf ci.WideningReturnStringFunction)
console.writeline( d2() )
'Dim d3 as new WideningReturnNullableDelegate(AddressOf ci.WideningReturnNullableFunction)
'console.writeline( d3(n) )
Dim d4 as new WideningReturnReferenceDelegate(AddressOf ci.WideningReturnReferenceFunction)
console.writeline( d4() )
Dim d5 as new WideningReturnArrayDelegate(AddressOf ci.WideningReturnArrayFunction)
console.writeline( d5() )
Dim d6 as new WideningReturnValueDelegate(AddressOf ci.WideningReturnValueFunction)
console.writeline( d6() )
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningReturnNumericFunction
23
Hello from instance WideningReturnStringFunction
A
Hello from instance WideningReturnReferenceFunction
Derived
Hello from instance WideningReturnArrayFunction
Derived[]
Hello from instance WideningReturnValueFunction
S1
]]>)
Next
End Sub
<Fact()>
Public Sub WideningReturnValueDelegateFunctionRelaxation_nullable()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Function WideningReturnNullableDelegate() As Integer?
Class C
Public Function WideningReturnNullableFunction() As Byte?
console.writeline("Hello from instance WideningReturnNullableFunction ")
Return 25
End Function
End Class
Module Program
Sub Main(args As String())
Dim ci As New C()
Dim d3 As New WideningReturnNullableDelegate(AddressOf ci.WideningReturnNullableFunction)
Console.WriteLine((d3()).Value())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance WideningReturnNullableFunction
25
]]>)
Next
End Sub
<Fact>
Public Sub NarrowingArgumentsDelegateSubRelaxation()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Delegate Sub NarrowingNumericDelegate(pdel as Integer)
Delegate Sub NarrowingStringDelegate(pdel as String)
Delegate Sub NarrowingNullableDelegate(pdel as Integer?)
Delegate Sub NarrowingReferenceDelegate(pdel as Base)
Delegate Sub NarrowingArrayDelegate(pdel() as Base)
Delegate Sub NarrowingValueDelegate(pdel as Object)
Structure S1
End Structure
Class Base
End Class
Class Derived
Inherits Base
End Class
Class C
Public Sub NarrowingNumericSub(psub as Byte)
console.writeline("Hello from instance NarrowingNumericDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingStringSub(psub as Char)
console.writeline("Hello from instance NarrowingStringDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingNullableSub(psub as Byte?)
console.writeline("Hello from instance NarrowingNullableDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingReferenceSub(psub as Derived)
console.writeline("Hello from instance NarrowingReferenceDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingArraySub(psub() as Derived)
console.writeline("Hello from instance NarrowingArrayDelegate " & psub.ToString() )
End Sub
Public Sub NarrowingValueSub(psub as S1)
console.writeline("Hello from instance NarrowingValueDelegate")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim n? As Integer' = 23
Dim arr(1) as Derived
arr(0) = new Derived()
arr(1) = new Derived()
Dim ci as new C()
Dim d1 as new NarrowingNumericDelegate(AddressOf ci.NarrowingNumericSub)
d1(23)
Dim d2 as new NarrowingStringDelegate(AddressOf ci.NarrowingStringSub)
d2("c")
'Dim d3 as new NarrowingNullableDelegate(AddressOf ci.NarrowingNullableSub)
'd3(n)
Dim d4 as new NarrowingReferenceDelegate(AddressOf ci.NarrowingReferenceSub)
d4(new Derived())
Dim d5 as new NarrowingArrayDelegate(AddressOf ci.NarrowingArraySub)
d5(arr)
Dim d6 as new NarrowingValueDelegate(AddressOf ci.NarrowingValueSub)
d6(new S1())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance NarrowingNumericDelegate 23
Hello from instance NarrowingStringDelegate c
Hello from instance NarrowingReferenceDelegate Derived
Hello from instance NarrowingArrayDelegate Derived[]
Hello from instance NarrowingValueDelegate
]]>)
End Sub
<Fact()>
Public Sub NarrowingArgumentsDelegateSubRelaxation_nullable()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Delegate Sub NarrowingNullableDelegate(p as Integer?)
Class C
Public Sub NarrowingNullableSub(p as Byte?)
console.writeline("Hello from instance NarrowingNullableDelegate " & p.Value.ToString() )
End Sub
End Class
Module Program
Sub Main(args As String())
Dim n? As Integer = 23
Dim ci as new C()
Dim d3 as new NarrowingNullableDelegate(AddressOf ci.NarrowingNullableSub)
d3(n)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance NarrowingNullableDelegate 23
]]>)
End Sub
<Fact>
Public Sub OmittingArgumentsDelegateSubRelaxation_strictoff()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Delegate Sub OmittingArgumentsDelegate(p as Integer)
Class C
Public Sub OmittingArgumentsSub()
console.writeline("Hello from instance OmittingArgumentsDelegate.")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new OmittingArgumentsDelegate(AddressOf ci.OmittingArgumentsSub)
d1(23)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingArgumentsDelegate.
]]>)
End Sub
<Fact()>
Public Sub OmittingArgumentsDelegateSubRelaxation_lambda()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Delegate Sub OmittingArgumentsDelegate(p as Integer)
Module Program
Sub Main(args As String())
Dim d1 as new OmittingArgumentsDelegate(Sub() console.writeline("Hello from instance OmittingArgumentsDelegate."))
d1(23)
d1 = Sub() console.writeline("Hello from instance OmittingArgumentsDelegate.")
d1.Invoke(23)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingArgumentsDelegate.
Hello from instance OmittingArgumentsDelegate.
]]>)
End Sub
<Fact>
Public Sub OmittingReturnValueDelegateFunctionRelaxation()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub OmittingReturnValueDelegate(p as Integer)
Class C
Public Function OmittingReturnValueSub(p as Integer) as Integer
console.writeline("Hello from instance OmittingReturnValueSub.")
return 23
End Function
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new OmittingReturnValueDelegate(AddressOf ci.OmittingReturnValueSub)
d1(23)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingReturnValueSub.
]]>)
Next
End Sub
<Fact()>
Public Sub OmittingOptionalParameter()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub OmittingOptionalParameter1Delegate(p as Integer, p as Integer)
Delegate Sub OmittingOptionalParameter2Delegate(p as Integer)
Delegate Sub OmittingOptionalParameter3Delegate()
Class C
Public Sub OmittingOptionalParameter1Sub(optional a as integer = 23, optional b as integer = 42)
console.writeline("Hello from instance OmittingOptionalParameter1Sub.")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new OmittingOptionalParameter1Delegate(AddressOf ci.OmittingOptionalParameter1Sub)
d1(23, 23)
Dim d2 as new OmittingOptionalParameter2Delegate(AddressOf ci.OmittingOptionalParameter1Sub)
d2(23)
Dim d3 as new OmittingOptionalParameter3Delegate(AddressOf ci.OmittingOptionalParameter1Sub)
d3()
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance OmittingOptionalParameter1Sub.
Hello from instance OmittingOptionalParameter1Sub.
Hello from instance OmittingOptionalParameter1Sub.
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation1()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub ParamArrayInSubPerfectMatch1Delegate(pdel as Integer, pdel as Integer)
Delegate Sub ParamArrayInSubPerfectMatch2Delegate(p as Base, p as Base)
Delegate Sub ParamArrayInSubPerfectMatch3Delegate()
Delegate Sub ParamArrayInSubWideningMatch1Delegate(p as Integer, p as Byte)
Class Base
End Class
Class Derived
Inherits Base
end Class
Class C
Public Sub ParamArrayInSubPerfectMatch1Sub(paramarray p() as Integer)
console.writeline("Hello from instance ParamArrayInSubPerfectMatch1Sub.")
End Sub
Public Sub ParamArrayInSubPerfectMatch2Sub(paramarray p() as Base)
console.writeline("Hello from instance ParamArrayInSubPerfectMatch2Sub.")
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new ParamArrayInSubPerfectMatch1Delegate(AddressOf ci.ParamArrayInSubPerfectMatch1Sub)
d1(23, 23)
Dim d2 as new ParamArrayInSubPerfectMatch2Delegate(AddressOf ci.ParamArrayInSubPerfectMatch2Sub)
d2(new Derived(), new Derived())
Dim d3 as new ParamArrayInSubPerfectMatch3Delegate(AddressOf ci.ParamArrayInSubPerfectMatch2Sub)
d3()
Dim d4 as new ParamArrayInSubPerfectMatch3Delegate(AddressOf ci.ParamArrayInSubPerfectMatch1Sub)
d4()
Dim d5 as new ParamArrayInSubWideningMatch1Delegate(AddressOf ci.ParamArrayInSubPerfectMatch1Sub)
d5(23,42)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArrayInSubPerfectMatch1Sub.
Hello from instance ParamArrayInSubPerfectMatch2Sub.
Hello from instance ParamArrayInSubPerfectMatch2Sub.
Hello from instance ParamArrayInSubPerfectMatch1Sub.
Hello from instance ParamArrayInSubPerfectMatch1Sub.
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation2()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub ParamArrayDelegateRelaxation1Delegate(p() as Integer)
Class C
Public Sub ParamArrayDelegateRelaxation1Sub(paramarray b() as integer)
console.writeline("Hello from instance ParamArrayDelegateRelaxation1Sub.")
console.writeline(b(0) & " " & b(1))
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim arr(1) as integer
arr(0) = 23
arr(1) = 42
Dim d2 as new ParamArrayDelegateRelaxation1Delegate(AddressOf ci.ParamArrayDelegateRelaxation1Sub)
d2(arr)
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArrayDelegateRelaxation1Sub.
23 42
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation4()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Delegate Sub ExpandedParamArrayDelegate(b as byte, b as byte, b as byte)
Class C
Public Sub ParamArraySub(b as byte, paramarray p() as Byte)
console.writeline("Hello from instance ParamArraySub.")
console.writeline(p)
console.writeline(p(0))
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d2 as new ExpandedParamArrayDelegate(AddressOf ci.ParamArraySub)
d2(1,2,3)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArraySub.
System.Byte[]
2
]]>)
Next
End Sub
<Fact>
Public Sub ParamArrayDelegateRelaxation5()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Class Base
End Class
Class Derived
Inherits Base
End Class
Delegate Sub ExpandedParamArrayDelegate1(b as byte, b as Integer, b as Byte)
Delegate Sub ExpandedParamArrayDelegate2(b as byte, b as Base, b as Derived)
Class C
Public Sub ParamArraySub1(b as byte, paramarray p() as Integer)
console.writeline("Hello from instance ParamArraySub.")
console.writeline(p)
console.writeline(p(0))
console.writeline(p(1))
End Sub
Public Sub ParamArraySub2(b as byte, paramarray p() as Base)
console.writeline("Hello from instance ParamArraySub.")
console.writeline(p)
console.writeline(p(0))
console.writeline(p(1))
End Sub
End Class
Module Program
Sub Main(args As String())
Dim ci as new C()
Dim d1 as new ExpandedParamArrayDelegate1(AddressOf ci.ParamArraySub1)
d1(1,2,3)
Dim d2 as new ExpandedParamArrayDelegate2(AddressOf ci.ParamArraySub2)
d2(1,new Derived(), new Derived())
d2(1,new Base(), new Derived())
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from instance ParamArraySub.
System.Int32[]
2
3
Hello from instance ParamArraySub.
Base[]
Derived
Derived
Hello from instance ParamArraySub.
Base[]
Base
Derived
]]>)
Next
End Sub
<Fact>
Public Sub ByRefParamArraysFromMetadata()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module M
Public Sub Main()
Dim d1 as DelegateByRefParamArray.DelegateSubWithParamArrayOfReferenceTypes = AddressOf SubWithParamArray
Dim bases(1) as DelegateByRefParamArray_Base
bases(0) = new DelegateByRefParamArray_Base(1)
bases(1) = new DelegateByRefParamArray_Base(2)
' does not work.
' d1(new DelegateByRefParamArray_Base(1), new DelegateByRefParamArray_Base(2))
d1(bases)
Console.WriteLine("SubWithParamArray returned: " & bases(0).field & " " & bases(1).field)
Dim d2 as DelegateByRefParamArray.DelegateSubWithByRefParamArrayOfReferenceTypes = AddressOf DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_2
' byref is ignored when calling through the delegate.
d2(bases)
Console.WriteLine("SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: " & bases(0).field & " " & bases(1).field)
' byref is also ignored when calling the method directly.
DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_2(bases)
Console.WriteLine("SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: " & bases(0).field & " " & bases(1).field)
End Sub
Public Sub SubWithParamArray(ParamArray p() as DelegateByRefParamArray_Base)
Console.WriteLine("Called SubWithParamArray: " & p(0).field & " " & p(1).field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
Called SubWithParamArray: 1 2
SubWithParamArray returned: 1 2
Called SubWithByRefParamArrayOfReferenceTypes_Identify_2.
SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: 1 2
Called SubWithByRefParamArrayOfReferenceTypes_Identify_2.
SubWithByRefParamArrayOfReferenceTypes_Identify_2 returned: 1 2
]]>)
End Sub
<Fact>
Public Sub ByRefParamArraysFromMetadataNarrowingBack()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module M
Delegate Sub ByRefArrayOfDerived(ByRef x as DelegateByRefParamArray_Derived())
Delegate Sub ByRefArrayOfBase(ByRef x as DelegateByRefParamArray_Base())
Public Sub Main()
' Testing:
' Delegate Sub (ByRef x as Derived())
' Sub TargetMethod(ByRef ParamArray x As Base())
' dev 10 does not create a stub and uses byval here.
Dim d3 as ByRefArrayOfDerived = AddressOf DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_1
Dim derived(1) as DelegateByRefParamArray_Derived
derived(0) = new DelegateByRefParamArray_Derived(1)
derived(1) = new DelegateByRefParamArray_Derived(2)
d3(derived)
Console.WriteLine("SubWithByRefParamArrayOfReferenceTypes_Identify_1 returned: " & derived(0).field & " " & derived(1).field)
' same as above, this time, delegate's last parameter is paramarray as well.
'
dim d4 as DelegateByRefParamArray.DelegateSubWithRefParamArrayOfReferenceTypesDerived = addressof DelegateByRefParamArray.ByRefParamArraySubOfBase
Dim arr2(1) as DelegateByRefParamArray_Derived
arr2(0) = new DelegateByRefParamArray_Derived(1)
arr2(1) = new DelegateByRefParamArray_Derived(2)
d4(arr2)
Console.WriteLine("ByRefParamArraySubOfBase returned: " & arr2(0).field & " " & arr2(1).field)
' testing Delegate Sub(ByRef x as Base()) with
' Sub goo (ByRef ParamArray x as Base())
dim d5 as ByRefArrayOfBase = addressof DelegateByRefParamArray.ByRefParamArraySubOfBase
Dim arr3(1) as DelegateByRefParamArray_Base
arr3(0) = new DelegateByRefParamArray_Base(1)
arr3(1) = new DelegateByRefParamArray_Base(2)
d5(arr3)
Console.WriteLine("ByRefParamArraySubOfBase returned: " & arr3(0).field & " " & arr3(1).field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
Called SubWithByRefParamArrayOfReferenceTypes_Identify_1.
SubWithByRefParamArrayOfReferenceTypes_Identify_1 returned: 1 2
ByRefParamArraySubOfBase returned: 1 2
ByRefParamArraySubOfBase returned: 23 42
]]>)
End Sub
<Fact>
Public Sub DelegatesWithParamArraysFromMetadataExpandParameters()
For Each optionValue In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option strict <%= optionValue %>
Imports System
Module M
Public Sub Main()
Dim d1 as DelegateByRefParamArray.DelegateSubWithParamArrayOfReferenceTypes = AddressOf SubWithParamArray
d1(new DelegateByRefParamArray_Base(1), new DelegateByRefParamArray_Base(2))
Dim d2 as DelegateByRefParamArray.DelegateSubWithByRefParamArrayOfReferenceTypes = AddressOf DelegateByRefParamArray.SubWithByRefParamArrayOfReferenceTypes_Identify_2
d2(new DelegateByRefParamArray_Base(1), new DelegateByRefParamArray_Base(2))
End Sub
Public Sub SubWithParamArray(ParamArray p() as DelegateByRefParamArray_Base)
Console.WriteLine("Called SubWithParamArray: " & p(0).field & " " & p(1).field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
Called SubWithParamArray: 1 2
Called SubWithByRefParamArrayOfReferenceTypes_Identify_2.
]]>)
Next
End Sub
<Fact>
Public Sub IgnoringTypeCharactersInAddressOf()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub MySub()
console.writeline("Ignored type characters ...")
End Sub
Function MyFunction() As String
console.writeline("Really ignored type characters ...")
Return ""
End Function
Sub Main()
Dim d1 As Action = AddressOf MySub%
Dim d2 As Func(Of String) = AddressOf MyFunction%
d1()
d2()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Ignored type characters ...
Really ignored type characters ...
]]>)
End Sub
<Fact>
Public Sub ConversionsOfUnexpandedParamArrays()
Dim source =
<compilation>
<file name="a.vb">
imports system
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Module1
Sub M1(paramarray x() As Base)
console.writeline("Hello from Delegate.")
End Sub
Sub M2(x As Action(Of Base()))
console.writeline("Sub M2(x As Action(Of Base())) called.")
Dim arr(0) as Base
arr(0) = new Derived()
x(arr)
End Sub
Sub M2(x As Action(Of Derived()))
console.writeline("Sub M2(x As Action(Of Derived())) called.")
Dim arr(0) as Derived
arr(0) = new Derived()
x(arr)
End Sub
Sub Main()
Dim x1 As Action(Of Base) = AddressOf M1
x1(new Derived())
Dim x2 As Action(Of Derived) = AddressOf M1
x2(new Derived())
M2(AddressOf M1)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from Delegate.
Hello from Delegate.
Sub M2(x As Action(Of Base())) called.
Hello from Delegate.
]]>)
End Sub
<Fact>
Public Sub NarrowingWarningForOptionStrictCustomReturnValues()
Dim source =
<compilation>
<file name="a.vb">
Imports system
Class Base
End Class
Class Derived
Inherits Base
End Class
Module Module1
Delegate Function MyDelegate() as Derived
Public Function goo() as Base
return new Derived()
End Function
Sub Main()
Dim x1 As new MyDelegate(AddressOf goo)
Console.WriteLine(x1())
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom),
expectedOutput:=<![CDATA[
Derived
]]>)
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)).
AssertTheseDiagnostics(<expected>
BC42016: Implicit conversion from 'Base' to 'Derived'.
Dim x1 As new MyDelegate(AddressOf goo)
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NewDelegateWithLambdaExpression()
For Each OptionStrict In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
option strict <%= OptionStrict %>
IMPORTS SYStEM
Delegate Sub D1()
Delegate Function D2() as String
Module Program
Sub Main(args As String())
Dim x As New D1(Sub() Console.WriteLine("Hello from lambda."))
x
Dim y As New D2(Function() "Hello from lambda 2.")
console.writeline(y.Invoke())
Dim z as Func(Of String) = Function() "Hello from lambda 3."
console.writeline(z.Invoke())
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompileAndVerify(source,
expectedOutput:=<![CDATA[
Hello from lambda.
Hello from lambda 2.
Hello from lambda 3.
]]>)
Next
End Sub
''' bug 7319
<Fact>
Public Sub AddressOfAndGenerics1()
Dim comp1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Module M1
Sub Bar(Of T)(ByVal x As T)
Console.WriteLine(x)
End Sub
Delegate Sub Goo(p as Byte)
Sub Main()
Dim x As new Goo(AddressOf Bar(Of String))
x.Invoke(23)
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(comp1, expectedOutput:="23")
End Sub
<Fact>
Public Sub ConversionsOptBackExceedTargetParameter()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Program
Delegate Sub DelByRefExpanded(ByRef a as DelegateByRefParamArray_Derived, ByRef b as DelegateByRefParamArray_Derived, ByRef b as DelegateByRefParamArray_Derived)
Sub Main()
' this does crash in Dev10. The bug was resolved as won't fix.
Dim x As DelByRefExpanded = addressof DelegateByRefParamArray.ByRefParamAndParamArraySubOfBase
dim derived0 as new DelegateByRefParamArray_Derived(1)
dim derived1 as new DelegateByRefParamArray_Derived(2)
dim derived2 as new DelegateByRefParamArray_Derived(3)
x(derived0, derived1, derived2)
Console.WriteLine("ByRefParamArraySubOfBase returned: " & derived0.field & " " & derived1.field & " " & derived2.field)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source,
references:={TestReferences.SymbolsTests.DelegateImplementation.DelegateByRefParamArray},
expectedOutput:=<![CDATA[
ByRefParamArraySubOfBase returned: 23 2 3
]]>)
End Sub
<Fact>
Public Sub CaptureReceiverUsedByStub()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Test1()
Test2()
Test3()
Test4()
Dim x As New C1()
x.Test5()
x.Test6()
Dim y As New S1()
y.Test7()
y.Test8()
Test11()
Test12()
Test13()
Test14()
Test15()
Test16()
Test17()
End Sub
Sub Test1()
System.Console.WriteLine("-- Test1 --")
Dim d As Func(Of Integer) = AddressOf SideEffect1().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test2()
System.Console.WriteLine("-- Test2 --")
Dim d As Func(Of Long) = AddressOf SideEffect1().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test3()
System.Console.WriteLine("-- Test3 --")
Dim d As Func(Of Integer) = AddressOf SideEffect2().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test4()
System.Console.WriteLine("-- Test4 --")
Dim d As Func(Of Long) = AddressOf SideEffect2().F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test11()
System.Console.WriteLine("-- Test11 --")
Dim d As Func(Of Integer) = AddressOf SideEffect1().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test12()
System.Console.WriteLine("-- Test12 --")
Dim d As Func(Of Long) = AddressOf SideEffect1().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test13()
System.Console.WriteLine("-- Test13 --")
Dim d As Func(Of Integer) = AddressOf SideEffect2().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test14()
System.Console.WriteLine("-- Test14 --")
Dim d As Func(Of Long) = AddressOf SideEffect2().F2
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test15()
System.Console.WriteLine("-- Test15 --")
Dim s As Object = New S1()
Dim d As Func(Of Integer) = AddressOf s.GetHashCode
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Sub Test16()
System.Console.WriteLine("-- Test16 --")
Dim s As Object = New S1()
Dim d As Func(Of Long) = AddressOf s.GetHashCode
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Public ReadOnly Property P1 As C1
Get
System.Console.WriteLine("P1")
Return New C1()
End Get
End Property
Sub Test17()
System.Console.WriteLine("-- Test17 --")
Dim d As Func(Of Integer) = AddressOf P1.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
End Sub
Function SideEffect1() As C1
System.Console.WriteLine("SideEffect1")
Return New C1()
End Function
Function SideEffect2() As S1
System.Console.WriteLine("SideEffect2")
Return New S1()
End Function
End Module
Class C1
Public f As Integer
Function F1() As Integer
f = f + 1
Return f
End Function
Shared Function F2() As Integer
Return 100
End Function
Sub Test5()
System.Console.WriteLine("-- Test5 --")
Dim d As Func(Of Integer) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
Sub Test6()
System.Console.WriteLine("-- Test6 --")
Dim d As Func(Of Long) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
End Class
Structure S1
Public f As Integer
Function F1() As Integer
f = f - 1
Return f
End Function
Shared Function F2() As Integer
Return -100
End Function
Sub Test7()
System.Console.WriteLine("-- Test7 --")
Dim d As Func(Of Integer) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
Sub Test8()
System.Console.WriteLine("-- Test8 --")
Dim d As Func(Of Long) = AddressOf Me.F1
System.Console.WriteLine(d())
System.Console.WriteLine(d())
System.Console.WriteLine(f)
End Sub
Public Overrides Function GetHashCode() As Integer
f = f - 10
Return f
End Function
End Structure
</file>
</compilation>
CompileAndVerify(source,
expectedOutput:=<![CDATA[
-- Test1 --
SideEffect1
1
2
-- Test2 --
SideEffect1
1
2
-- Test3 --
SideEffect2
-1
-2
-- Test4 --
SideEffect2
-1
-2
-- Test5 --
1
2
2
-- Test6 --
3
4
4
-- Test7 --
-1
-2
0
-- Test8 --
-1
-2
0
-- Test11 --
100
100
-- Test12 --
100
100
-- Test13 --
-100
-100
-- Test14 --
-100
-100
-- Test15 --
-10
-20
-- Test16 --
-10
-20
-- Test17 --
P1
1
2
]]>)
End Sub
<WorkItem(9029, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub DelegateRelaxationConversions_Simple()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Test
Sub goo(x As Func(Of Exception, Exception), y As Func(Of Exception, ArgumentException), z As Func(Of Exception, ArgumentException), a As Func(Of Exception, Exception), b As Func(Of ArgumentException, Exception), c As Func(Of ArgumentException, Exception))
Console.WriteLine("goo")
End Sub
Sub Main()
Dim f1 As Func(Of Exception, ArgumentException) = Function(a As Exception) New ArgumentException()
Dim f2 As Func(Of ArgumentException, Exception) = Function(a As ArgumentException) New ArgumentException()
Dim f As Func(Of Exception, Exception) = Function(a As Exception) New ArgumentException
f = f2
f = f1
f1 = f2
f2 = f1
goo(f1, f1, f1, f1, f2, f2)
End Sub
End Module
</file>
</compilation>
Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
CompilationUtils.AssertTheseDiagnostics(c,
<expected>
BC42016: Implicit conversion from 'Func(Of ArgumentException, Exception)' to 'Func(Of Exception, Exception)'; this conversion may fail because 'Exception' is not derived from 'ArgumentException', as required for the 'In' generic parameter 'T' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f = f2
~~
BC42016: Implicit conversion from 'Func(Of ArgumentException, Exception)' to 'Func(Of Exception, ArgumentException)'; this conversion may fail because 'Exception' is not derived from 'ArgumentException', as required for the 'Out' generic parameter 'TResult' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f1 = f2
~~
</expected>)
c = c.WithOptions(c.Options.WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(c,
<expected>
BC36755: 'Func(Of ArgumentException, Exception)' cannot be converted to 'Func(Of Exception, Exception)' because 'Exception' is not derived from 'ArgumentException', as required for the 'In' generic parameter 'T' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f = f2
~~
BC36754: 'Func(Of ArgumentException, Exception)' cannot be converted to 'Func(Of Exception, ArgumentException)' because 'Exception' is not derived from 'ArgumentException', as required for the 'Out' generic parameter 'TResult' in 'Delegate Function Func(Of In T, Out TResult)(arg As T) As TResult'.
f1 = f2
~~
</expected>)
End Sub
<WorkItem(542068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542068")>
<Fact>
Public Sub DelegateBindingForGenericMethods01()
For Each OptionStrict In {"On", "Off"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= OptionStrict %>
Imports System
Imports System.Collections.Generic
' VB has different behavior between whether the below class is generic
' or non-generic. The below code produces no errors. However, if I get
' rid of the "(Of T, U)" bit in the below line, the code suddenly
' starts reporting error BC30794 (No 'goo' is most specific).
Public Class Runner(Of T, U)
Delegate Function Del1(Of TT, UU)(
x As TT,
y As List(Of TT),
z As Dictionary(Of List(Of TT), UU)) As UU
Delegate Sub Del2(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
'Most specific overload in Dev10 VB
'In Dev10 C# this overload is less specific - but in Dev10 VB this is (strangely) more specific
Sub goo(Of TT, UU, VV)(
xx As TT,
yy As UU,
zz As VV)
Console.Write("pass")
End Sub
'Can bind to this overload - but above overload is more specific in Dev10 VB
'In Dev10 C# this overload is more specific - but in Dev10 VB this is (strangely) less specific
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
Console.Write("fail")
End Sub
'Unrelated overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
Console.Write("fail2")
End Sub
Public Sub Run(Of AA, BB, CC)()
Dim d As Del2(Of AA, BB, CC) = AddressOf goo
Dim d2 As Del2(Of Long, Long, Long) = AddressOf goo
d(Nothing, Nothing, Nothing)
d2(Nothing, Nothing, Nothing)
End Sub
End Class
Module Runner
Sub Main()
Dim t As New Runner(Of Long, Long)
t.Run(Of Long, Long, Long)()
End Sub
End Module
</file>
</compilation>
Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
CompilationUtils.AssertNoErrors(c)
CompileAndVerify(c, expectedOutput:="passpass")
Next
End Sub
<Fact>
Public Sub DelegateBindingForGenericMethods02()
For Each OptionStrict In {"Off", "On"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= OptionStrict %>
Imports System
Imports System.Collections.Generic
Class Runner(Of T, U)
Delegate Function Del1(Of TT, UU)(
x As TT,
y As List(Of TT),
z As Dictionary(Of List(Of TT), UU)) As UU
Delegate Sub Del2(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
'Should bind to this overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
Console.Write("pass")
End Sub
'Unrelated overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
Console.Write("fail")
End Sub
Public Sub Run(Of AA, BB, CC)()
Dim d As Del2(Of AA, BB, CC) = AddressOf goo
Dim d2 As Del2(Of Long, Long, Long) = AddressOf goo
d(Nothing, Nothing, Nothing)
d2(Nothing, Nothing, Nothing)
End Sub
End Class
Module Test
Sub Main()
Dim t As New Runner(Of Long, Long)
t.Run(Of Long, Long, Long)()
End Sub
End Module
</file>
</compilation>
Dim c = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
CompilationUtils.AssertNoErrors(c)
CompileAndVerify(c, expectedOutput:="passpass")
Next
End Sub
<Fact>
Public Sub DelegateBindingForGenericMethods03()
For Each OptionStrict In {"Off", "On"}
Dim source =
<compilation>
<file name="a.vb">
Option Strict <%= OptionStrict %>
Imports System
Imports System.Collections.Generic
Class Runner(Of T, U)
Delegate Function Del1(Of TT, UU)(
x As TT,
y As List(Of TT),
z As Dictionary(Of List(Of TT), UU)) As UU
Delegate Sub Del2(Of TT, UU, VV)(
x As Func(Of TT, List(Of TT), UU, Dictionary(Of List(Of TT), UU)),
y As Del1(Of UU, VV),
z As Action(Of VV, List(Of VV), Dictionary(Of List(Of VV), TT)))
'Should bind to this overload
Sub goo(Of TT, UU, VV)(
xx As TT,
yy As UU,
zz As VV)
Console.Write("pass")
End Sub
'Unrelated overload
Sub goo(Of TT, UU, VV)(
x As Func(Of TT, UU, VV),
y As Func(Of UU, VV, TT),
z As Func(Of VV, TT, UU))
Console.Write("fail")
End Sub
Public Sub Run(Of AA, BB, CC)()
Dim d As Del2(Of AA, BB, CC) = AddressOf goo
Dim d2 As Del2(Of Long, Long, Long) = AddressOf goo
d(Nothing, Nothing, Nothing)
d2(Nothing, Nothing, Nothing)
End Sub
End Class
Module Test
Sub Main()
Dim t As New Runner(Of Long, Long)
t.Run(Of Long, Long, Long)()
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="passpass").VerifyDiagnostics()
Next
End Sub
<Fact()>
Public Sub ZeroArgumentRelaxationVsOtherNarrowing_1()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Test
Sub Test111(x As Integer)
System.Console.WriteLine("Test111(x As Integer)")
End Sub
Sub Test111(x As Byte)
System.Console.WriteLine("Test111(x As Byte)")
End Sub
Sub Test111()
System.Console.WriteLine("Test111()")
End Sub
Sub Main()
Dim ttt1 As Action(Of Long)
ttt1 = AddressOf Test111
ttt1(2)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="Test111()").VerifyDiagnostics()
End Sub
<WorkItem(544065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544065")>
<Fact()>
Public Sub Bug12211()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Class C1
Public Shared Narrowing Operator CType(ByVal arg As Long) As c1
Return New c1
End Operator
End Class
Class C3
Public Shared Sub goo(Optional ByVal y As C1 = Nothing)
res1 = "Correct Method called"
if y is nothing then
res1 = res1 & " and no parameter was passed."
end if
End Sub
Public shared sub goo(arg as integer)
End Sub
End Class
Delegate Sub goo6(ByVal arg As Long)
Friend Module DelOverl0020mod
Public res1 As String
Sub Main()
Dim d6 As goo6 = AddressOf c3.goo
d6(5L)
System.Console.WriteLine(res1)
End Sub
End Module
</file>
</compilation>
#If False Then
CompileAndVerify(source, expectedOutput:="Correct Method called and no parameter was passed.").VerifyDiagnostics().VerifyIL("DelOverl0020mod.Main",
<![CDATA[
{
// Code size 32 (0x20)
.maxstack 2
.locals init (goo6 V_0) //d6
IL_0000: ldnull
IL_0001: ldftn "Sub DelOverl0020mod._Lambda$__1(Long)"
IL_0007: newobj "Sub goo6..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.5
IL_000f: conv.i8
IL_0010: callvirt "Sub goo6.Invoke(Long)"
IL_0015: ldsfld "DelOverl0020mod.res1 As String"
IL_001a: call "Sub System.Console.WriteLine(String)"
IL_001f: ret
}
]]>).VerifyIL("DelOverl0020mod._Lambda$__1",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: call "Sub C3.goo(C1)"
IL_0006: ret
}
]]>)
#Else
' According to the spec, zero argument relaxation can be used only when target method has NO parameters.
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30950: No accessible method 'goo' has a signature compatible with delegate 'Delegate Sub goo6(arg As Long)':
'Public Shared Sub goo([y As C1 = Nothing])': Argument matching parameter 'y' narrows from 'Long' to 'C1'.
'Public Shared Sub goo(arg As Integer)': Argument matching parameter 'arg' narrows from 'Long' to 'Integer'.
Dim d6 As goo6 = AddressOf c3.goo
~~~~~~
</expected>)
#End If
End Sub
<Fact(), WorkItem(545253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545253")>
Public Sub Bug13571()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C1
Event e As Action(Of Exception)
Sub Goo(ParamArray x() As Integer) Handles MyClass.e
End Sub
Sub Test()
Dim e1 As Action(Of Exception) = AddressOf Goo
End Sub
End Class
Class C2
Event e As Action(Of Exception)
Sub Goo(Optional x As Integer = 2) Handles MyClass.e
End Sub
Sub Test()
Dim e1 As Action(Of Exception) = AddressOf Goo
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC31029: Method 'Goo' cannot handle event 'e' because they do not have a compatible signature.
Sub Goo(ParamArray x() As Integer) Handles MyClass.e
~
BC31143: Method 'Public Sub Goo(ParamArray x As Integer())' does not have a signature compatible with delegate 'Delegate Sub Action(Of Exception)(obj As Exception)'.
Dim e1 As Action(Of Exception) = AddressOf Goo
~~~
BC31029: Method 'Goo' cannot handle event 'e' because they do not have a compatible signature.
Sub Goo(Optional x As Integer = 2) Handles MyClass.e
~
BC31143: Method 'Public Sub Goo([x As Integer = 2])' does not have a signature compatible with delegate 'Delegate Sub Action(Of Exception)(obj As Exception)'.
Dim e1 As Action(Of Exception) = AddressOf Goo
~~~
</expected>)
End Sub
<Fact>
Public Sub DelegateMethodDelegates()
Dim source =
<compilation>
<file>
Imports System
Class C
Dim invoke As Action
Dim beginInvoke As Func(Of AsyncCallback, Object, IAsyncResult)
Dim endInvoke As Action(Of IAsyncResult)
Dim dynamicInvoke As Func(Of Object(), Object)
Dim clone As Func(Of Object)
Dim eql As Func(Of Object, Boolean)
Sub M()
Dim a = New Action(AddressOf M)
invoke = New Action(AddressOf a.Invoke)
beginInvoke = New Func(Of AsyncCallback, Object, IAsyncResult)(AddressOf a.BeginInvoke)
endInvoke = New Action(Of IAsyncResult)(AddressOf a.EndInvoke)
dynamicInvoke = New Func(Of Object(), Object)(AddressOf a.DynamicInvoke)
clone = New Func(Of Object)(AddressOf a.Clone)
eql = New Func(Of Object, Boolean)(AddressOf a.Equals)
End Sub
End Class
</file>
</compilation>
' Dev11 emits ldvirtftn, we emit ldftn
CompileAndVerify(source).VerifyIL("C.M", <![CDATA[
{
// Code size 124 (0x7c)
.maxstack 3
.locals init (System.Action V_0) //a
IL_0000: ldarg.0
IL_0001: ldftn "Sub C.M()"
IL_0007: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldloc.0
IL_000f: ldftn "Sub System.Action.Invoke()"
IL_0015: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_001a: stfld "C.invoke As System.Action"
IL_001f: ldarg.0
IL_0020: ldloc.0
IL_0021: ldftn "Function System.Action.BeginInvoke(System.AsyncCallback, Object) As System.IAsyncResult"
IL_0027: newobj "Sub System.Func(Of System.AsyncCallback, Object, System.IAsyncResult)..ctor(Object, System.IntPtr)"
IL_002c: stfld "C.beginInvoke As System.Func(Of System.AsyncCallback, Object, System.IAsyncResult)"
IL_0031: ldarg.0
IL_0032: ldloc.0
IL_0033: ldftn "Sub System.Action.EndInvoke(System.IAsyncResult)"
IL_0039: newobj "Sub System.Action(Of System.IAsyncResult)..ctor(Object, System.IntPtr)"
IL_003e: stfld "C.endInvoke As System.Action(Of System.IAsyncResult)"
IL_0043: ldarg.0
IL_0044: ldloc.0
IL_0045: ldftn "Function System.Delegate.DynamicInvoke(ParamArray Object()) As Object"
IL_004b: newobj "Sub System.Func(Of Object(), Object)..ctor(Object, System.IntPtr)"
IL_0050: stfld "C.dynamicInvoke As System.Func(Of Object(), Object)"
IL_0055: ldarg.0
IL_0056: ldloc.0
IL_0057: dup
IL_0058: ldvirtftn "Function System.Delegate.Clone() As Object"
IL_005e: newobj "Sub System.Func(Of Object)..ctor(Object, System.IntPtr)"
IL_0063: stfld "C.clone As System.Func(Of Object)"
IL_0068: ldarg.0
IL_0069: ldloc.0
IL_006a: dup
IL_006b: ldvirtftn "Function System.MulticastDelegate.Equals(Object) As Boolean"
IL_0071: newobj "Sub System.Func(Of Object, Boolean)..ctor(Object, System.IntPtr)"
IL_0076: stfld "C.eql As System.Func(Of Object, Boolean)"
IL_007b: ret
}
]]>)
End Sub
<Fact(), WorkItem(629369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629369")>
Public Sub DelegateConversionOfNothing()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim f As Func(Of Integer, Integer)
Dim f2 = Function(x As Integer) x
f2 = Nothing
f = f2
Console.WriteLine(If(f Is Nothing, "pass", "fail"))
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="pass").VerifyDiagnostics()
End Sub
<Fact(), WorkItem(629369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629369")>
Public Sub DelegateConversionOfNothing_02()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim f As Func(Of Integer, Integer)
Dim f2 = Function(x As Integer) CShort(x)
f2 = Nothing
f = f2
Console.WriteLine(If(f Is Nothing, "pass", "fail"))
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="pass").VerifyDiagnostics()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/VisualStudio/Core/Test/Snippets/VisualBasicSnippetExpansionClientTests.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
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets
Imports Microsoft.VisualStudio.Text.Projection
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets
<[UseExportProvider]>
Public Class VisualBasicSnippetExpansionClientTests
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_EmptyDocument() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"System"}
Dim expectedUpdatedCode = <![CDATA[Imports System
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_EmptyDocument_SystemAtTop() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"First.Alphabetically", "System.Bar"}
Dim expectedUpdatedCode = <![CDATA[Imports System.Bar
Imports First.Alphabetically
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_EmptyDocument_SystemNotSortedToTop() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"First.Alphabetically", "System.Bar"}
Dim expectedUpdatedCode = <![CDATA[Imports First.Alphabetically
Imports System.Bar
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=False, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_AddsOnlyNewNamespaces() As Task
Dim originalCode = <![CDATA[Imports A.B.C
Imports D.E.F
]]>.Value
Dim namespacesToAdd = {"D.E.F", "G.H.I"}
Dim expectedUpdatedCode = <![CDATA[Imports A.B.C
Imports D.E.F
Imports G.H.I
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact(Skip:="Issue #321"), Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_AddsOnlyNewAliasAndNamespacePairs() As Task
Dim originalCode = <![CDATA[Imports A = B.C
Imports D = E.F
Imports G = H.I
]]>.Value
Dim namespacesToAdd = {"A = E.F", "D = B.C", "G = H.I", "J = K.L"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
Imports A = E.F
Imports D = B.C
Imports D = E.F
Imports G = H.I
Imports J = K.L
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateNamespaceDetectionIgnoresCase() As Task
Dim originalCode = <![CDATA[Imports A.b.C
]]>.Value
Dim namespacesToAdd = {"a.B.C", "A.B.c"}
Dim expectedUpdatedCode = <![CDATA[Imports A.b.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateAliasNamespacePairDetectionIgnoresWhitespace1() As Task
Dim originalCode = <![CDATA[Imports A = B.C
]]>.Value
Dim namespacesToAdd = {"A = B.C"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateAliasNamespacePairDetectionIgnoresWhitespace2() As Task
Dim originalCode = <![CDATA[Imports A = B.C
]]>.Value
Dim namespacesToAdd = {"A=B.C"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateAliasNamespacePairDetectionIgnoresCase() As Task
Dim originalCode = <![CDATA[Imports A = B.C
]]>.Value
Dim namespacesToAdd = {"a = b.C"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_OnlyFormatNewImports() As Task
Dim originalCode = <![CDATA[Imports A = B.C
Imports G= H.I
]]>.Value
Dim namespacesToAdd = {"D =E.F"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
Imports D = E.F
Imports G= H.I
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_XmlNamespaceImport() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"<xmlns:db=""http://example.org/database-two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateXmlNamespaceDetectionIgnoresWhitespace1() As Task
Dim originalCode = <![CDATA[Imports <xmlns:db = "http://example.org/database-two">
]]>.Value
Dim namespacesToAdd = {"<xmlns:db=""http://example.org/database-two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db = "http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateXmlNamespaceDetectionIgnoresWhitespace2() As Task
Dim originalCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Dim namespacesToAdd = {"<xmlns:db = ""http://example.org/database-two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateXmlNamespaceDetectionIgnoresCase() As Task
Dim originalCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Dim namespacesToAdd = {"<xmlns:Db=""http://example.org/database-two"">", "<xmlns:db=""http://example.org/Database-Two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
<WorkItem(640961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640961")>
Public Async Function TestAddImport_BadNamespaceGetsAdded() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"$system"}
Dim expectedUpdatedCode = <![CDATA[Imports $system
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
<WorkItem(640961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640961")>
Public Async Function TestAddImport_TrailingTriviaIsIncluded() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"System.Data ' Trivia!"}
Dim expectedUpdatedCode = <![CDATA[Imports System.Data ' Trivia!
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
<WorkItem(640961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640961")>
Public Async Function TestAddImport_TrailingTriviaNotUsedInDuplicationDetection() As Task
Dim originalCode = <![CDATA[Imports System.Data ' Original trivia!
]]>.Value
Dim namespacesToAdd = {"System.Data ' Different trivia, should not be added!", "System ' Different namespace, should be added"}
Dim expectedUpdatedCode = <![CDATA[Imports System ' Different namespace, should be added
Imports System.Data ' Original trivia!
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_FullyInSubjectBuffer()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:For index = 1 to length
$$
Next|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|} |]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_FullyInSubjectBuffer2()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:For index = 1 to length
For index2 = 1 to length
$$
Next
Next|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|} |]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
For index2 = 1 to length
Next
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_ExpandedIntoSurfaceBuffer()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:For|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|} index = 1 to length
$$
Next|]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_FullyInSurfaceBuffer()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|}For index = 1 to length
$$
Next|]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfTheory, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
<InlineData(3)>
<InlineData(4)>
<InlineData(5)>
Public Sub TestFormattingWithTabSize(tabSize As Integer)
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
[|For index = 1 To 10
$$
Next|]
End Sub
End Class</Document>
</Project>
</Workspace>
Dim expectedResult = <Test>Class C
Sub M()
For index = 1 To 10
Next
End Sub
End Class</Test>
Using workspace = TestWorkspace.Create(workspaceXml, openDocuments:=False)
Dim document = workspace.Documents.Single()
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(FormattingOptions.UseTabs, document.Project.Language, True) _
.WithChangedOption(FormattingOptions.TabSize, document.Project.Language, tabSize) _
.WithChangedOption(FormattingOptions.IndentationSize, document.Project.Language, tabSize)))
Dim snippetExpansionClient = New SnippetExpansionClient(
workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Guids.CSharpLanguageServiceId,
document.GetTextView(),
document.GetTextBuffer(),
signatureHelpControllerProvider:=Nothing,
editorCommandHandlerServiceFactory:=Nothing,
Nothing,
workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)().ToImmutableArray())
SnippetExpansionClientTestsHelper.TestFormattingAndCaretPosition(snippetExpansionClient, document, expectedResult, tabSize * 3)
End Using
End Sub
Private Async Function TestSnippetAddImportsAsync(
markupCode As String,
namespacesToAdd As String(),
placeSystemNamespaceFirst As Boolean,
expectedUpdatedCode As String) As Tasks.Task
Dim originalCode As String = Nothing
Dim position As Integer?
MarkupTestFile.GetPosition(markupCode, originalCode, position)
Dim workspaceXml = <Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<CompilationOptions/>
<Document><%= originalCode %></Document>
</Project>
</Workspace>
Dim snippetNode = <Snippet>
<Imports>
</Imports>
</Snippet>
For Each namespaceToAdd In namespacesToAdd
snippetNode.Element("Imports").Add(<Import>
<Namespace><%= namespaceToAdd %></Namespace>
</Import>)
Next
Using workspace = TestWorkspace.Create(workspaceXml)
Dim expansionClient = New SnippetExpansionClient(
workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Guids.VisualBasicDebuggerLanguageId,
workspace.Documents.Single().GetTextView(),
workspace.Documents.Single().GetTextBuffer(),
signatureHelpControllerProvider:=Nothing,
editorCommandHandlerServiceFactory:=Nothing,
Nothing,
workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)().ToImmutableArray())
Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single()
Dim options = Await document.GetOptionsAsync(CancellationToken.None).ConfigureAwait(false)
options = options.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, placeSystemNamespaceFirst)
Dim updatedDocument = expansionClient.AddImports(
document,
options,
If(position, 0),
snippetNode,
allowInHiddenRegions:=False,
CancellationToken.None)
Assert.Equal(expectedUpdatedCode.Replace(vbLf, vbCrLf),
(Await updatedDocument.GetTextAsync()).ToString())
End Using
End Function
Public Sub TestFormatting(workspaceXmlWithSubjectBufferDocument As XElement, surfaceBufferDocumentXml As XElement, expectedSurfaceBuffer As XElement)
Using workspace = TestWorkspace.Create(workspaceXmlWithSubjectBufferDocument)
Dim subjectBufferDocument = workspace.Documents.Single()
Dim surfaceBufferDocument = workspace.CreateProjectionBufferDocument(
surfaceBufferDocumentXml.NormalizedValue,
{subjectBufferDocument},
options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim snippetExpansionClient = New SnippetExpansionClient(
workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Guids.CSharpLanguageServiceId,
surfaceBufferDocument.GetTextView(),
subjectBufferDocument.GetTextBuffer(),
signatureHelpControllerProvider:=Nothing,
editorCommandHandlerServiceFactory:=Nothing,
Nothing,
workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)().ToImmutableArray())
SnippetExpansionClientTestsHelper.TestProjectionBuffer(snippetExpansionClient, surfaceBufferDocument, expectedSurfaceBuffer)
End Using
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
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets
Imports Microsoft.VisualStudio.Text.Projection
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets
<[UseExportProvider]>
Public Class VisualBasicSnippetExpansionClientTests
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_EmptyDocument() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"System"}
Dim expectedUpdatedCode = <![CDATA[Imports System
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_EmptyDocument_SystemAtTop() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"First.Alphabetically", "System.Bar"}
Dim expectedUpdatedCode = <![CDATA[Imports System.Bar
Imports First.Alphabetically
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_EmptyDocument_SystemNotSortedToTop() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"First.Alphabetically", "System.Bar"}
Dim expectedUpdatedCode = <![CDATA[Imports First.Alphabetically
Imports System.Bar
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=False, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_AddsOnlyNewNamespaces() As Task
Dim originalCode = <![CDATA[Imports A.B.C
Imports D.E.F
]]>.Value
Dim namespacesToAdd = {"D.E.F", "G.H.I"}
Dim expectedUpdatedCode = <![CDATA[Imports A.B.C
Imports D.E.F
Imports G.H.I
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact(Skip:="Issue #321"), Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_AddsOnlyNewAliasAndNamespacePairs() As Task
Dim originalCode = <![CDATA[Imports A = B.C
Imports D = E.F
Imports G = H.I
]]>.Value
Dim namespacesToAdd = {"A = E.F", "D = B.C", "G = H.I", "J = K.L"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
Imports A = E.F
Imports D = B.C
Imports D = E.F
Imports G = H.I
Imports J = K.L
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateNamespaceDetectionIgnoresCase() As Task
Dim originalCode = <![CDATA[Imports A.b.C
]]>.Value
Dim namespacesToAdd = {"a.B.C", "A.B.c"}
Dim expectedUpdatedCode = <![CDATA[Imports A.b.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateAliasNamespacePairDetectionIgnoresWhitespace1() As Task
Dim originalCode = <![CDATA[Imports A = B.C
]]>.Value
Dim namespacesToAdd = {"A = B.C"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateAliasNamespacePairDetectionIgnoresWhitespace2() As Task
Dim originalCode = <![CDATA[Imports A = B.C
]]>.Value
Dim namespacesToAdd = {"A=B.C"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateAliasNamespacePairDetectionIgnoresCase() As Task
Dim originalCode = <![CDATA[Imports A = B.C
]]>.Value
Dim namespacesToAdd = {"a = b.C"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_OnlyFormatNewImports() As Task
Dim originalCode = <![CDATA[Imports A = B.C
Imports G= H.I
]]>.Value
Dim namespacesToAdd = {"D =E.F"}
Dim expectedUpdatedCode = <![CDATA[Imports A = B.C
Imports D = E.F
Imports G= H.I
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_XmlNamespaceImport() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"<xmlns:db=""http://example.org/database-two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateXmlNamespaceDetectionIgnoresWhitespace1() As Task
Dim originalCode = <![CDATA[Imports <xmlns:db = "http://example.org/database-two">
]]>.Value
Dim namespacesToAdd = {"<xmlns:db=""http://example.org/database-two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db = "http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateXmlNamespaceDetectionIgnoresWhitespace2() As Task
Dim originalCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Dim namespacesToAdd = {"<xmlns:db = ""http://example.org/database-two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Async Function TestAddImport_DuplicateXmlNamespaceDetectionIgnoresCase() As Task
Dim originalCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Dim namespacesToAdd = {"<xmlns:Db=""http://example.org/database-two"">", "<xmlns:db=""http://example.org/Database-Two"">"}
Dim expectedUpdatedCode = <![CDATA[Imports <xmlns:db="http://example.org/database-two">
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
<WorkItem(640961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640961")>
Public Async Function TestAddImport_BadNamespaceGetsAdded() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"$system"}
Dim expectedUpdatedCode = <![CDATA[Imports $system
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
<WorkItem(640961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640961")>
Public Async Function TestAddImport_TrailingTriviaIsIncluded() As Task
Dim originalCode = <![CDATA[]]>.Value
Dim namespacesToAdd = {"System.Data ' Trivia!"}
Dim expectedUpdatedCode = <![CDATA[Imports System.Data ' Trivia!
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
<WorkItem(640961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640961")>
Public Async Function TestAddImport_TrailingTriviaNotUsedInDuplicationDetection() As Task
Dim originalCode = <![CDATA[Imports System.Data ' Original trivia!
]]>.Value
Dim namespacesToAdd = {"System.Data ' Different trivia, should not be added!", "System ' Different namespace, should be added"}
Dim expectedUpdatedCode = <![CDATA[Imports System ' Different namespace, should be added
Imports System.Data ' Original trivia!
]]>.Value
Await TestSnippetAddImportsAsync(originalCode, namespacesToAdd, placeSystemNamespaceFirst:=True, expectedUpdatedCode:=expectedUpdatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_FullyInSubjectBuffer()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:For index = 1 to length
$$
Next|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|} |]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_FullyInSubjectBuffer2()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:For index = 1 to length
For index2 = 1 to length
$$
Next
Next|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|} |]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
For index2 = 1 to length
Next
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_ExpandedIntoSurfaceBuffer()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:For|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|} index = 1 to length
$$
Next|]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)>
Public Sub TestSnippetFormatting_ProjectionBuffer_FullyInSurfaceBuffer()
Dim workspaceXmlWithSubjectBufferDocument =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
@{|S1:|}
End Sub
End Class</Document>
</Project>
</Workspace>
Dim surfaceBufferDocument = <Document><div>
@[|{|S1:|}For index = 1 to length
$$
Next|]
</div></Document>
Dim expectedSurfaceBuffer = <SurfaceBuffer><div>
@For index = 1 to length
Next
</div></SurfaceBuffer>
TestFormatting(workspaceXmlWithSubjectBufferDocument, surfaceBufferDocument, expectedSurfaceBuffer)
End Sub
<WpfTheory, WorkItem(4652, "https://github.com/dotnet/roslyn/issues/4652")>
<Trait(Traits.Feature, Traits.Features.Snippets)>
<InlineData(3)>
<InlineData(4)>
<InlineData(5)>
Public Sub TestFormattingWithTabSize(tabSize As Integer)
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>Class C
Sub M()
[|For index = 1 To 10
$$
Next|]
End Sub
End Class</Document>
</Project>
</Workspace>
Dim expectedResult = <Test>Class C
Sub M()
For index = 1 To 10
Next
End Sub
End Class</Test>
Using workspace = TestWorkspace.Create(workspaceXml, openDocuments:=False)
Dim document = workspace.Documents.Single()
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _
.WithChangedOption(FormattingOptions.UseTabs, document.Project.Language, True) _
.WithChangedOption(FormattingOptions.TabSize, document.Project.Language, tabSize) _
.WithChangedOption(FormattingOptions.IndentationSize, document.Project.Language, tabSize)))
Dim snippetExpansionClient = New SnippetExpansionClient(
workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Guids.CSharpLanguageServiceId,
document.GetTextView(),
document.GetTextBuffer(),
signatureHelpControllerProvider:=Nothing,
editorCommandHandlerServiceFactory:=Nothing,
Nothing,
workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)().ToImmutableArray())
SnippetExpansionClientTestsHelper.TestFormattingAndCaretPosition(snippetExpansionClient, document, expectedResult, tabSize * 3)
End Using
End Sub
Private Async Function TestSnippetAddImportsAsync(
markupCode As String,
namespacesToAdd As String(),
placeSystemNamespaceFirst As Boolean,
expectedUpdatedCode As String) As Tasks.Task
Dim originalCode As String = Nothing
Dim position As Integer?
MarkupTestFile.GetPosition(markupCode, originalCode, position)
Dim workspaceXml = <Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<CompilationOptions/>
<Document><%= originalCode %></Document>
</Project>
</Workspace>
Dim snippetNode = <Snippet>
<Imports>
</Imports>
</Snippet>
For Each namespaceToAdd In namespacesToAdd
snippetNode.Element("Imports").Add(<Import>
<Namespace><%= namespaceToAdd %></Namespace>
</Import>)
Next
Using workspace = TestWorkspace.Create(workspaceXml)
Dim expansionClient = New SnippetExpansionClient(
workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Guids.VisualBasicDebuggerLanguageId,
workspace.Documents.Single().GetTextView(),
workspace.Documents.Single().GetTextBuffer(),
signatureHelpControllerProvider:=Nothing,
editorCommandHandlerServiceFactory:=Nothing,
Nothing,
workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)().ToImmutableArray())
Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single()
Dim options = Await document.GetOptionsAsync(CancellationToken.None).ConfigureAwait(false)
options = options.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, placeSystemNamespaceFirst)
Dim updatedDocument = expansionClient.AddImports(
document,
options,
If(position, 0),
snippetNode,
allowInHiddenRegions:=False,
CancellationToken.None)
Assert.Equal(expectedUpdatedCode.Replace(vbLf, vbCrLf),
(Await updatedDocument.GetTextAsync()).ToString())
End Using
End Function
Public Sub TestFormatting(workspaceXmlWithSubjectBufferDocument As XElement, surfaceBufferDocumentXml As XElement, expectedSurfaceBuffer As XElement)
Using workspace = TestWorkspace.Create(workspaceXmlWithSubjectBufferDocument)
Dim subjectBufferDocument = workspace.Documents.Single()
Dim surfaceBufferDocument = workspace.CreateProjectionBufferDocument(
surfaceBufferDocumentXml.NormalizedValue,
{subjectBufferDocument},
options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim snippetExpansionClient = New SnippetExpansionClient(
workspace.ExportProvider.GetExportedValue(Of IThreadingContext),
Guids.CSharpLanguageServiceId,
surfaceBufferDocument.GetTextView(),
subjectBufferDocument.GetTextBuffer(),
signatureHelpControllerProvider:=Nothing,
editorCommandHandlerServiceFactory:=Nothing,
Nothing,
workspace.ExportProvider.GetExports(Of ArgumentProvider, OrderableLanguageMetadata)().ToImmutableArray())
SnippetExpansionClientTestsHelper.TestProjectionBuffer(snippetExpansionClient, surfaceBufferDocument, expectedSurfaceBuffer)
End Using
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MetadataFileReferenceCompilationTests.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.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Roslyn.Test.Utilities
Public Class MetadataFileReferenceCompilationTests
Inherits BasicTestBase
<WorkItem(539480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539480")>
<WorkItem(1037628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems?_a=edit&id=1037628")>
<Fact>
Public Sub BC31011ERR_BadRefLib1()
Dim ref = MetadataReference.CreateFromImage({}, filePath:="Goo.dll")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadRefLib1">
<file name="a.vb">
Class C1
End Class
</file>
</compilation>)
compilation1 = compilation1.AddReferences(ref)
Dim expectedErrors1 = <errors>
BC31519: 'Goo.dll' cannot be referenced because it is not a valid assembly.
</errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(1037628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems?_a=edit&id=1037628")>
<Fact>
Public Sub BC31007ERR_BadModuleFile1()
Dim ref = ModuleMetadata.CreateFromImage({}).GetReference(filePath:="Goo.dll")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadRefLib1">
<file name="a.vb">
Class C1
End Class
</file>
</compilation>)
compilation1 = compilation1.AddReferences(ref)
Dim expectedErrors1 = <errors>
BC31007: Unable to load module file 'Goo.dll': PE image doesn't contain managed metadata.
</errors>
Using New EnsureEnglishUICulture
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Using
End Sub
<WorkItem(538349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538349")>
<WorkItem(545062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545062")>
<Fact>
Public Sub DuplicateReferences()
Dim mscorlibMetadata = AssemblyMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib)
Dim mscorlib1 = mscorlibMetadata.GetReference(filePath:="lib1.dll")
Dim mscorlib2 = mscorlibMetadata.GetReference(filePath:="lib1.dll")
Dim comp = VisualBasicCompilation.Create("test", references:={mscorlib1, mscorlib2})
Assert.Equal(2, comp.ExternalReferences.Length)
Assert.Null(comp.GetReferencedAssemblySymbol(mscorlib1)) ' ignored
Assert.NotNull(comp.GetReferencedAssemblySymbol(mscorlib2))
Dim mscorlibNoEmbed = mscorlibMetadata.GetReference(filePath:="lib1.dll")
Dim mscorlibEmbed = mscorlibMetadata.GetReference(filePath:="lib1.dll", embedInteropTypes:=True)
comp = VisualBasicCompilation.Create("test", references:={mscorlibNoEmbed, mscorlibEmbed})
Assert.Equal(2, comp.ExternalReferences.Length)
Assert.Null(comp.GetReferencedAssemblySymbol(mscorlibNoEmbed)) ' ignored
Assert.NotNull(comp.GetReferencedAssemblySymbol(mscorlibEmbed))
comp = VisualBasicCompilation.Create("test", references:={mscorlibEmbed, mscorlibNoEmbed})
Assert.Equal(2, comp.ExternalReferences.Length)
Assert.Null(comp.GetReferencedAssemblySymbol(mscorlibEmbed)) ' ignored
Assert.NotNull(comp.GetReferencedAssemblySymbol(mscorlibNoEmbed))
End Sub
<Fact>
Public Sub ReferencesVersioning()
Dim metadata1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1)
Dim metadata2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2)
Dim b = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="b">
<file name="b.vb">
Public Class B
Public Shared Function Main() As Integer
Return C.Main()
End Function
End Class
</file>
</compilation>,
references:={MetadataReference.CreateFromImage(TestResources.General.C2)},
options:=TestOptions.ReleaseDll)
Dim metadata3 = AssemblyMetadata.CreateFromImage(b.EmitToArray())
Dim a = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="a">
<file name="a.vb">
Class A
Public Shared Sub Main()
B.Main()
End Sub
End Class
</file>
</compilation>,
references:={metadata1.GetReference(filePath:="file1.dll"), metadata2.GetReference(filePath:="file2.dll"), metadata3.GetReference(filePath:="file1.dll")},
options:=TestOptions.ReleaseDll)
Using stream = New MemoryStream()
a.Emit(stream)
End Using
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 System.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Roslyn.Test.Utilities
Public Class MetadataFileReferenceCompilationTests
Inherits BasicTestBase
<WorkItem(539480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539480")>
<WorkItem(1037628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems?_a=edit&id=1037628")>
<Fact>
Public Sub BC31011ERR_BadRefLib1()
Dim ref = MetadataReference.CreateFromImage({}, filePath:="Goo.dll")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadRefLib1">
<file name="a.vb">
Class C1
End Class
</file>
</compilation>)
compilation1 = compilation1.AddReferences(ref)
Dim expectedErrors1 = <errors>
BC31519: 'Goo.dll' cannot be referenced because it is not a valid assembly.
</errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(1037628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems?_a=edit&id=1037628")>
<Fact>
Public Sub BC31007ERR_BadModuleFile1()
Dim ref = ModuleMetadata.CreateFromImage({}).GetReference(filePath:="Goo.dll")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadRefLib1">
<file name="a.vb">
Class C1
End Class
</file>
</compilation>)
compilation1 = compilation1.AddReferences(ref)
Dim expectedErrors1 = <errors>
BC31007: Unable to load module file 'Goo.dll': PE image doesn't contain managed metadata.
</errors>
Using New EnsureEnglishUICulture
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Using
End Sub
<WorkItem(538349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538349")>
<WorkItem(545062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545062")>
<Fact>
Public Sub DuplicateReferences()
Dim mscorlibMetadata = AssemblyMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib)
Dim mscorlib1 = mscorlibMetadata.GetReference(filePath:="lib1.dll")
Dim mscorlib2 = mscorlibMetadata.GetReference(filePath:="lib1.dll")
Dim comp = VisualBasicCompilation.Create("test", references:={mscorlib1, mscorlib2})
Assert.Equal(2, comp.ExternalReferences.Length)
Assert.Null(comp.GetReferencedAssemblySymbol(mscorlib1)) ' ignored
Assert.NotNull(comp.GetReferencedAssemblySymbol(mscorlib2))
Dim mscorlibNoEmbed = mscorlibMetadata.GetReference(filePath:="lib1.dll")
Dim mscorlibEmbed = mscorlibMetadata.GetReference(filePath:="lib1.dll", embedInteropTypes:=True)
comp = VisualBasicCompilation.Create("test", references:={mscorlibNoEmbed, mscorlibEmbed})
Assert.Equal(2, comp.ExternalReferences.Length)
Assert.Null(comp.GetReferencedAssemblySymbol(mscorlibNoEmbed)) ' ignored
Assert.NotNull(comp.GetReferencedAssemblySymbol(mscorlibEmbed))
comp = VisualBasicCompilation.Create("test", references:={mscorlibEmbed, mscorlibNoEmbed})
Assert.Equal(2, comp.ExternalReferences.Length)
Assert.Null(comp.GetReferencedAssemblySymbol(mscorlibEmbed)) ' ignored
Assert.NotNull(comp.GetReferencedAssemblySymbol(mscorlibNoEmbed))
End Sub
<Fact>
Public Sub ReferencesVersioning()
Dim metadata1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1)
Dim metadata2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2)
Dim b = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="b">
<file name="b.vb">
Public Class B
Public Shared Function Main() As Integer
Return C.Main()
End Function
End Class
</file>
</compilation>,
references:={MetadataReference.CreateFromImage(TestResources.General.C2)},
options:=TestOptions.ReleaseDll)
Dim metadata3 = AssemblyMetadata.CreateFromImage(b.EmitToArray())
Dim a = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="a">
<file name="a.vb">
Class A
Public Shared Sub Main()
B.Main()
End Sub
End Class
</file>
</compilation>,
references:={metadata1.GetReference(filePath:="file1.dll"), metadata2.GetReference(filePath:="file2.dll"), metadata3.GetReference(filePath:="file1.dll")},
options:=TestOptions.ReleaseDll)
Using stream = New MemoryStream()
a.Emit(stream)
End Using
End Sub
End Class
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/CSharp/Portable/Organizing/Organizers/EventDeclarationOrganizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class EventDeclarationOrganizer : AbstractSyntaxNodeOrganizer<EventDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EventDeclarationOrganizer()
{
}
protected override EventDeclarationSyntax Organize(
EventDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.EventKeyword,
syntax.Type,
syntax.ExplicitInterfaceSpecifier,
syntax.Identifier,
syntax.AccessorList,
syntax.SemicolonToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class EventDeclarationOrganizer : AbstractSyntaxNodeOrganizer<EventDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EventDeclarationOrganizer()
{
}
protected override EventDeclarationSyntax Organize(
EventDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.EventKeyword,
syntax.Type,
syntax.ExplicitInterfaceSpecifier,
syntax.Identifier,
syntax.AccessorList,
syntax.SemicolonToken);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Scripting/CSharpTest/InteractiveSessionReferencesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Scripting.TestCompilationFactory;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.Test
{
public class InteractiveSessionReferencesTests : TestBase
{
/// <summary>
/// Test adding a reference to NetStandard 2.0 library.
/// Validates that we resolve all references correctly in the first and the subsequent submissions.
/// </summary>
[Fact]
[WorkItem(345, "https://github.com/dotnet/try/issues/345")]
public async Task LibraryReference_NetStandard20()
{
var libSource = @"
public class C
{
public readonly int X = 1;
}
";
var libImage = CreateCSharpCompilation(libSource, TargetFrameworkUtil.NetStandard20References, "lib").EmitToArray();
var dir = Temp.CreateDirectory();
var libFile = dir.CreateFile("lib.dll").WriteAllBytes(libImage);
var s0 = CSharpScript.Create($@"
#r ""{libFile.Path}""
int F(C c) => c.X;
");
var s1 = s0.ContinueWith($@"
F(new C())
");
var diagnostics = s1.Compile();
Assert.Empty(diagnostics);
var result = await s1.EvaluateAsync();
Assert.Equal(1, (int)result);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task LibraryReference_MissingDependency_MultipleResolveAttempts(bool swapReferences)
{
var libASource = @"
public class A
{
public readonly int X = D.Y;
}
";
var libBSource = @"
public class B
{
public readonly int X = D.Y;
}
";
var libDSource = @"
public class D
{
public static readonly int Y = 1;
}
";
var dir = Temp.CreateDirectory();
// 1\a.dll
// 2\{b.dll, d.dll}
var dir1 = dir.CreateDirectory("1");
var dir2 = dir.CreateDirectory("2");
var libDImage = CreateCSharpCompilation(libDSource, TargetFrameworkUtil.NetStandard20References, "libD").EmitToArray();
var libDFile = dir2.CreateFile("libD.dll").WriteAllBytes(libDImage);
var libDRef = MetadataReference.CreateFromFile(libDFile.Path);
var libAImage = CreateCSharpCompilation(libASource, TargetFrameworkUtil.NetStandard20References.Concat(libDRef), "libA").EmitToArray();
var libAFile = dir1.CreateFile("libA.dll").WriteAllBytes(libAImage);
var libBImage = CreateCSharpCompilation(libBSource, TargetFrameworkUtil.NetStandard20References.Concat(libDRef), "libB").EmitToArray();
var libBFile = dir2.CreateFile("libB.dll").WriteAllBytes(libBImage);
var r1 = swapReferences ? libBFile.Path : libAFile.Path;
var r2 = swapReferences ? libAFile.Path : libBFile.Path;
var s0 = CSharpScript.Create($@"
#r ""{r1}""
#r ""{r2}""
new A().X + new B().X
");
var diagnostics0 = s0.Compile();
Assert.Empty(diagnostics0);
var result = await s0.EvaluateAsync();
Assert.Equal(2, (int)result);
}
[Fact]
public void LibraryReference_MissingDependency()
{
var libASource = @"
public class C
{
public readonly int X = D.Y;
}
";
var libBSource = @"
public class D
{
public static readonly int Y = 1;
public static readonly int Z = 2;
}
";
var dir = Temp.CreateDirectory();
var libBImage = CreateCSharpCompilation(libBSource, TargetFrameworkUtil.NetStandard20References, "libB").EmitToArray();
// store the reference under a different file name, so that it is not found by the resolver:
var libBFile = dir.CreateFile("libB1.dll").WriteAllBytes(libBImage);
var libBRef = MetadataReference.CreateFromFile(libBFile.Path);
var libAImage = CreateCSharpCompilation(libASource, TargetFrameworkUtil.NetStandard20References.Concat(libBRef), "libA").EmitToArray();
var libAFile = dir.CreateFile("libA.dll").WriteAllBytes(libAImage);
var s0 = CSharpScript.Create($@"
#r ""{libAFile.Path}""
int F(C c) => c.X;
");
var diagnostics0 = s0.Compile();
Assert.Empty(diagnostics0);
File.Move(libBFile.Path, Path.Combine(dir.Path, "libB.dll"));
var s1 = s0.ContinueWith($@"
F(new C())
");
var diagnostics1 = s1.Compile();
Assert.Empty(diagnostics1);
var m = s1.GetCompilation().Assembly.Modules.Single();
Assert.False(m.ReferencedAssemblies.Any(a => a.Name == "libB"));
var missingB = m.ReferencedAssemblySymbols.Single(a => a.Name == "libA").Modules.Single().ReferencedAssemblySymbols.Single(a => a.Name == "libB");
Assert.IsType<MissingAssemblySymbol>(missingB.GetSymbol());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Scripting.TestCompilationFactory;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.Test
{
public class InteractiveSessionReferencesTests : TestBase
{
/// <summary>
/// Test adding a reference to NetStandard 2.0 library.
/// Validates that we resolve all references correctly in the first and the subsequent submissions.
/// </summary>
[Fact]
[WorkItem(345, "https://github.com/dotnet/try/issues/345")]
public async Task LibraryReference_NetStandard20()
{
var libSource = @"
public class C
{
public readonly int X = 1;
}
";
var libImage = CreateCSharpCompilation(libSource, TargetFrameworkUtil.NetStandard20References, "lib").EmitToArray();
var dir = Temp.CreateDirectory();
var libFile = dir.CreateFile("lib.dll").WriteAllBytes(libImage);
var s0 = CSharpScript.Create($@"
#r ""{libFile.Path}""
int F(C c) => c.X;
");
var s1 = s0.ContinueWith($@"
F(new C())
");
var diagnostics = s1.Compile();
Assert.Empty(diagnostics);
var result = await s1.EvaluateAsync();
Assert.Equal(1, (int)result);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task LibraryReference_MissingDependency_MultipleResolveAttempts(bool swapReferences)
{
var libASource = @"
public class A
{
public readonly int X = D.Y;
}
";
var libBSource = @"
public class B
{
public readonly int X = D.Y;
}
";
var libDSource = @"
public class D
{
public static readonly int Y = 1;
}
";
var dir = Temp.CreateDirectory();
// 1\a.dll
// 2\{b.dll, d.dll}
var dir1 = dir.CreateDirectory("1");
var dir2 = dir.CreateDirectory("2");
var libDImage = CreateCSharpCompilation(libDSource, TargetFrameworkUtil.NetStandard20References, "libD").EmitToArray();
var libDFile = dir2.CreateFile("libD.dll").WriteAllBytes(libDImage);
var libDRef = MetadataReference.CreateFromFile(libDFile.Path);
var libAImage = CreateCSharpCompilation(libASource, TargetFrameworkUtil.NetStandard20References.Concat(libDRef), "libA").EmitToArray();
var libAFile = dir1.CreateFile("libA.dll").WriteAllBytes(libAImage);
var libBImage = CreateCSharpCompilation(libBSource, TargetFrameworkUtil.NetStandard20References.Concat(libDRef), "libB").EmitToArray();
var libBFile = dir2.CreateFile("libB.dll").WriteAllBytes(libBImage);
var r1 = swapReferences ? libBFile.Path : libAFile.Path;
var r2 = swapReferences ? libAFile.Path : libBFile.Path;
var s0 = CSharpScript.Create($@"
#r ""{r1}""
#r ""{r2}""
new A().X + new B().X
");
var diagnostics0 = s0.Compile();
Assert.Empty(diagnostics0);
var result = await s0.EvaluateAsync();
Assert.Equal(2, (int)result);
}
[Fact]
public void LibraryReference_MissingDependency()
{
var libASource = @"
public class C
{
public readonly int X = D.Y;
}
";
var libBSource = @"
public class D
{
public static readonly int Y = 1;
public static readonly int Z = 2;
}
";
var dir = Temp.CreateDirectory();
var libBImage = CreateCSharpCompilation(libBSource, TargetFrameworkUtil.NetStandard20References, "libB").EmitToArray();
// store the reference under a different file name, so that it is not found by the resolver:
var libBFile = dir.CreateFile("libB1.dll").WriteAllBytes(libBImage);
var libBRef = MetadataReference.CreateFromFile(libBFile.Path);
var libAImage = CreateCSharpCompilation(libASource, TargetFrameworkUtil.NetStandard20References.Concat(libBRef), "libA").EmitToArray();
var libAFile = dir.CreateFile("libA.dll").WriteAllBytes(libAImage);
var s0 = CSharpScript.Create($@"
#r ""{libAFile.Path}""
int F(C c) => c.X;
");
var diagnostics0 = s0.Compile();
Assert.Empty(diagnostics0);
File.Move(libBFile.Path, Path.Combine(dir.Path, "libB.dll"));
var s1 = s0.ContinueWith($@"
F(new C())
");
var diagnostics1 = s1.Compile();
Assert.Empty(diagnostics1);
var m = s1.GetCompilation().Assembly.Modules.Single();
Assert.False(m.ReferencedAssemblies.Any(a => a.Name == "libB"));
var missingB = m.ReferencedAssemblySymbols.Single(a => a.Name == "libA").Modules.Single().ReferencedAssemblySymbols.Single(a => a.Name == "libB");
Assert.IsType<MissingAssemblySymbol>(missingB.GetSymbol());
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.SymbolSearch.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.SymbolSearch;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
public int AddImport_SuggestForTypesInReferenceAssemblies
{
get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); }
set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); }
}
public int AddImport_SuggestForTypesInNuGetPackages
{
get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); }
set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value); }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.SymbolSearch;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
public int AddImport_SuggestForTypesInReferenceAssemblies
{
get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); }
set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); }
}
public int AddImport_SuggestForTypesInNuGetPackages
{
get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); }
set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value); }
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/Core/Shared/Utilities/ThreadingContextTaskSchedulerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext)
{
CurrentContextScheduler = threadingContext.HasMainThread
? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory)
: TaskScheduler.Default;
}
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext)
{
CurrentContextScheduler = threadingContext.HasMainThread
? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory)
: TaskScheduler.Default;
}
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/VisualBasicSymbolMatcher.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Concurrent
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend NotInheritable Class VisualBasicSymbolMatcher
Inherits SymbolMatcher
Private Shared ReadOnly s_nameComparer As StringComparer = IdentifierComparison.Comparer
Private ReadOnly _defs As MatchDefs
Private ReadOnly _symbols As MatchSymbols
Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue),
sourceAssembly As SourceAssemblySymbol,
sourceContext As EmitContext,
otherAssembly As SourceAssemblySymbol,
otherContext As EmitContext,
otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)))
_defs = New MatchDefsToSource(sourceContext, otherContext)
_symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, New DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object)))
End Sub
Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue),
sourceAssembly As SourceAssemblySymbol,
sourceContext As EmitContext,
otherAssembly As PEAssemblySymbol)
_defs = New MatchDefsToMetadata(sourceContext, otherAssembly)
_symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt:=Nothing, deepTranslatorOpt:=Nothing)
End Sub
Public Overrides Function MapDefinition(definition As Cci.IDefinition) As Cci.IDefinition
Dim symbol As Symbol = TryCast(definition.GetInternalSymbol(), Symbol)
If symbol IsNot Nothing Then
Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.IDefinition)
End If
' TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595)
Return _defs.VisitDef(definition)
End Function
Public Overrides Function MapNamespace([namespace] As Cci.INamespace) As Cci.INamespace
Debug.Assert(TypeOf [namespace].GetInternalSymbol() Is NamespaceSymbol)
Return DirectCast(_symbols.Visit(DirectCast([namespace]?.GetInternalSymbol(), NamespaceSymbol))?.GetCciAdapter(), Cci.INamespace)
End Function
Public Overrides Function MapReference(reference As Cci.ITypeReference) As Cci.ITypeReference
Dim symbol As Symbol = TryCast(reference.GetInternalSymbol(), Symbol)
If symbol IsNot Nothing Then
Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.ITypeReference)
End If
Return Nothing
End Function
Friend Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean
Return _symbols.TryGetAnonymousTypeName(template, name, index)
End Function
Private MustInherit Class MatchDefs
Private ReadOnly _sourceContext As EmitContext
Private ReadOnly _matches As ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition)
Private _lazyTopLevelTypes As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition)
Public Sub New(sourceContext As EmitContext)
Me._sourceContext = sourceContext
Me._matches = New ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition)(ReferenceEqualityComparer.Instance)
End Sub
Public Function VisitDef(def As Cci.IDefinition) As Cci.IDefinition
Return Me._matches.GetOrAdd(def, AddressOf Me.VisitDefInternal)
End Function
Private Function VisitDefInternal(def As Cci.IDefinition) As Cci.IDefinition
Dim type = TryCast(def, Cci.ITypeDefinition)
If type IsNot Nothing Then
Dim namespaceType As Cci.INamespaceTypeDefinition = type.AsNamespaceTypeDefinition(Me._sourceContext)
If namespaceType IsNot Nothing Then
Return Me.VisitNamespaceType(namespaceType)
End If
Dim nestedType As Cci.INestedTypeDefinition = type.AsNestedTypeDefinition(Me._sourceContext)
Debug.Assert(nestedType IsNot Nothing)
Dim otherContainer = DirectCast(Me.VisitDef(nestedType.ContainingTypeDefinition), Cci.ITypeDefinition)
If otherContainer Is Nothing Then
Return Nothing
End If
Return VisitTypeMembers(otherContainer, nestedType, AddressOf GetNestedTypes, Function(a, b) s_nameComparer.Equals(a.Name, b.Name))
End If
Dim member = TryCast(def, Cci.ITypeDefinitionMember)
If member IsNot Nothing Then
Dim otherContainer = DirectCast(Me.VisitDef(member.ContainingTypeDefinition), Cci.ITypeDefinition)
If otherContainer Is Nothing Then
Return Nothing
End If
Dim field = TryCast(def, Cci.IFieldDefinition)
If field IsNot Nothing Then
Return VisitTypeMembers(otherContainer, field, AddressOf GetFields, Function(a, b) s_nameComparer.Equals(a.Name, b.Name))
End If
End If
' We are only expecting types and fields currently.
Throw ExceptionUtilities.UnexpectedValue(def)
End Function
Protected MustOverride Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition)
Protected MustOverride Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition)
Protected MustOverride Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition)
Private Function VisitNamespaceType(def As Cci.INamespaceTypeDefinition) As Cci.INamespaceTypeDefinition
' All generated top-level types are assumed to be in the global namespace.
' However, this may be an embedded NoPIA type within a namespace.
' Since we do not support edits that include references to NoPIA types
' (see #855640), it's reasonable to simply drop such cases.
If Not String.IsNullOrEmpty(def.NamespaceName) Then
Return Nothing
End If
Dim otherDef As Cci.INamespaceTypeDefinition = Nothing
Me.GetTopLevelTypesByName().TryGetValue(def.Name, otherDef)
Return otherDef
End Function
Private Function GetTopLevelTypesByName() As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition)
If Me._lazyTopLevelTypes Is Nothing Then
Dim typesByName As Dictionary(Of String, Cci.INamespaceTypeDefinition) = New Dictionary(Of String, Cci.INamespaceTypeDefinition)(s_nameComparer)
For Each type As Cci.INamespaceTypeDefinition In Me.GetTopLevelTypes()
' All generated top-level types are assumed to be in the global namespace.
If String.IsNullOrEmpty(type.NamespaceName) Then
typesByName.Add(type.Name, type)
End If
Next
Interlocked.CompareExchange(Me._lazyTopLevelTypes, typesByName, Nothing)
End If
Return Me._lazyTopLevelTypes
End Function
Private Shared Function VisitTypeMembers(Of T As {Class, Cci.ITypeDefinitionMember})(
otherContainer As Cci.ITypeDefinition,
member As T,
getMembers As Func(Of Cci.ITypeDefinition, IEnumerable(Of T)),
predicate As Func(Of T, T, Boolean)) As T
' We could cache the members by name (see Matcher.VisitNamedTypeMembers)
' but the assumption is this class is only used for types with few members
' so caching is not necessary and linear search is acceptable.
Return getMembers(otherContainer).FirstOrDefault(Function(otherMember As T) predicate(member, otherMember))
End Function
End Class
Private NotInheritable Class MatchDefsToMetadata
Inherits MatchDefs
Private ReadOnly _otherAssembly As PEAssemblySymbol
Public Sub New(sourceContext As EmitContext, otherAssembly As PEAssemblySymbol)
MyBase.New(sourceContext)
Me._otherAssembly = otherAssembly
End Sub
Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition)
Dim builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition) = ArrayBuilder(Of Cci.INamespaceTypeDefinition).GetInstance()
GetTopLevelTypes(builder, Me._otherAssembly.GlobalNamespace)
Return builder.ToArrayAndFree()
End Function
Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition)
Return (DirectCast(def, PENamedTypeSymbol)).GetTypeMembers().Cast(Of Cci.INestedTypeDefinition)()
End Function
Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition)
Return (DirectCast(def, PENamedTypeSymbol)).GetFieldsToEmit().Cast(Of Cci.IFieldDefinition)()
End Function
Private Overloads Shared Sub GetTopLevelTypes(builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition), [namespace] As NamespaceSymbol)
For Each member In [namespace].GetMembers()
If member.Kind = SymbolKind.Namespace Then
GetTopLevelTypes(builder, DirectCast(member, NamespaceSymbol))
Else
builder.Add(DirectCast(member.GetCciAdapter(), Cci.INamespaceTypeDefinition))
End If
Next
End Sub
End Class
Private NotInheritable Class MatchDefsToSource
Inherits MatchDefs
Private ReadOnly _otherContext As EmitContext
Public Sub New(sourceContext As EmitContext, otherContext As EmitContext)
MyBase.New(sourceContext)
_otherContext = otherContext
End Sub
Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition)
Return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext)
End Function
Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition)
Return def.GetNestedTypes(_otherContext)
End Function
Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition)
Return def.GetFields(_otherContext)
End Function
End Class
Private NotInheritable Class MatchSymbols
Inherits VisualBasicSymbolVisitor(Of Symbol)
Private ReadOnly _anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue)
Private ReadOnly _comparer As SymbolComparer
Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol)
Private ReadOnly _sourceAssembly As SourceAssemblySymbol
Private ReadOnly _otherAssembly As AssemblySymbol
Private ReadOnly _otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal))
' A cache of members per type, populated when the first member for a given
' type Is needed. Within each type, members are indexed by name. The reason
' for caching, And indexing by name, Is to avoid searching sequentially
' through all members of a given kind each time a member Is matched.
Private ReadOnly _otherMembers As ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)))
Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue),
sourceAssembly As SourceAssemblySymbol,
otherAssembly As AssemblySymbol,
otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)),
deepTranslatorOpt As DeepTranslator)
_anonymousTypeMap = anonymousTypeMap
_sourceAssembly = sourceAssembly
_otherAssembly = otherAssembly
_otherSynthesizedMembersOpt = otherSynthesizedMembersOpt
_comparer = New SymbolComparer(Me, deepTranslatorOpt)
_matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance)
_otherMembers = New ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)))(ReferenceEqualityComparer.Instance)
End Sub
Friend Function TryGetAnonymousTypeName(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean
Dim otherType As AnonymousTypeValue = Nothing
If TryFindAnonymousType(type, otherType) Then
name = otherType.Name
index = otherType.UniqueIndex
Return True
End If
name = Nothing
index = -1
Return False
End Function
Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol
' Symbol should have been handled elsewhere.
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function Visit(symbol As Symbol) As Symbol
Debug.Assert(symbol.ContainingAssembly IsNot Me._otherAssembly)
' Add an entry for the match, even if there Is no match, to avoid
' matching the same symbol unsuccessfully multiple times.
Return Me._matches.GetOrAdd(symbol, AddressOf MyBase.Visit)
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol
Dim otherElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol)
If otherElementType Is Nothing Then
' For a newly added type, there is no match in the previous generation, so it could be Nothing.
Return Nothing
End If
Dim otherModifiers = VisitCustomModifiers(symbol.CustomModifiers)
If symbol.IsSZArray Then
Return ArrayTypeSymbol.CreateSZArray(otherElementType, otherModifiers, Me._otherAssembly)
End If
Return ArrayTypeSymbol.CreateMDArray(otherElementType, otherModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, Me._otherAssembly)
End Function
Public Overrides Function VisitEvent(symbol As EventSymbol) As Symbol
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreEventsEqual)
End Function
Public Overrides Function VisitField(symbol As FieldSymbol) As Symbol
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreFieldsEqual)
End Function
Public Overrides Function VisitMethod(symbol As MethodSymbol) As Symbol
' Not expecting constructed method.
Debug.Assert(symbol.IsDefinition)
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreMethodsEqual)
End Function
Public Overrides Function VisitModule([module] As ModuleSymbol) As Symbol
Dim otherAssembly = DirectCast(Visit([module].ContainingAssembly), AssemblySymbol)
If otherAssembly Is Nothing Then
Return Nothing
End If
' manifest module:
If [module].Ordinal = 0 Then
Return otherAssembly.Modules(0)
End If
' match non-manifest module by name:
For i = 1 To otherAssembly.Modules.Length - 1
Dim otherModule = otherAssembly.Modules(i)
' use case sensitive comparison -- modules whose names differ in casing are considered distinct
If StringComparer.Ordinal.Equals(otherModule.Name, [module].Name) Then
Return otherModule
End If
Next
Return Nothing
End Function
Public Overrides Function VisitAssembly(assembly As AssemblySymbol) As Symbol
If assembly.IsLinked Then
Return assembly
End If
' When we map synthesized symbols from previous generations to the latest compilation
' we might encounter a symbol that is defined in arbitrary preceding generation,
' not just the immediately preceding generation. If the source assembly uses time-based
' versioning assemblies of preceding generations might differ in their version number.
If IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly) Then
Return _otherAssembly
End If
' find a referenced assembly with the exactly same source identity:
For Each otherReferencedAssembly In _otherAssembly.Modules(0).ReferencedAssemblySymbols
If IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly) Then
Return otherReferencedAssembly
End If
Next
Return Nothing
End Function
Private Shared Function IdentityEqualIgnoringVersionWildcard(left As AssemblySymbol, right As AssemblySymbol) As Boolean
Dim leftIdentity = left.Identity
Dim rightIdentity = right.Identity
Return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) AndAlso
If(left.AssemblyVersionPattern, leftIdentity.Version).Equals(If(right.AssemblyVersionPattern, rightIdentity.Version)) AndAlso
AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity)
End Function
Public Overrides Function VisitNamespace([namespace] As NamespaceSymbol) As Symbol
Dim otherContainer As Symbol = Visit([namespace].ContainingSymbol)
' Containing namespace will be missing from other assembly
' if its was added in the (newer) source assembly.
If otherContainer Is Nothing Then
Return Nothing
End If
Select Case otherContainer.Kind
Case SymbolKind.NetModule
Return DirectCast(otherContainer, ModuleSymbol).GlobalNamespace
Case SymbolKind.Namespace
Return FindMatchingMember(otherContainer, [namespace], AddressOf AreNamespacesEqual)
Case Else
Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind)
End Select
End Function
Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol
Dim originalDef As NamedTypeSymbol = type.OriginalDefinition
If originalDef IsNot type Then
Dim otherDef As NamedTypeSymbol = DirectCast(Me.Visit(originalDef), NamedTypeSymbol)
' For anonymous delegates the rewriter generates a _ClosureCache$_N field
' of the constructed delegate type. For those cases, the matched result will
' be Nothing if the anonymous delegate is new to this compilation.
If otherDef Is Nothing Then
Return Nothing
End If
Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol) = otherDef.GetAllTypeParameters()
Dim translationFailed As Boolean = False
Dim otherTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v)
Dim newType = DirectCast(v.Visit(t.Type), TypeSymbol)
If newType Is Nothing Then
' For a newly added type, there is no match in the previous generation, so it could be Nothing.
translationFailed = True
newType = t.Type
End If
Return New TypeWithModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers))
End Function, Me)
If translationFailed Then
' There is no match in the previous generation.
Return Nothing
End If
Dim typeMap = TypeSubstitution.Create(otherDef, otherTypeParameters, otherTypeArguments, False)
Return otherDef.Construct(typeMap)
ElseIf type.IsTupleType Then
Dim otherDef = DirectCast(Me.Visit(type.TupleUnderlyingType), NamedTypeSymbol)
If otherDef Is Nothing OrElse Not otherDef.IsTupleOrCompatibleWithTupleOfCardinality(type.TupleElementTypes.Length) Then
Return Nothing
End If
Return otherDef
End If
Debug.Assert(type.IsDefinition)
Dim otherContainer As Symbol = Me.Visit(type.ContainingSymbol)
' Containing type will be missing from other assembly
' if the type was added in the (newer) source assembly.
If otherContainer Is Nothing Then
Return Nothing
End If
Select Case otherContainer.Kind
Case SymbolKind.Namespace
Dim template = TryCast(type, AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol)
If template IsNot Nothing Then
Debug.Assert(otherContainer Is _otherAssembly.GlobalNamespace)
Dim value As AnonymousTypeValue = Nothing
TryFindAnonymousType(template, value)
Return DirectCast(value.Type?.GetInternalSymbol(), NamedTypeSymbol)
End If
If type.IsAnonymousType Then
Return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type))
End If
Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual)
Case SymbolKind.NamedType
Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual)
Case Else
Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind)
End Select
End Function
Public Overrides Function VisitParameter(parameter As ParameterSymbol) As Symbol
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function VisitProperty(symbol As PropertySymbol) As Symbol
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.ArePropertiesEqual)
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol
Dim indexed = TryCast(symbol, IndexedTypeParameterSymbol)
If indexed IsNot Nothing Then
Return indexed
End If
Dim otherContainer As Symbol = Me.Visit(symbol.ContainingSymbol)
Debug.Assert(otherContainer IsNot Nothing)
Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Select Case otherContainer.Kind
Case SymbolKind.NamedType,
SymbolKind.ErrorType
otherTypeParameters = DirectCast(otherContainer, NamedTypeSymbol).TypeParameters
Case SymbolKind.Method
otherTypeParameters = DirectCast(otherContainer, MethodSymbol).TypeParameters
Case Else
Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind)
End Select
Return otherTypeParameters(symbol.Ordinal)
End Function
Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
Return modifiers.SelectAsArray(AddressOf VisitCustomModifier)
End Function
Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier
Dim type = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol)
Debug.Assert(type IsNot Nothing)
Return If(modifier.IsOptional,
VisualBasicCustomModifier.CreateOptional(type),
VisualBasicCustomModifier.CreateRequired(type))
End Function
Friend Function TryFindAnonymousType(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef otherType As AnonymousTypeValue) As Boolean
Debug.Assert(type.ContainingSymbol Is _sourceAssembly.GlobalNamespace)
Return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), otherType)
End Function
Private Function VisitNamedTypeMember(Of T As Symbol)(member As T, predicate As Func(Of T, T, Boolean)) As Symbol
Dim otherType As NamedTypeSymbol = DirectCast(Visit(member.ContainingType), NamedTypeSymbol)
If otherType Is Nothing Then
Return Nothing
End If
Return FindMatchingMember(otherType, member, predicate)
End Function
Private Function FindMatchingMember(Of T As Symbol)(otherTypeOrNamespace As ISymbolInternal, sourceMember As T, predicate As Func(Of T, T, Boolean)) As T
Dim otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, AddressOf GetAllEmittedMembers)
Dim otherMembers As ImmutableArray(Of ISymbolInternal) = Nothing
If otherMembersByName.TryGetValue(sourceMember.Name, otherMembers) Then
For Each otherMember In otherMembers
Dim other = TryCast(otherMember, T)
If other IsNot Nothing AndAlso predicate(sourceMember, other) Then
Return other
End If
Next
End If
Return Nothing
End Function
Private Function AreArrayTypesEqual(type As ArrayTypeSymbol, other As ArrayTypeSymbol) As Boolean
Debug.Assert(type.CustomModifiers.IsEmpty)
Debug.Assert(other.CustomModifiers.IsEmpty)
Return type.HasSameShapeAs(other) AndAlso Me.AreTypesEqual(type.ElementType, other.ElementType)
End Function
Private Function AreEventsEqual([event] As EventSymbol, other As EventSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals([event].Name, other.Name))
Return Me._comparer.Equals([event].Type, other.Type)
End Function
Private Function AreFieldsEqual(field As FieldSymbol, other As FieldSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals(field.Name, other.Name))
Return Me._comparer.Equals(field.Type, other.Type)
End Function
Private Function AreMethodsEqual(method As MethodSymbol, other As MethodSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals(method.Name, other.Name))
Debug.Assert(method.IsDefinition)
Debug.Assert(other.IsDefinition)
method = SubstituteTypeParameters(method)
other = SubstituteTypeParameters(other)
Return Me._comparer.Equals(method.ReturnType, other.ReturnType) AndAlso
method.Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual) AndAlso
method.TypeParameters.SequenceEqual(other.TypeParameters, AddressOf Me.AreTypesEqual)
End Function
Private Shared Function SubstituteTypeParameters(method As MethodSymbol) As MethodSymbol
Debug.Assert(method.IsDefinition)
Dim i As Integer = method.TypeParameters.Length
If i = 0 Then
Return method
End If
Return method.Construct(ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(IndexedTypeParameterSymbol.Take(i)))
End Function
Private Function AreNamedTypesEqual(type As NamedTypeSymbol, other As NamedTypeSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals(type.Name, other.Name))
Debug.Assert(Not type.HasTypeArgumentsCustomModifiers)
Debug.Assert(Not other.HasTypeArgumentsCustomModifiers)
' Tuple types should be unwrapped to their underlying type before getting here (see MatchSymbols.VisitNamedType)
Debug.Assert(Not type.IsTupleType)
Debug.Assert(Not other.IsTupleType)
Return type.TypeArgumentsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsNoUseSiteDiagnostics, AddressOf Me.AreTypesEqual)
End Function
Private Function AreNamespacesEqual([namespace] As NamespaceSymbol, other As NamespaceSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals([namespace].Name, other.Name))
Return True
End Function
Private Function AreParametersEqual(parameter As ParameterSymbol, other As ParameterSymbol) As Boolean
Debug.Assert(parameter.Ordinal = other.Ordinal)
Return parameter.IsByRef = other.IsByRef AndAlso Me._comparer.Equals(parameter.Type, other.Type)
End Function
Private Function ArePropertiesEqual([property] As PropertySymbol, other As PropertySymbol) As Boolean
Debug.Assert(s_nameComparer.Equals([property].Name, other.Name))
Return Me._comparer.Equals([property].Type, other.Type) AndAlso
[property].Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual)
End Function
Private Shared Function AreTypeParametersEqual(type As TypeParameterSymbol, other As TypeParameterSymbol) As Boolean
Debug.Assert(type.Ordinal = other.Ordinal)
Debug.Assert(s_nameComparer.Equals(type.Name, other.Name))
' Comparing constraints is unnecessary: two methods cannot differ by
' constraints alone and changing the signature of a method is a rude
' edit. Furthermore, comparing constraint types might lead to a cycle.
Debug.Assert(type.HasConstructorConstraint = other.HasConstructorConstraint)
Debug.Assert(type.HasValueTypeConstraint = other.HasValueTypeConstraint)
Debug.Assert(type.HasReferenceTypeConstraint = other.HasReferenceTypeConstraint)
Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length = other.ConstraintTypesNoUseSiteDiagnostics.Length)
Return True
End Function
Private Function AreTypesEqual(type As TypeSymbol, other As TypeSymbol) As Boolean
If type.Kind <> other.Kind Then
Return False
End If
Select Case type.Kind
Case SymbolKind.ArrayType
Return AreArrayTypesEqual(DirectCast(type, ArrayTypeSymbol), DirectCast(other, ArrayTypeSymbol))
Case SymbolKind.NamedType,
SymbolKind.ErrorType
Return AreNamedTypesEqual(DirectCast(type, NamedTypeSymbol), DirectCast(other, NamedTypeSymbol))
Case SymbolKind.TypeParameter
Return AreTypeParametersEqual(DirectCast(type, TypeParameterSymbol), DirectCast(other, TypeParameterSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(type.Kind)
End Select
End Function
Private Function GetAllEmittedMembers(symbol As ISymbolInternal) As IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal))
Dim members = ArrayBuilder(Of ISymbolInternal).GetInstance()
If symbol.Kind = SymbolKind.NamedType Then
Dim type = CType(symbol, NamedTypeSymbol)
members.AddRange(type.GetEventsToEmit())
members.AddRange(type.GetFieldsToEmit())
members.AddRange(type.GetMethodsToEmit())
members.AddRange(type.GetTypeMembers())
members.AddRange(type.GetPropertiesToEmit())
Else
members.AddRange(CType(symbol, NamespaceSymbol).GetMembers())
End If
Dim synthesizedMembers As ImmutableArray(Of ISymbolInternal) = Nothing
If _otherSynthesizedMembersOpt IsNot Nothing AndAlso _otherSynthesizedMembersOpt.TryGetValue(symbol, synthesizedMembers) Then
members.AddRange(synthesizedMembers)
End If
Dim result = members.ToDictionary(Function(s) s.Name, s_nameComparer)
members.Free()
Return result
End Function
Private Class SymbolComparer
Private ReadOnly _matcher As MatchSymbols
Private ReadOnly _deepTranslatorOpt As DeepTranslator
Public Sub New(matcher As MatchSymbols, deepTranslatorOpt As DeepTranslator)
Debug.Assert(matcher IsNot Nothing)
_matcher = matcher
_deepTranslatorOpt = deepTranslatorOpt
End Sub
Public Overloads Function Equals(source As TypeSymbol, other As TypeSymbol) As Boolean
Dim visitedSource = DirectCast(_matcher.Visit(source), TypeSymbol)
Dim visitedOther = If(_deepTranslatorOpt IsNot Nothing, DirectCast(_deepTranslatorOpt.Visit(other), TypeSymbol), other)
' If both visitedSource and visitedOther are Nothing, return false meaning that the method was not able to verify the equality.
Return visitedSource IsNot Nothing AndAlso visitedOther IsNot Nothing AndAlso visitedSource.IsSameType(visitedOther, TypeCompareKind.IgnoreTupleNames)
End Function
End Class
End Class
Friend NotInheritable Class DeepTranslator
Inherits VisualBasicSymbolVisitor(Of Symbol)
Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol)
Private ReadOnly _systemObject As NamedTypeSymbol
Public Sub New(systemObject As NamedTypeSymbol)
_matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance)
_systemObject = systemObject
End Sub
Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol
' Symbol should have been handled elsewhere.
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function Visit(symbol As Symbol) As Symbol
Return _matches.GetOrAdd(symbol, AddressOf MyBase.Visit)
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol
Dim translatedElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol)
Dim translatedModifiers = VisitCustomModifiers(symbol.CustomModifiers)
If symbol.IsSZArray Then
Return ArrayTypeSymbol.CreateSZArray(translatedElementType, translatedModifiers, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly)
End If
Return ArrayTypeSymbol.CreateMDArray(translatedElementType, translatedModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly)
End Function
Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol
If type.IsTupleType Then
type = type.TupleUnderlyingType
Debug.Assert(Not type.IsTupleType)
End If
Dim originalDef As NamedTypeSymbol = type.OriginalDefinition
If originalDef IsNot type Then
Dim translatedTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v) New TypeWithModifiers(DirectCast(v.Visit(t.Type), TypeSymbol),
v.VisitCustomModifiers(t.CustomModifiers)), Me)
Dim translatedOriginalDef = DirectCast(Me.Visit(originalDef), NamedTypeSymbol)
Dim typeMap = TypeSubstitution.Create(translatedOriginalDef, translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, False)
Return translatedOriginalDef.Construct(typeMap)
End If
Debug.Assert(type.IsDefinition)
If type.IsAnonymousType Then
Return Me.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type))
End If
Return type
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol
Return symbol
End Function
Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
Return modifiers.SelectAsArray(AddressOf VisitCustomModifier)
End Function
Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier
Dim translatedType = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol)
Debug.Assert(translatedType IsNot Nothing)
Return If(modifier.IsOptional,
VisualBasicCustomModifier.CreateOptional(translatedType),
VisualBasicCustomModifier.CreateRequired(translatedType))
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.Concurrent
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend NotInheritable Class VisualBasicSymbolMatcher
Inherits SymbolMatcher
Private Shared ReadOnly s_nameComparer As StringComparer = IdentifierComparison.Comparer
Private ReadOnly _defs As MatchDefs
Private ReadOnly _symbols As MatchSymbols
Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue),
sourceAssembly As SourceAssemblySymbol,
sourceContext As EmitContext,
otherAssembly As SourceAssemblySymbol,
otherContext As EmitContext,
otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)))
_defs = New MatchDefsToSource(sourceContext, otherContext)
_symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, New DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object)))
End Sub
Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue),
sourceAssembly As SourceAssemblySymbol,
sourceContext As EmitContext,
otherAssembly As PEAssemblySymbol)
_defs = New MatchDefsToMetadata(sourceContext, otherAssembly)
_symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt:=Nothing, deepTranslatorOpt:=Nothing)
End Sub
Public Overrides Function MapDefinition(definition As Cci.IDefinition) As Cci.IDefinition
Dim symbol As Symbol = TryCast(definition.GetInternalSymbol(), Symbol)
If symbol IsNot Nothing Then
Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.IDefinition)
End If
' TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595)
Return _defs.VisitDef(definition)
End Function
Public Overrides Function MapNamespace([namespace] As Cci.INamespace) As Cci.INamespace
Debug.Assert(TypeOf [namespace].GetInternalSymbol() Is NamespaceSymbol)
Return DirectCast(_symbols.Visit(DirectCast([namespace]?.GetInternalSymbol(), NamespaceSymbol))?.GetCciAdapter(), Cci.INamespace)
End Function
Public Overrides Function MapReference(reference As Cci.ITypeReference) As Cci.ITypeReference
Dim symbol As Symbol = TryCast(reference.GetInternalSymbol(), Symbol)
If symbol IsNot Nothing Then
Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.ITypeReference)
End If
Return Nothing
End Function
Friend Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean
Return _symbols.TryGetAnonymousTypeName(template, name, index)
End Function
Private MustInherit Class MatchDefs
Private ReadOnly _sourceContext As EmitContext
Private ReadOnly _matches As ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition)
Private _lazyTopLevelTypes As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition)
Public Sub New(sourceContext As EmitContext)
Me._sourceContext = sourceContext
Me._matches = New ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition)(ReferenceEqualityComparer.Instance)
End Sub
Public Function VisitDef(def As Cci.IDefinition) As Cci.IDefinition
Return Me._matches.GetOrAdd(def, AddressOf Me.VisitDefInternal)
End Function
Private Function VisitDefInternal(def As Cci.IDefinition) As Cci.IDefinition
Dim type = TryCast(def, Cci.ITypeDefinition)
If type IsNot Nothing Then
Dim namespaceType As Cci.INamespaceTypeDefinition = type.AsNamespaceTypeDefinition(Me._sourceContext)
If namespaceType IsNot Nothing Then
Return Me.VisitNamespaceType(namespaceType)
End If
Dim nestedType As Cci.INestedTypeDefinition = type.AsNestedTypeDefinition(Me._sourceContext)
Debug.Assert(nestedType IsNot Nothing)
Dim otherContainer = DirectCast(Me.VisitDef(nestedType.ContainingTypeDefinition), Cci.ITypeDefinition)
If otherContainer Is Nothing Then
Return Nothing
End If
Return VisitTypeMembers(otherContainer, nestedType, AddressOf GetNestedTypes, Function(a, b) s_nameComparer.Equals(a.Name, b.Name))
End If
Dim member = TryCast(def, Cci.ITypeDefinitionMember)
If member IsNot Nothing Then
Dim otherContainer = DirectCast(Me.VisitDef(member.ContainingTypeDefinition), Cci.ITypeDefinition)
If otherContainer Is Nothing Then
Return Nothing
End If
Dim field = TryCast(def, Cci.IFieldDefinition)
If field IsNot Nothing Then
Return VisitTypeMembers(otherContainer, field, AddressOf GetFields, Function(a, b) s_nameComparer.Equals(a.Name, b.Name))
End If
End If
' We are only expecting types and fields currently.
Throw ExceptionUtilities.UnexpectedValue(def)
End Function
Protected MustOverride Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition)
Protected MustOverride Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition)
Protected MustOverride Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition)
Private Function VisitNamespaceType(def As Cci.INamespaceTypeDefinition) As Cci.INamespaceTypeDefinition
' All generated top-level types are assumed to be in the global namespace.
' However, this may be an embedded NoPIA type within a namespace.
' Since we do not support edits that include references to NoPIA types
' (see #855640), it's reasonable to simply drop such cases.
If Not String.IsNullOrEmpty(def.NamespaceName) Then
Return Nothing
End If
Dim otherDef As Cci.INamespaceTypeDefinition = Nothing
Me.GetTopLevelTypesByName().TryGetValue(def.Name, otherDef)
Return otherDef
End Function
Private Function GetTopLevelTypesByName() As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition)
If Me._lazyTopLevelTypes Is Nothing Then
Dim typesByName As Dictionary(Of String, Cci.INamespaceTypeDefinition) = New Dictionary(Of String, Cci.INamespaceTypeDefinition)(s_nameComparer)
For Each type As Cci.INamespaceTypeDefinition In Me.GetTopLevelTypes()
' All generated top-level types are assumed to be in the global namespace.
If String.IsNullOrEmpty(type.NamespaceName) Then
typesByName.Add(type.Name, type)
End If
Next
Interlocked.CompareExchange(Me._lazyTopLevelTypes, typesByName, Nothing)
End If
Return Me._lazyTopLevelTypes
End Function
Private Shared Function VisitTypeMembers(Of T As {Class, Cci.ITypeDefinitionMember})(
otherContainer As Cci.ITypeDefinition,
member As T,
getMembers As Func(Of Cci.ITypeDefinition, IEnumerable(Of T)),
predicate As Func(Of T, T, Boolean)) As T
' We could cache the members by name (see Matcher.VisitNamedTypeMembers)
' but the assumption is this class is only used for types with few members
' so caching is not necessary and linear search is acceptable.
Return getMembers(otherContainer).FirstOrDefault(Function(otherMember As T) predicate(member, otherMember))
End Function
End Class
Private NotInheritable Class MatchDefsToMetadata
Inherits MatchDefs
Private ReadOnly _otherAssembly As PEAssemblySymbol
Public Sub New(sourceContext As EmitContext, otherAssembly As PEAssemblySymbol)
MyBase.New(sourceContext)
Me._otherAssembly = otherAssembly
End Sub
Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition)
Dim builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition) = ArrayBuilder(Of Cci.INamespaceTypeDefinition).GetInstance()
GetTopLevelTypes(builder, Me._otherAssembly.GlobalNamespace)
Return builder.ToArrayAndFree()
End Function
Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition)
Return (DirectCast(def, PENamedTypeSymbol)).GetTypeMembers().Cast(Of Cci.INestedTypeDefinition)()
End Function
Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition)
Return (DirectCast(def, PENamedTypeSymbol)).GetFieldsToEmit().Cast(Of Cci.IFieldDefinition)()
End Function
Private Overloads Shared Sub GetTopLevelTypes(builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition), [namespace] As NamespaceSymbol)
For Each member In [namespace].GetMembers()
If member.Kind = SymbolKind.Namespace Then
GetTopLevelTypes(builder, DirectCast(member, NamespaceSymbol))
Else
builder.Add(DirectCast(member.GetCciAdapter(), Cci.INamespaceTypeDefinition))
End If
Next
End Sub
End Class
Private NotInheritable Class MatchDefsToSource
Inherits MatchDefs
Private ReadOnly _otherContext As EmitContext
Public Sub New(sourceContext As EmitContext, otherContext As EmitContext)
MyBase.New(sourceContext)
_otherContext = otherContext
End Sub
Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition)
Return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext)
End Function
Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition)
Return def.GetNestedTypes(_otherContext)
End Function
Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition)
Return def.GetFields(_otherContext)
End Function
End Class
Private NotInheritable Class MatchSymbols
Inherits VisualBasicSymbolVisitor(Of Symbol)
Private ReadOnly _anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue)
Private ReadOnly _comparer As SymbolComparer
Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol)
Private ReadOnly _sourceAssembly As SourceAssemblySymbol
Private ReadOnly _otherAssembly As AssemblySymbol
Private ReadOnly _otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal))
' A cache of members per type, populated when the first member for a given
' type Is needed. Within each type, members are indexed by name. The reason
' for caching, And indexing by name, Is to avoid searching sequentially
' through all members of a given kind each time a member Is matched.
Private ReadOnly _otherMembers As ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)))
Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue),
sourceAssembly As SourceAssemblySymbol,
otherAssembly As AssemblySymbol,
otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)),
deepTranslatorOpt As DeepTranslator)
_anonymousTypeMap = anonymousTypeMap
_sourceAssembly = sourceAssembly
_otherAssembly = otherAssembly
_otherSynthesizedMembersOpt = otherSynthesizedMembersOpt
_comparer = New SymbolComparer(Me, deepTranslatorOpt)
_matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance)
_otherMembers = New ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)))(ReferenceEqualityComparer.Instance)
End Sub
Friend Function TryGetAnonymousTypeName(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean
Dim otherType As AnonymousTypeValue = Nothing
If TryFindAnonymousType(type, otherType) Then
name = otherType.Name
index = otherType.UniqueIndex
Return True
End If
name = Nothing
index = -1
Return False
End Function
Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol
' Symbol should have been handled elsewhere.
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function Visit(symbol As Symbol) As Symbol
Debug.Assert(symbol.ContainingAssembly IsNot Me._otherAssembly)
' Add an entry for the match, even if there Is no match, to avoid
' matching the same symbol unsuccessfully multiple times.
Return Me._matches.GetOrAdd(symbol, AddressOf MyBase.Visit)
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol
Dim otherElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol)
If otherElementType Is Nothing Then
' For a newly added type, there is no match in the previous generation, so it could be Nothing.
Return Nothing
End If
Dim otherModifiers = VisitCustomModifiers(symbol.CustomModifiers)
If symbol.IsSZArray Then
Return ArrayTypeSymbol.CreateSZArray(otherElementType, otherModifiers, Me._otherAssembly)
End If
Return ArrayTypeSymbol.CreateMDArray(otherElementType, otherModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, Me._otherAssembly)
End Function
Public Overrides Function VisitEvent(symbol As EventSymbol) As Symbol
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreEventsEqual)
End Function
Public Overrides Function VisitField(symbol As FieldSymbol) As Symbol
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreFieldsEqual)
End Function
Public Overrides Function VisitMethod(symbol As MethodSymbol) As Symbol
' Not expecting constructed method.
Debug.Assert(symbol.IsDefinition)
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreMethodsEqual)
End Function
Public Overrides Function VisitModule([module] As ModuleSymbol) As Symbol
Dim otherAssembly = DirectCast(Visit([module].ContainingAssembly), AssemblySymbol)
If otherAssembly Is Nothing Then
Return Nothing
End If
' manifest module:
If [module].Ordinal = 0 Then
Return otherAssembly.Modules(0)
End If
' match non-manifest module by name:
For i = 1 To otherAssembly.Modules.Length - 1
Dim otherModule = otherAssembly.Modules(i)
' use case sensitive comparison -- modules whose names differ in casing are considered distinct
If StringComparer.Ordinal.Equals(otherModule.Name, [module].Name) Then
Return otherModule
End If
Next
Return Nothing
End Function
Public Overrides Function VisitAssembly(assembly As AssemblySymbol) As Symbol
If assembly.IsLinked Then
Return assembly
End If
' When we map synthesized symbols from previous generations to the latest compilation
' we might encounter a symbol that is defined in arbitrary preceding generation,
' not just the immediately preceding generation. If the source assembly uses time-based
' versioning assemblies of preceding generations might differ in their version number.
If IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly) Then
Return _otherAssembly
End If
' find a referenced assembly with the exactly same source identity:
For Each otherReferencedAssembly In _otherAssembly.Modules(0).ReferencedAssemblySymbols
If IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly) Then
Return otherReferencedAssembly
End If
Next
Return Nothing
End Function
Private Shared Function IdentityEqualIgnoringVersionWildcard(left As AssemblySymbol, right As AssemblySymbol) As Boolean
Dim leftIdentity = left.Identity
Dim rightIdentity = right.Identity
Return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) AndAlso
If(left.AssemblyVersionPattern, leftIdentity.Version).Equals(If(right.AssemblyVersionPattern, rightIdentity.Version)) AndAlso
AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity)
End Function
Public Overrides Function VisitNamespace([namespace] As NamespaceSymbol) As Symbol
Dim otherContainer As Symbol = Visit([namespace].ContainingSymbol)
' Containing namespace will be missing from other assembly
' if its was added in the (newer) source assembly.
If otherContainer Is Nothing Then
Return Nothing
End If
Select Case otherContainer.Kind
Case SymbolKind.NetModule
Return DirectCast(otherContainer, ModuleSymbol).GlobalNamespace
Case SymbolKind.Namespace
Return FindMatchingMember(otherContainer, [namespace], AddressOf AreNamespacesEqual)
Case Else
Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind)
End Select
End Function
Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol
Dim originalDef As NamedTypeSymbol = type.OriginalDefinition
If originalDef IsNot type Then
Dim otherDef As NamedTypeSymbol = DirectCast(Me.Visit(originalDef), NamedTypeSymbol)
' For anonymous delegates the rewriter generates a _ClosureCache$_N field
' of the constructed delegate type. For those cases, the matched result will
' be Nothing if the anonymous delegate is new to this compilation.
If otherDef Is Nothing Then
Return Nothing
End If
Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol) = otherDef.GetAllTypeParameters()
Dim translationFailed As Boolean = False
Dim otherTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v)
Dim newType = DirectCast(v.Visit(t.Type), TypeSymbol)
If newType Is Nothing Then
' For a newly added type, there is no match in the previous generation, so it could be Nothing.
translationFailed = True
newType = t.Type
End If
Return New TypeWithModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers))
End Function, Me)
If translationFailed Then
' There is no match in the previous generation.
Return Nothing
End If
Dim typeMap = TypeSubstitution.Create(otherDef, otherTypeParameters, otherTypeArguments, False)
Return otherDef.Construct(typeMap)
ElseIf type.IsTupleType Then
Dim otherDef = DirectCast(Me.Visit(type.TupleUnderlyingType), NamedTypeSymbol)
If otherDef Is Nothing OrElse Not otherDef.IsTupleOrCompatibleWithTupleOfCardinality(type.TupleElementTypes.Length) Then
Return Nothing
End If
Return otherDef
End If
Debug.Assert(type.IsDefinition)
Dim otherContainer As Symbol = Me.Visit(type.ContainingSymbol)
' Containing type will be missing from other assembly
' if the type was added in the (newer) source assembly.
If otherContainer Is Nothing Then
Return Nothing
End If
Select Case otherContainer.Kind
Case SymbolKind.Namespace
Dim template = TryCast(type, AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol)
If template IsNot Nothing Then
Debug.Assert(otherContainer Is _otherAssembly.GlobalNamespace)
Dim value As AnonymousTypeValue = Nothing
TryFindAnonymousType(template, value)
Return DirectCast(value.Type?.GetInternalSymbol(), NamedTypeSymbol)
End If
If type.IsAnonymousType Then
Return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type))
End If
Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual)
Case SymbolKind.NamedType
Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual)
Case Else
Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind)
End Select
End Function
Public Overrides Function VisitParameter(parameter As ParameterSymbol) As Symbol
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function VisitProperty(symbol As PropertySymbol) As Symbol
Return Me.VisitNamedTypeMember(symbol, AddressOf Me.ArePropertiesEqual)
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol
Dim indexed = TryCast(symbol, IndexedTypeParameterSymbol)
If indexed IsNot Nothing Then
Return indexed
End If
Dim otherContainer As Symbol = Me.Visit(symbol.ContainingSymbol)
Debug.Assert(otherContainer IsNot Nothing)
Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol)
Select Case otherContainer.Kind
Case SymbolKind.NamedType,
SymbolKind.ErrorType
otherTypeParameters = DirectCast(otherContainer, NamedTypeSymbol).TypeParameters
Case SymbolKind.Method
otherTypeParameters = DirectCast(otherContainer, MethodSymbol).TypeParameters
Case Else
Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind)
End Select
Return otherTypeParameters(symbol.Ordinal)
End Function
Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
Return modifiers.SelectAsArray(AddressOf VisitCustomModifier)
End Function
Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier
Dim type = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol)
Debug.Assert(type IsNot Nothing)
Return If(modifier.IsOptional,
VisualBasicCustomModifier.CreateOptional(type),
VisualBasicCustomModifier.CreateRequired(type))
End Function
Friend Function TryFindAnonymousType(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef otherType As AnonymousTypeValue) As Boolean
Debug.Assert(type.ContainingSymbol Is _sourceAssembly.GlobalNamespace)
Return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), otherType)
End Function
Private Function VisitNamedTypeMember(Of T As Symbol)(member As T, predicate As Func(Of T, T, Boolean)) As Symbol
Dim otherType As NamedTypeSymbol = DirectCast(Visit(member.ContainingType), NamedTypeSymbol)
If otherType Is Nothing Then
Return Nothing
End If
Return FindMatchingMember(otherType, member, predicate)
End Function
Private Function FindMatchingMember(Of T As Symbol)(otherTypeOrNamespace As ISymbolInternal, sourceMember As T, predicate As Func(Of T, T, Boolean)) As T
Dim otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, AddressOf GetAllEmittedMembers)
Dim otherMembers As ImmutableArray(Of ISymbolInternal) = Nothing
If otherMembersByName.TryGetValue(sourceMember.Name, otherMembers) Then
For Each otherMember In otherMembers
Dim other = TryCast(otherMember, T)
If other IsNot Nothing AndAlso predicate(sourceMember, other) Then
Return other
End If
Next
End If
Return Nothing
End Function
Private Function AreArrayTypesEqual(type As ArrayTypeSymbol, other As ArrayTypeSymbol) As Boolean
Debug.Assert(type.CustomModifiers.IsEmpty)
Debug.Assert(other.CustomModifiers.IsEmpty)
Return type.HasSameShapeAs(other) AndAlso Me.AreTypesEqual(type.ElementType, other.ElementType)
End Function
Private Function AreEventsEqual([event] As EventSymbol, other As EventSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals([event].Name, other.Name))
Return Me._comparer.Equals([event].Type, other.Type)
End Function
Private Function AreFieldsEqual(field As FieldSymbol, other As FieldSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals(field.Name, other.Name))
Return Me._comparer.Equals(field.Type, other.Type)
End Function
Private Function AreMethodsEqual(method As MethodSymbol, other As MethodSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals(method.Name, other.Name))
Debug.Assert(method.IsDefinition)
Debug.Assert(other.IsDefinition)
method = SubstituteTypeParameters(method)
other = SubstituteTypeParameters(other)
Return Me._comparer.Equals(method.ReturnType, other.ReturnType) AndAlso
method.Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual) AndAlso
method.TypeParameters.SequenceEqual(other.TypeParameters, AddressOf Me.AreTypesEqual)
End Function
Private Shared Function SubstituteTypeParameters(method As MethodSymbol) As MethodSymbol
Debug.Assert(method.IsDefinition)
Dim i As Integer = method.TypeParameters.Length
If i = 0 Then
Return method
End If
Return method.Construct(ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(IndexedTypeParameterSymbol.Take(i)))
End Function
Private Function AreNamedTypesEqual(type As NamedTypeSymbol, other As NamedTypeSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals(type.Name, other.Name))
Debug.Assert(Not type.HasTypeArgumentsCustomModifiers)
Debug.Assert(Not other.HasTypeArgumentsCustomModifiers)
' Tuple types should be unwrapped to their underlying type before getting here (see MatchSymbols.VisitNamedType)
Debug.Assert(Not type.IsTupleType)
Debug.Assert(Not other.IsTupleType)
Return type.TypeArgumentsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsNoUseSiteDiagnostics, AddressOf Me.AreTypesEqual)
End Function
Private Function AreNamespacesEqual([namespace] As NamespaceSymbol, other As NamespaceSymbol) As Boolean
Debug.Assert(s_nameComparer.Equals([namespace].Name, other.Name))
Return True
End Function
Private Function AreParametersEqual(parameter As ParameterSymbol, other As ParameterSymbol) As Boolean
Debug.Assert(parameter.Ordinal = other.Ordinal)
Return parameter.IsByRef = other.IsByRef AndAlso Me._comparer.Equals(parameter.Type, other.Type)
End Function
Private Function ArePropertiesEqual([property] As PropertySymbol, other As PropertySymbol) As Boolean
Debug.Assert(s_nameComparer.Equals([property].Name, other.Name))
Return Me._comparer.Equals([property].Type, other.Type) AndAlso
[property].Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual)
End Function
Private Shared Function AreTypeParametersEqual(type As TypeParameterSymbol, other As TypeParameterSymbol) As Boolean
Debug.Assert(type.Ordinal = other.Ordinal)
Debug.Assert(s_nameComparer.Equals(type.Name, other.Name))
' Comparing constraints is unnecessary: two methods cannot differ by
' constraints alone and changing the signature of a method is a rude
' edit. Furthermore, comparing constraint types might lead to a cycle.
Debug.Assert(type.HasConstructorConstraint = other.HasConstructorConstraint)
Debug.Assert(type.HasValueTypeConstraint = other.HasValueTypeConstraint)
Debug.Assert(type.HasReferenceTypeConstraint = other.HasReferenceTypeConstraint)
Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length = other.ConstraintTypesNoUseSiteDiagnostics.Length)
Return True
End Function
Private Function AreTypesEqual(type As TypeSymbol, other As TypeSymbol) As Boolean
If type.Kind <> other.Kind Then
Return False
End If
Select Case type.Kind
Case SymbolKind.ArrayType
Return AreArrayTypesEqual(DirectCast(type, ArrayTypeSymbol), DirectCast(other, ArrayTypeSymbol))
Case SymbolKind.NamedType,
SymbolKind.ErrorType
Return AreNamedTypesEqual(DirectCast(type, NamedTypeSymbol), DirectCast(other, NamedTypeSymbol))
Case SymbolKind.TypeParameter
Return AreTypeParametersEqual(DirectCast(type, TypeParameterSymbol), DirectCast(other, TypeParameterSymbol))
Case Else
Throw ExceptionUtilities.UnexpectedValue(type.Kind)
End Select
End Function
Private Function GetAllEmittedMembers(symbol As ISymbolInternal) As IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal))
Dim members = ArrayBuilder(Of ISymbolInternal).GetInstance()
If symbol.Kind = SymbolKind.NamedType Then
Dim type = CType(symbol, NamedTypeSymbol)
members.AddRange(type.GetEventsToEmit())
members.AddRange(type.GetFieldsToEmit())
members.AddRange(type.GetMethodsToEmit())
members.AddRange(type.GetTypeMembers())
members.AddRange(type.GetPropertiesToEmit())
Else
members.AddRange(CType(symbol, NamespaceSymbol).GetMembers())
End If
Dim synthesizedMembers As ImmutableArray(Of ISymbolInternal) = Nothing
If _otherSynthesizedMembersOpt IsNot Nothing AndAlso _otherSynthesizedMembersOpt.TryGetValue(symbol, synthesizedMembers) Then
members.AddRange(synthesizedMembers)
End If
Dim result = members.ToDictionary(Function(s) s.Name, s_nameComparer)
members.Free()
Return result
End Function
Private Class SymbolComparer
Private ReadOnly _matcher As MatchSymbols
Private ReadOnly _deepTranslatorOpt As DeepTranslator
Public Sub New(matcher As MatchSymbols, deepTranslatorOpt As DeepTranslator)
Debug.Assert(matcher IsNot Nothing)
_matcher = matcher
_deepTranslatorOpt = deepTranslatorOpt
End Sub
Public Overloads Function Equals(source As TypeSymbol, other As TypeSymbol) As Boolean
Dim visitedSource = DirectCast(_matcher.Visit(source), TypeSymbol)
Dim visitedOther = If(_deepTranslatorOpt IsNot Nothing, DirectCast(_deepTranslatorOpt.Visit(other), TypeSymbol), other)
' If both visitedSource and visitedOther are Nothing, return false meaning that the method was not able to verify the equality.
Return visitedSource IsNot Nothing AndAlso visitedOther IsNot Nothing AndAlso visitedSource.IsSameType(visitedOther, TypeCompareKind.IgnoreTupleNames)
End Function
End Class
End Class
Friend NotInheritable Class DeepTranslator
Inherits VisualBasicSymbolVisitor(Of Symbol)
Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol)
Private ReadOnly _systemObject As NamedTypeSymbol
Public Sub New(systemObject As NamedTypeSymbol)
_matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance)
_systemObject = systemObject
End Sub
Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol
' Symbol should have been handled elsewhere.
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function Visit(symbol As Symbol) As Symbol
Return _matches.GetOrAdd(symbol, AddressOf MyBase.Visit)
End Function
Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol
Dim translatedElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol)
Dim translatedModifiers = VisitCustomModifiers(symbol.CustomModifiers)
If symbol.IsSZArray Then
Return ArrayTypeSymbol.CreateSZArray(translatedElementType, translatedModifiers, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly)
End If
Return ArrayTypeSymbol.CreateMDArray(translatedElementType, translatedModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly)
End Function
Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol
If type.IsTupleType Then
type = type.TupleUnderlyingType
Debug.Assert(Not type.IsTupleType)
End If
Dim originalDef As NamedTypeSymbol = type.OriginalDefinition
If originalDef IsNot type Then
Dim translatedTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v) New TypeWithModifiers(DirectCast(v.Visit(t.Type), TypeSymbol),
v.VisitCustomModifiers(t.CustomModifiers)), Me)
Dim translatedOriginalDef = DirectCast(Me.Visit(originalDef), NamedTypeSymbol)
Dim typeMap = TypeSubstitution.Create(translatedOriginalDef, translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, False)
Return translatedOriginalDef.Construct(typeMap)
End If
Debug.Assert(type.IsDefinition)
If type.IsAnonymousType Then
Return Me.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type))
End If
Return type
End Function
Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol
Return symbol
End Function
Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
Return modifiers.SelectAsArray(AddressOf VisitCustomModifier)
End Function
Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier
Dim translatedType = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol)
Debug.Assert(translatedType IsNot Nothing)
Return If(modifier.IsOptional,
VisualBasicCustomModifier.CreateOptional(translatedType),
VisualBasicCustomModifier.CreateRequired(translatedType))
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/Core/Options/SignatureHelpOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Editor.Options
{
internal static class SignatureHelpOptions
{
public static readonly PerLanguageOption2<bool> ShowSignatureHelp = new(nameof(SignatureHelpOptions), nameof(ShowSignatureHelp), defaultValue: true);
}
[ExportOptionProvider, Shared]
internal class SignatureHelpOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SignatureHelpOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
SignatureHelpOptions.ShowSignatureHelp);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Editor.Options
{
internal static class SignatureHelpOptions
{
public static readonly PerLanguageOption2<bool> ShowSignatureHelp = new(nameof(SignatureHelpOptions), nameof(ShowSignatureHelp), defaultValue: true);
}
[ExportOptionProvider, Shared]
internal class SignatureHelpOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SignatureHelpOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
SignatureHelpOptions.ShowSignatureHelp);
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_Helpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
private static bool IsAccessible(ISymbol symbol)
{
if (symbol.Locations.Any(l => l.IsInMetadata))
{
var accessibility = symbol.DeclaredAccessibility;
return accessibility == Accessibility.Public ||
accessibility == Accessibility.Protected ||
accessibility == Accessibility.ProtectedOrInternal;
}
return true;
}
internal static async Task<bool> OriginalSymbolsMatchAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol? symbolToMatch,
CancellationToken cancellationToken)
{
if (ReferenceEquals(searchSymbol, symbolToMatch))
return true;
if (searchSymbol == null || symbolToMatch == null)
return false;
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch))
return true;
if (await OriginalSymbolsMatchCoreAsync(solution, searchSymbol, symbolToMatch, cancellationToken).ConfigureAwait(false))
return true;
if (searchSymbol.Kind == SymbolKind.Namespace && symbolToMatch.Kind == SymbolKind.Namespace)
{
// if one of them is a merged namespace symbol and other one is its constituent namespace symbol, they are equivalent.
var namespace1 = (INamespaceSymbol)searchSymbol;
var namespace2 = (INamespaceSymbol)symbolToMatch;
var namespace1Count = namespace1.ConstituentNamespaces.Length;
var namespace2Count = namespace2.ConstituentNamespaces.Length;
if (namespace1Count != namespace2Count)
{
if ((namespace1Count > 1 && await namespace1.ConstituentNamespaces.AnyAsync(static (n, arg) => NamespaceSymbolsMatchAsync(arg.solution, n, arg.namespace2, arg.cancellationToken), (solution, namespace2, cancellationToken)).ConfigureAwait(false)) ||
(namespace2Count > 1 && await namespace2.ConstituentNamespaces.AnyAsync(static (n2, arg) => NamespaceSymbolsMatchAsync(arg.solution, arg.namespace1, n2, arg.cancellationToken), (solution, namespace1, cancellationToken)).ConfigureAwait(false)))
{
return true;
}
}
}
return false;
}
private static async Task<bool> OriginalSymbolsMatchCoreAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol symbolToMatch,
CancellationToken cancellationToken)
{
if (searchSymbol == null || symbolToMatch == null)
return false;
searchSymbol = searchSymbol.GetOriginalUnreducedDefinition();
symbolToMatch = symbolToMatch.GetOriginalUnreducedDefinition();
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch, SymbolEqualityComparer.Default))
return true;
// We compare the given searchSymbol and symbolToMatch for equivalence using SymbolEquivalenceComparer
// as follows:
// 1) We compare the given symbols using the SymbolEquivalenceComparer.IgnoreAssembliesInstance,
// which ignores the containing assemblies for named types equivalence checks. This is required
// to handle equivalent named types which are forwarded to completely different assemblies.
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
// 3) Otherwise, if the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent
// if containing assemblies are NOT ignored. We need to perform additional checks to ensure they
// are indeed equivalent:
//
// (a) If IgnoreAssembliesInstance.Equals equivalence visitor encountered any pair of non-nested
// named types which were equivalent in all aspects, except that they resided in different
// assemblies, we need to ensure that all such pairs are indeed equivalent types. Such a pair
// of named types is equivalent if and only if one of them is a type defined in either
// searchSymbolCompilation(C1) or symbolToMatchCompilation(C2), say defined in reference assembly
// A (version v1) in compilation C1, and the other type is a forwarded type, such that it is
// forwarded from reference assembly A (version v2) to assembly B in compilation C2.
// (b) Otherwise, if no such named type pairs were encountered, symbols ARE equivalent.
using var _ = PooledDictionary<INamedTypeSymbol, INamedTypeSymbol>.GetInstance(out var equivalentTypesWithDifferingAssemblies);
// 1) Compare searchSymbol and symbolToMatch using SymbolEquivalenceComparer.IgnoreAssembliesInstance
if (!SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(searchSymbol, symbolToMatch, equivalentTypesWithDifferingAssemblies))
{
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
return false;
}
// 3) If the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent if containing assemblies are NOT ignored.
if (equivalentTypesWithDifferingAssemblies.Count > 0)
{
// Step 3a) Ensure that all pairs of named types in equivalentTypesWithDifferingAssemblies are indeed equivalent types.
return await VerifyForwardedTypesAsync(solution, equivalentTypesWithDifferingAssemblies, cancellationToken).ConfigureAwait(false);
}
// 3b) If no such named type pairs were encountered, symbols ARE equivalent.
return true;
}
private static Task<bool> NamespaceSymbolsMatchAsync(
Solution solution,
INamespaceSymbol namespace1,
INamespaceSymbol namespace2,
CancellationToken cancellationToken)
{
return OriginalSymbolsMatchAsync(solution, namespace1, namespace2, cancellationToken);
}
/// <summary>
/// Verifies that all pairs of named types in equivalentTypesWithDifferingAssemblies are equivalent forwarded types.
/// </summary>
private static async Task<bool> VerifyForwardedTypesAsync(
Solution solution,
Dictionary<INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies);
Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any());
// Must contain equivalents named types residing in different assemblies.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly)));
// Must contain non-nested named types.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null));
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null));
// Cache compilations so we avoid recreating any as we walk the pairs of types.
using var _ = PooledHashSet<Compilation>.GetInstance(out var compilationSet);
foreach (var (type1, type2) in equivalentTypesWithDifferingAssemblies)
{
// Check if type1 was forwarded to type2 in type2's compilation, or if type2 was forwarded to type1 in
// type1's compilation. We check both direction as this API is called from higher level comparison APIs
// that are unordered.
if (!await VerifyForwardedTypeAsync(solution, candidate: type1, forwardedTo: type2, compilationSet, cancellationToken).ConfigureAwait(false) &&
!await VerifyForwardedTypeAsync(solution, candidate: type2, forwardedTo: type1, compilationSet, cancellationToken).ConfigureAwait(false))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns <see langword="true"/> if <paramref name="candidate"/> was forwarded to <paramref name="forwardedTo"/> in
/// <paramref name="forwardedTo"/>'s <see cref="Compilation"/>.
/// </summary>
private static async Task<bool> VerifyForwardedTypeAsync(
Solution solution,
INamedTypeSymbol candidate,
INamedTypeSymbol forwardedTo,
HashSet<Compilation> compilationSet,
CancellationToken cancellationToken)
{
// Only need to operate on original definitions. i.e. List<T> is the type that is forwarded,
// not List<string>.
candidate = GetOridinalUnderlyingType(candidate);
forwardedTo = GetOridinalUnderlyingType(forwardedTo);
var forwardedToOriginatingProject = solution.GetOriginatingProject(forwardedTo);
if (forwardedToOriginatingProject == null)
return false;
var forwardedToCompilation = await forwardedToOriginatingProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
if (forwardedToCompilation == null)
return false;
// Cache the compilation so that if we need it while checking another set of forwarded types, we don't
// expensively throw it away and recreate it.
compilationSet.Add(forwardedToCompilation);
var candidateFullMetadataName = candidate.ContainingNamespace?.IsGlobalNamespace != false
? candidate.MetadataName
: $"{candidate.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat)}.{candidate.MetadataName}";
// Now, find the corresponding reference to type1's assembly in type2's compilation and see if that assembly
// contains a forward that matches type2. If so, type1 was forwarded to type2.
var candidateAssemblyName = candidate.ContainingAssembly.Name;
foreach (var assembly in forwardedToCompilation.GetReferencedAssemblySymbols())
{
if (assembly.Name == candidateAssemblyName)
{
var resolvedType = assembly.ResolveForwardedType(candidateFullMetadataName);
if (Equals(resolvedType, forwardedTo))
return true;
}
}
return false;
}
private static INamedTypeSymbol GetOridinalUnderlyingType(INamedTypeSymbol type)
=> (type.NativeIntegerUnderlyingType ?? type).OriginalDefinition;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
private static bool IsAccessible(ISymbol symbol)
{
if (symbol.Locations.Any(l => l.IsInMetadata))
{
var accessibility = symbol.DeclaredAccessibility;
return accessibility == Accessibility.Public ||
accessibility == Accessibility.Protected ||
accessibility == Accessibility.ProtectedOrInternal;
}
return true;
}
internal static async Task<bool> OriginalSymbolsMatchAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol? symbolToMatch,
CancellationToken cancellationToken)
{
if (ReferenceEquals(searchSymbol, symbolToMatch))
return true;
if (searchSymbol == null || symbolToMatch == null)
return false;
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch))
return true;
if (await OriginalSymbolsMatchCoreAsync(solution, searchSymbol, symbolToMatch, cancellationToken).ConfigureAwait(false))
return true;
if (searchSymbol.Kind == SymbolKind.Namespace && symbolToMatch.Kind == SymbolKind.Namespace)
{
// if one of them is a merged namespace symbol and other one is its constituent namespace symbol, they are equivalent.
var namespace1 = (INamespaceSymbol)searchSymbol;
var namespace2 = (INamespaceSymbol)symbolToMatch;
var namespace1Count = namespace1.ConstituentNamespaces.Length;
var namespace2Count = namespace2.ConstituentNamespaces.Length;
if (namespace1Count != namespace2Count)
{
if ((namespace1Count > 1 && await namespace1.ConstituentNamespaces.AnyAsync(static (n, arg) => NamespaceSymbolsMatchAsync(arg.solution, n, arg.namespace2, arg.cancellationToken), (solution, namespace2, cancellationToken)).ConfigureAwait(false)) ||
(namespace2Count > 1 && await namespace2.ConstituentNamespaces.AnyAsync(static (n2, arg) => NamespaceSymbolsMatchAsync(arg.solution, arg.namespace1, n2, arg.cancellationToken), (solution, namespace1, cancellationToken)).ConfigureAwait(false)))
{
return true;
}
}
}
return false;
}
private static async Task<bool> OriginalSymbolsMatchCoreAsync(
Solution solution,
ISymbol searchSymbol,
ISymbol symbolToMatch,
CancellationToken cancellationToken)
{
if (searchSymbol == null || symbolToMatch == null)
return false;
searchSymbol = searchSymbol.GetOriginalUnreducedDefinition();
symbolToMatch = symbolToMatch.GetOriginalUnreducedDefinition();
// Avoid the expensive checks if we can fast path when the compiler just says these are equal. Also, for the
// purposes of symbol finding nullability of symbols doesn't affect things, so just use the default
// comparison.
if (searchSymbol.Equals(symbolToMatch, SymbolEqualityComparer.Default))
return true;
// We compare the given searchSymbol and symbolToMatch for equivalence using SymbolEquivalenceComparer
// as follows:
// 1) We compare the given symbols using the SymbolEquivalenceComparer.IgnoreAssembliesInstance,
// which ignores the containing assemblies for named types equivalence checks. This is required
// to handle equivalent named types which are forwarded to completely different assemblies.
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
// 3) Otherwise, if the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent
// if containing assemblies are NOT ignored. We need to perform additional checks to ensure they
// are indeed equivalent:
//
// (a) If IgnoreAssembliesInstance.Equals equivalence visitor encountered any pair of non-nested
// named types which were equivalent in all aspects, except that they resided in different
// assemblies, we need to ensure that all such pairs are indeed equivalent types. Such a pair
// of named types is equivalent if and only if one of them is a type defined in either
// searchSymbolCompilation(C1) or symbolToMatchCompilation(C2), say defined in reference assembly
// A (version v1) in compilation C1, and the other type is a forwarded type, such that it is
// forwarded from reference assembly A (version v2) to assembly B in compilation C2.
// (b) Otherwise, if no such named type pairs were encountered, symbols ARE equivalent.
using var _ = PooledDictionary<INamedTypeSymbol, INamedTypeSymbol>.GetInstance(out var equivalentTypesWithDifferingAssemblies);
// 1) Compare searchSymbol and symbolToMatch using SymbolEquivalenceComparer.IgnoreAssembliesInstance
if (!SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(searchSymbol, symbolToMatch, equivalentTypesWithDifferingAssemblies))
{
// 2) If the symbols are NOT equivalent ignoring assemblies, then they cannot be equivalent.
return false;
}
// 3) If the symbols ARE equivalent ignoring assemblies, they may or may not be equivalent if containing assemblies are NOT ignored.
if (equivalentTypesWithDifferingAssemblies.Count > 0)
{
// Step 3a) Ensure that all pairs of named types in equivalentTypesWithDifferingAssemblies are indeed equivalent types.
return await VerifyForwardedTypesAsync(solution, equivalentTypesWithDifferingAssemblies, cancellationToken).ConfigureAwait(false);
}
// 3b) If no such named type pairs were encountered, symbols ARE equivalent.
return true;
}
private static Task<bool> NamespaceSymbolsMatchAsync(
Solution solution,
INamespaceSymbol namespace1,
INamespaceSymbol namespace2,
CancellationToken cancellationToken)
{
return OriginalSymbolsMatchAsync(solution, namespace1, namespace2, cancellationToken);
}
/// <summary>
/// Verifies that all pairs of named types in equivalentTypesWithDifferingAssemblies are equivalent forwarded types.
/// </summary>
private static async Task<bool> VerifyForwardedTypesAsync(
Solution solution,
Dictionary<INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies);
Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any());
// Must contain equivalents named types residing in different assemblies.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly)));
// Must contain non-nested named types.
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null));
Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null));
// Cache compilations so we avoid recreating any as we walk the pairs of types.
using var _ = PooledHashSet<Compilation>.GetInstance(out var compilationSet);
foreach (var (type1, type2) in equivalentTypesWithDifferingAssemblies)
{
// Check if type1 was forwarded to type2 in type2's compilation, or if type2 was forwarded to type1 in
// type1's compilation. We check both direction as this API is called from higher level comparison APIs
// that are unordered.
if (!await VerifyForwardedTypeAsync(solution, candidate: type1, forwardedTo: type2, compilationSet, cancellationToken).ConfigureAwait(false) &&
!await VerifyForwardedTypeAsync(solution, candidate: type2, forwardedTo: type1, compilationSet, cancellationToken).ConfigureAwait(false))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns <see langword="true"/> if <paramref name="candidate"/> was forwarded to <paramref name="forwardedTo"/> in
/// <paramref name="forwardedTo"/>'s <see cref="Compilation"/>.
/// </summary>
private static async Task<bool> VerifyForwardedTypeAsync(
Solution solution,
INamedTypeSymbol candidate,
INamedTypeSymbol forwardedTo,
HashSet<Compilation> compilationSet,
CancellationToken cancellationToken)
{
// Only need to operate on original definitions. i.e. List<T> is the type that is forwarded,
// not List<string>.
candidate = GetOridinalUnderlyingType(candidate);
forwardedTo = GetOridinalUnderlyingType(forwardedTo);
var forwardedToOriginatingProject = solution.GetOriginatingProject(forwardedTo);
if (forwardedToOriginatingProject == null)
return false;
var forwardedToCompilation = await forwardedToOriginatingProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
if (forwardedToCompilation == null)
return false;
// Cache the compilation so that if we need it while checking another set of forwarded types, we don't
// expensively throw it away and recreate it.
compilationSet.Add(forwardedToCompilation);
var candidateFullMetadataName = candidate.ContainingNamespace?.IsGlobalNamespace != false
? candidate.MetadataName
: $"{candidate.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat)}.{candidate.MetadataName}";
// Now, find the corresponding reference to type1's assembly in type2's compilation and see if that assembly
// contains a forward that matches type2. If so, type1 was forwarded to type2.
var candidateAssemblyName = candidate.ContainingAssembly.Name;
foreach (var assembly in forwardedToCompilation.GetReferencedAssemblySymbols())
{
if (assembly.Name == candidateAssemblyName)
{
var resolvedType = assembly.ResolveForwardedType(candidateFullMetadataName);
if (Equals(resolvedType, forwardedTo))
return true;
}
}
return false;
}
private static INamedTypeSymbol GetOridinalUnderlyingType(INamedTypeSymbol type)
=> (type.NativeIntegerUnderlyingType ?? type).OriginalDefinition;
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/Core/Portable/Completion/CommonCompletionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Options;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.Tags;
namespace Microsoft.CodeAnalysis.Completion
{
internal abstract partial class CommonCompletionService : CompletionServiceWithProviders
{
protected CommonCompletionService(Workspace workspace)
: base(workspace)
{
}
protected override CompletionItem GetBetterItem(CompletionItem item, CompletionItem existingItem)
{
// We've constructed the export order of completion providers so
// that snippets are exported after everything else. That way,
// when we choose a single item per display text, snippet
// glyphs appear by snippets. This breaks preselection of items
// whose display text is also a snippet (workitem 852578),
// the snippet item doesn't have its preselect bit set.
// We'll special case this by not preferring later items
// if they are snippets and the other candidate is preselected.
if (existingItem.Rules.MatchPriority != MatchPriority.Default && IsSnippetItem(item))
{
return existingItem;
}
return base.GetBetterItem(item, existingItem);
}
internal override Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync(
Document document,
int caretPosition,
CompletionTrigger trigger,
ImmutableHashSet<string> roles,
OptionSet options,
CancellationToken cancellationToken)
{
return GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken);
}
protected static bool IsKeywordItem(CompletionItem item)
=> item.Tags.Contains(WellKnownTags.Keyword);
protected static bool IsSnippetItem(CompletionItem item)
=> item.Tags.Contains(WellKnownTags.Snippet);
internal override ImmutableArray<CompletionItem> FilterItems(Document document, ImmutableArray<(CompletionItem, PatternMatch?)> itemsWithPatternMatch, string filterText)
{
var helper = CompletionHelper.GetHelper(document);
return CompletionService.FilterItems(helper, itemsWithPatternMatch, filterText);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Options;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.Tags;
namespace Microsoft.CodeAnalysis.Completion
{
internal abstract partial class CommonCompletionService : CompletionServiceWithProviders
{
protected CommonCompletionService(Workspace workspace)
: base(workspace)
{
}
protected override CompletionItem GetBetterItem(CompletionItem item, CompletionItem existingItem)
{
// We've constructed the export order of completion providers so
// that snippets are exported after everything else. That way,
// when we choose a single item per display text, snippet
// glyphs appear by snippets. This breaks preselection of items
// whose display text is also a snippet (workitem 852578),
// the snippet item doesn't have its preselect bit set.
// We'll special case this by not preferring later items
// if they are snippets and the other candidate is preselected.
if (existingItem.Rules.MatchPriority != MatchPriority.Default && IsSnippetItem(item))
{
return existingItem;
}
return base.GetBetterItem(item, existingItem);
}
internal override Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync(
Document document,
int caretPosition,
CompletionTrigger trigger,
ImmutableHashSet<string> roles,
OptionSet options,
CancellationToken cancellationToken)
{
return GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken);
}
protected static bool IsKeywordItem(CompletionItem item)
=> item.Tags.Contains(WellKnownTags.Keyword);
protected static bool IsSnippetItem(CompletionItem item)
=> item.Tags.Contains(WellKnownTags.Snippet);
internal override ImmutableArray<CompletionItem> FilterItems(Document document, ImmutableArray<(CompletionItem, PatternMatch?)> itemsWithPatternMatch, string filterText)
{
var helper = CompletionHelper.GetHelper(document);
return CompletionService.FilterItems(helper, itemsWithPatternMatch, filterText);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/InheritanceMarginHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin
{
internal static class InheritanceMarginHelpers
{
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_I_Up_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.ImplementedInterface)
.Add(InheritanceRelationship.InheritedInterface)
.Add(InheritanceRelationship.ImplementedMember);
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_I_Down_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.ImplementingType)
.Add(InheritanceRelationship.ImplementingMember);
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_O_Up_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.BaseType)
.Add(InheritanceRelationship.OverriddenMember);
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_O_Down_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.DerivedType)
.Add(InheritanceRelationship.OverridingMember);
/// <summary>
/// Decide which moniker should be shown.
/// </summary>
public static ImageMoniker GetMoniker(InheritanceRelationship inheritanceRelationship)
{
// If there are multiple targets and we have the corresponding compound image, use it
if (s_relationships_Shown_As_I_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag))
&& s_relationships_Shown_As_O_Down_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.ImplementingOverridden;
}
if (s_relationships_Shown_As_I_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag))
&& s_relationships_Shown_As_O_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.ImplementingOverriding;
}
// Otherwise, show the image based on this preference
if (s_relationships_Shown_As_I_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Implementing;
}
if (s_relationships_Shown_As_I_Down_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Implemented;
}
if (s_relationships_Shown_As_O_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Overriding;
}
if (s_relationships_Shown_As_O_Down_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Overridden;
}
// The relationship is None. Don't know what image should be shown, throws
throw ExceptionUtilities.UnexpectedValue(inheritanceRelationship);
}
public static ImmutableArray<InheritanceMenuItemViewModel> CreateMenuItemViewModelsForSingleMember(ImmutableArray<InheritanceTargetItem> targets)
=> targets.OrderBy(target => target.DisplayName)
.GroupBy(target => target.RelationToMember)
.SelectMany(grouping => CreateMenuItemsWithHeader(grouping.Key, grouping))
.ToImmutableArray();
/// <summary>
/// Create the view models for the inheritance targets of multiple members
/// e.g.
/// MemberViewModel1 -> HeaderViewModel
/// Target1ViewModel
/// HeaderViewModel
/// Target2ViewModel
/// MemberViewModel2 -> HeaderViewModel
/// Target4ViewModel
/// HeaderViewModel
/// Target5ViewModel
/// </summary>
public static ImmutableArray<InheritanceMenuItemViewModel> CreateMenuItemViewModelsForMultipleMembers(ImmutableArray<InheritanceMarginItem> members)
{
Contract.ThrowIfTrue(members.Length <= 1);
// For multiple members, check if all the targets have the same inheritance relationship.
// If so, then don't add the header, because it is already indicated by the margin.
// Otherwise, add the Header.
return members.SelectAsArray(MemberMenuItemViewModel.CreateWithHeaderInTargets).CastArray<InheritanceMenuItemViewModel>();
}
public static ImmutableArray<InheritanceMenuItemViewModel> CreateMenuItemsWithHeader(
InheritanceRelationship relationship,
IEnumerable<InheritanceTargetItem> targets)
{
using var _ = CodeAnalysis.PooledObjects.ArrayBuilder<InheritanceMenuItemViewModel>.GetInstance(out var builder);
var displayContent = relationship switch
{
InheritanceRelationship.ImplementedInterface => ServicesVSResources.Implemented_interfaces,
InheritanceRelationship.BaseType => ServicesVSResources.Base_Types,
InheritanceRelationship.DerivedType => ServicesVSResources.Derived_types,
InheritanceRelationship.InheritedInterface => ServicesVSResources.Inherited_interfaces,
InheritanceRelationship.ImplementingType => ServicesVSResources.Implementing_types,
InheritanceRelationship.ImplementedMember => ServicesVSResources.Implemented_members,
InheritanceRelationship.OverriddenMember => ServicesVSResources.Overridden_members,
InheritanceRelationship.OverridingMember => ServicesVSResources.Overriding_members,
InheritanceRelationship.ImplementingMember => ServicesVSResources.Implementing_members,
_ => throw ExceptionUtilities.UnexpectedValue(relationship)
};
var headerViewModel = new HeaderMenuItemViewModel(displayContent, GetMoniker(relationship), displayContent);
builder.Add(headerViewModel);
foreach (var targetItem in targets)
{
builder.Add(TargetMenuItemViewModel.Create(targetItem));
}
return builder.ToImmutable();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin
{
internal static class InheritanceMarginHelpers
{
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_I_Up_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.ImplementedInterface)
.Add(InheritanceRelationship.InheritedInterface)
.Add(InheritanceRelationship.ImplementedMember);
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_I_Down_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.ImplementingType)
.Add(InheritanceRelationship.ImplementingMember);
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_O_Up_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.BaseType)
.Add(InheritanceRelationship.OverriddenMember);
private static readonly ImmutableArray<InheritanceRelationship> s_relationships_Shown_As_O_Down_Arrow
= ImmutableArray<InheritanceRelationship>.Empty
.Add(InheritanceRelationship.DerivedType)
.Add(InheritanceRelationship.OverridingMember);
/// <summary>
/// Decide which moniker should be shown.
/// </summary>
public static ImageMoniker GetMoniker(InheritanceRelationship inheritanceRelationship)
{
// If there are multiple targets and we have the corresponding compound image, use it
if (s_relationships_Shown_As_I_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag))
&& s_relationships_Shown_As_O_Down_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.ImplementingOverridden;
}
if (s_relationships_Shown_As_I_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag))
&& s_relationships_Shown_As_O_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.ImplementingOverriding;
}
// Otherwise, show the image based on this preference
if (s_relationships_Shown_As_I_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Implementing;
}
if (s_relationships_Shown_As_I_Down_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Implemented;
}
if (s_relationships_Shown_As_O_Up_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Overriding;
}
if (s_relationships_Shown_As_O_Down_Arrow.Any(flag => inheritanceRelationship.HasFlag(flag)))
{
return KnownMonikers.Overridden;
}
// The relationship is None. Don't know what image should be shown, throws
throw ExceptionUtilities.UnexpectedValue(inheritanceRelationship);
}
public static ImmutableArray<InheritanceMenuItemViewModel> CreateMenuItemViewModelsForSingleMember(ImmutableArray<InheritanceTargetItem> targets)
=> targets.OrderBy(target => target.DisplayName)
.GroupBy(target => target.RelationToMember)
.SelectMany(grouping => CreateMenuItemsWithHeader(grouping.Key, grouping))
.ToImmutableArray();
/// <summary>
/// Create the view models for the inheritance targets of multiple members
/// e.g.
/// MemberViewModel1 -> HeaderViewModel
/// Target1ViewModel
/// HeaderViewModel
/// Target2ViewModel
/// MemberViewModel2 -> HeaderViewModel
/// Target4ViewModel
/// HeaderViewModel
/// Target5ViewModel
/// </summary>
public static ImmutableArray<InheritanceMenuItemViewModel> CreateMenuItemViewModelsForMultipleMembers(ImmutableArray<InheritanceMarginItem> members)
{
Contract.ThrowIfTrue(members.Length <= 1);
// For multiple members, check if all the targets have the same inheritance relationship.
// If so, then don't add the header, because it is already indicated by the margin.
// Otherwise, add the Header.
return members.SelectAsArray(MemberMenuItemViewModel.CreateWithHeaderInTargets).CastArray<InheritanceMenuItemViewModel>();
}
public static ImmutableArray<InheritanceMenuItemViewModel> CreateMenuItemsWithHeader(
InheritanceRelationship relationship,
IEnumerable<InheritanceTargetItem> targets)
{
using var _ = CodeAnalysis.PooledObjects.ArrayBuilder<InheritanceMenuItemViewModel>.GetInstance(out var builder);
var displayContent = relationship switch
{
InheritanceRelationship.ImplementedInterface => ServicesVSResources.Implemented_interfaces,
InheritanceRelationship.BaseType => ServicesVSResources.Base_Types,
InheritanceRelationship.DerivedType => ServicesVSResources.Derived_types,
InheritanceRelationship.InheritedInterface => ServicesVSResources.Inherited_interfaces,
InheritanceRelationship.ImplementingType => ServicesVSResources.Implementing_types,
InheritanceRelationship.ImplementedMember => ServicesVSResources.Implemented_members,
InheritanceRelationship.OverriddenMember => ServicesVSResources.Overridden_members,
InheritanceRelationship.OverridingMember => ServicesVSResources.Overriding_members,
InheritanceRelationship.ImplementingMember => ServicesVSResources.Implementing_members,
_ => throw ExceptionUtilities.UnexpectedValue(relationship)
};
var headerViewModel = new HeaderMenuItemViewModel(displayContent, GetMoniker(relationship), displayContent);
builder.Add(headerViewModel);
foreach (var targetItem in targets)
{
builder.Add(TargetMenuItemViewModel.Create(targetItem));
}
return builder.ToImmutable();
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.TypeParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class AnonymousTypeManager
{
/// <summary>
/// Represents an anonymous type template's type parameter.
/// </summary>
internal sealed class AnonymousTypeParameterSymbol : TypeParameterSymbol
{
private readonly Symbol _container;
private readonly int _ordinal;
private readonly string _name;
public AnonymousTypeParameterSymbol(Symbol container, int ordinal, string name)
{
Debug.Assert((object)container != null);
Debug.Assert(!string.IsNullOrEmpty(name));
_container = container;
_ordinal = ordinal;
_name = name;
}
public override TypeParameterKind TypeParameterKind
{
get
{
return TypeParameterKind.Type;
}
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override int Ordinal
{
get { return _ordinal; }
}
public override string Name
{
get { return _name; }
}
public override bool HasConstructorConstraint
{
get { return false; }
}
public override bool HasReferenceTypeConstraint
{
get { return false; }
}
public override bool IsReferenceTypeFromConstraintTypes
{
get { return false; }
}
internal override bool? ReferenceTypeConstraintIsNullable
{
get { return false; }
}
public override bool HasNotNullConstraint => false;
internal override bool? IsNotNullable => null;
public override bool HasValueTypeConstraint
{
get { return false; }
}
public override bool IsValueTypeFromConstraintTypes
{
get { return false; }
}
public override bool HasUnmanagedTypeConstraint
{
get { return false; }
}
public override bool IsImplicitlyDeclared
{
get { return true; }
}
public override VarianceKind Variance
{
get { return VarianceKind.None; }
}
internal override void EnsureAllConstraintsAreResolved()
{
}
internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress)
{
return ImmutableArray<TypeWithAnnotations>.Empty;
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress)
{
return null;
}
internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress)
{
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.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class AnonymousTypeManager
{
/// <summary>
/// Represents an anonymous type template's type parameter.
/// </summary>
internal sealed class AnonymousTypeParameterSymbol : TypeParameterSymbol
{
private readonly Symbol _container;
private readonly int _ordinal;
private readonly string _name;
public AnonymousTypeParameterSymbol(Symbol container, int ordinal, string name)
{
Debug.Assert((object)container != null);
Debug.Assert(!string.IsNullOrEmpty(name));
_container = container;
_ordinal = ordinal;
_name = name;
}
public override TypeParameterKind TypeParameterKind
{
get
{
return TypeParameterKind.Type;
}
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override int Ordinal
{
get { return _ordinal; }
}
public override string Name
{
get { return _name; }
}
public override bool HasConstructorConstraint
{
get { return false; }
}
public override bool HasReferenceTypeConstraint
{
get { return false; }
}
public override bool IsReferenceTypeFromConstraintTypes
{
get { return false; }
}
internal override bool? ReferenceTypeConstraintIsNullable
{
get { return false; }
}
public override bool HasNotNullConstraint => false;
internal override bool? IsNotNullable => null;
public override bool HasValueTypeConstraint
{
get { return false; }
}
public override bool IsValueTypeFromConstraintTypes
{
get { return false; }
}
public override bool HasUnmanagedTypeConstraint
{
get { return false; }
}
public override bool IsImplicitlyDeclared
{
get { return true; }
}
public override VarianceKind Variance
{
get { return VarianceKind.None; }
}
internal override void EnsureAllConstraintsAreResolved()
{
}
internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress)
{
return ImmutableArray<TypeWithAnnotations>.Empty;
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress)
{
return null;
}
internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress)
{
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasicTest/InvertConditional/InvertIfTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.InvertConditional
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InvertConditional
Partial Public Class InvertConditionalTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicInvertConditionalCodeRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function InvertConditional1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = [||]if(x, a, b)
end sub
end class",
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = if(Not x, b, a)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function InvertConditional2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = [||]if(not x, a, b)
end sub
end class",
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = if(x, b, a)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function TestTrivia() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = [||]if(x,
a,
b)
end sub
end class",
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = if(Not x,
b,
a)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function MissingOnBinaryIf() As Task
Await TestMissingAsync(
"class C
sub M(x as integer?, a as integer)
dim c = [||]if(x, a)
end sub
end class")
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.InvertConditional
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InvertConditional
Partial Public Class InvertConditionalTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicInvertConditionalCodeRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function InvertConditional1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = [||]if(x, a, b)
end sub
end class",
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = if(Not x, b, a)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function InvertConditional2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = [||]if(not x, a, b)
end sub
end class",
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = if(x, b, a)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function TestTrivia() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = [||]if(x,
a,
b)
end sub
end class",
"class C
sub M(x as boolean, a as integer, b as integer)
dim c = if(Not x,
b,
a)
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)>
Public Async Function MissingOnBinaryIf() As Task
Await TestMissingAsync(
"class C
sub M(x as integer?, a as integer)
dim c = [||]if(x, a)
end sub
end class")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./docs/features/StaticAbstractMembersInInterfaces.md | Static Abstract Members In Interfaces
=====================================
An interface is allowed to specify abstract static members that implementing classes and structs are then
required to provide an explicit or implicit implementation of. The members can be accessed off of type
parameters that are constrained by the interface.
Proposal:
- https://github.com/dotnet/csharplang/issues/4436
- https://github.com/dotnet/csharplang/blob/main/proposals/static-abstracts-in-interfaces.md
Feature branch: https://github.com/dotnet/roslyn/tree/features/StaticAbstractMembersInInterfaces
Test plan: https://github.com/dotnet/roslyn/issues/52221 | Static Abstract Members In Interfaces
=====================================
An interface is allowed to specify abstract static members that implementing classes and structs are then
required to provide an explicit or implicit implementation of. The members can be accessed off of type
parameters that are constrained by the interface.
Proposal:
- https://github.com/dotnet/csharplang/issues/4436
- https://github.com/dotnet/csharplang/blob/main/proposals/static-abstracts-in-interfaces.md
Feature branch: https://github.com/dotnet/roslyn/tree/features/StaticAbstractMembersInInterfaces
Test plan: https://github.com/dotnet/roslyn/issues/52221 | -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ISyntaxFormattingService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Diagnostics;
#if !CODE_STYLE
using Microsoft.CodeAnalysis.Host;
#endif
namespace Microsoft.CodeAnalysis.Formatting
{
internal interface ISyntaxFormattingService
#if !CODE_STYLE
: ILanguageService
#endif
{
IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules();
IFormattingResult Format(SyntaxNode node, IEnumerable<TextSpan> spans, bool shouldUseFormattingSpanCollapse, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, 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.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Diagnostics;
#if !CODE_STYLE
using Microsoft.CodeAnalysis.Host;
#endif
namespace Microsoft.CodeAnalysis.Formatting
{
internal interface ISyntaxFormattingService
#if !CODE_STYLE
: ILanguageService
#endif
{
IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules();
IFormattingResult Format(SyntaxNode node, IEnumerable<TextSpan> spans, bool shouldUseFormattingSpanCollapse, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> rules, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/Core/Implementation/SolutionPreviewItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.CodeAnalysis.Editor
{
internal class SolutionPreviewItem
{
public readonly ProjectId ProjectId;
public readonly DocumentId? DocumentId;
public readonly Func<CancellationToken, Task<object?>> LazyPreview;
public readonly string? Text;
/// <summary>
/// Construct an instance of <see cref="SolutionPreviewItem"/>
/// </summary>
/// <param name="projectId"><see cref="ProjectId"/> for the <see cref="Project"/> that contains the content being visualized in the supplied <paramref name="lazyPreview"/></param>
/// <param name="documentId"><see cref="DocumentId"/> for the <see cref="Document"/> being visualized in the supplied <paramref name="lazyPreview"/></param>
/// <param name="lazyPreview">Lazily instantiated preview content.</param>
/// <remarks>Use lazy instantiation to ensure that any <see cref="ITextView"/> that may be present inside a given preview are only instantiated at the point
/// when the VS lightbulb requests that preview. Otherwise, we could end up instantiating a bunch of <see cref="ITextView"/>s most of which will never get
/// passed to the VS lightbulb. Such zombie <see cref="ITextView"/>s will never get closed and we will end up leaking memory.</remarks>
public SolutionPreviewItem(ProjectId projectId, DocumentId? documentId, Func<CancellationToken, Task<object?>> lazyPreview)
{
ProjectId = projectId;
DocumentId = documentId;
LazyPreview = lazyPreview;
}
public SolutionPreviewItem(ProjectId projectId, DocumentId? documentId, string text)
: this(projectId, documentId, c => Task.FromResult<object?>(text))
{
Text = text;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.CodeAnalysis.Editor
{
internal class SolutionPreviewItem
{
public readonly ProjectId ProjectId;
public readonly DocumentId? DocumentId;
public readonly Func<CancellationToken, Task<object?>> LazyPreview;
public readonly string? Text;
/// <summary>
/// Construct an instance of <see cref="SolutionPreviewItem"/>
/// </summary>
/// <param name="projectId"><see cref="ProjectId"/> for the <see cref="Project"/> that contains the content being visualized in the supplied <paramref name="lazyPreview"/></param>
/// <param name="documentId"><see cref="DocumentId"/> for the <see cref="Document"/> being visualized in the supplied <paramref name="lazyPreview"/></param>
/// <param name="lazyPreview">Lazily instantiated preview content.</param>
/// <remarks>Use lazy instantiation to ensure that any <see cref="ITextView"/> that may be present inside a given preview are only instantiated at the point
/// when the VS lightbulb requests that preview. Otherwise, we could end up instantiating a bunch of <see cref="ITextView"/>s most of which will never get
/// passed to the VS lightbulb. Such zombie <see cref="ITextView"/>s will never get closed and we will end up leaking memory.</remarks>
public SolutionPreviewItem(ProjectId projectId, DocumentId? documentId, Func<CancellationToken, Task<object?>> lazyPreview)
{
ProjectId = projectId;
DocumentId = documentId;
LazyPreview = lazyPreview;
}
public SolutionPreviewItem(ProjectId projectId, DocumentId? documentId, string text)
: this(projectId, documentId, c => Task.FromResult<object?>(text))
{
Text = text;
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/Test/EditAndContinue/EditAndContinueTestAnalyzerConfigOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal class EditAndContinueTestAnalyzerConfigOptions : AnalyzerConfigOptions
{
private readonly Dictionary<string, string> _options;
public EditAndContinueTestAnalyzerConfigOptions(IEnumerable<(string key, string value)> options)
=> _options = options.ToDictionary(e => e.key, e => e.value);
public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
=> _options.TryGetValue(key, out value);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal class EditAndContinueTestAnalyzerConfigOptions : AnalyzerConfigOptions
{
private readonly Dictionary<string, string> _options;
public EditAndContinueTestAnalyzerConfigOptions(IEnumerable<(string key, string value)> options)
=> _options = options.ToDictionary(e => e.key, e => e.value);
public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
=> _options.TryGetValue(key, out value);
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/CSharp/Portable/CodeFixes/GenerateEnumMember/GenerateEnumMemberCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateEnumMember
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateEnumMember), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateConstructor)]
internal class GenerateEnumMemberCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
private const string CS0117 = nameof(CS0117); // error CS0117: 'Color' does not contain a definition for 'Red'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateEnumMemberCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CS0117); }
}
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IGenerateEnumMemberService>();
return service.GenerateEnumMemberAsync(document, node, cancellationToken);
}
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
=> node is IdentifierNameSyntax;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateEnumMember
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateEnumMember), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateConstructor)]
internal class GenerateEnumMemberCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
private const string CS0117 = nameof(CS0117); // error CS0117: 'Color' does not contain a definition for 'Red'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateEnumMemberCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CS0117); }
}
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IGenerateEnumMemberService>();
return service.GenerateEnumMemberAsync(document, node, cancellationToken);
}
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
=> node is IdentifierNameSyntax;
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/Core/Portable/Workspace/Solution/ProjectDiagnostic.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
public class ProjectDiagnostic : WorkspaceDiagnostic
{
public ProjectId ProjectId { get; }
public ProjectDiagnostic(WorkspaceDiagnosticKind kind, string message, ProjectId projectId)
: base(kind, message)
{
this.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.
#nullable disable
namespace Microsoft.CodeAnalysis
{
public class ProjectDiagnostic : WorkspaceDiagnostic
{
public ProjectId ProjectId { get; }
public ProjectDiagnostic(WorkspaceDiagnosticKind kind, string message, ProjectId projectId)
: base(kind, message)
{
this.ProjectId = projectId;
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/xlf/VBResources.ru.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="ru" original="../VBResources.resx">
<body>
<trans-unit id="ERR_AssignmentInitOnly">
<source>Init-only property '{0}' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor.</source>
<target state="translated">Свойство "{0}", доступное только для инициализации, можно назначать только c помощью инициализатора элемента объекта или для "Me", "MyClass" или "MyBase" в конструкторе экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSwitchValue">
<source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source>
<target state="translated">Ошибка в синтаксисе командной строки: "{0}" не является допустимым значением для параметра "{1}". Значение должно иметь форму "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CommentsAfterLineContinuationNotAvailable1">
<source>Please use language version {0} or greater to use comments after line continuation character.</source>
<target state="translated">Используйте версию языка {0} или более позднюю, чтобы использовать комментарии после символа продолжения строки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">Не удается внедрить тип "{0}", так как он имеет неабстрактный член. Попробуйте задать для свойства "Внедрить типы взаимодействия" значение false.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir">
<source>Multiple analyzer config files cannot be in the same directory ('{0}').</source>
<target state="translated">В одном каталоге ("{0}") не может находиться несколько файлов конфигурации анализатора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingInitOnlyProperty">
<source>'{0}' cannot override init-only '{1}'.</source>
<target state="translated">"{0}" не может переопределить свойство "{1}", предназначенное только для инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementInitOnly">
<source>Init-only '{0}' cannot be implemented.</source>
<target state="translated">Невозможно реализовать свойство "{0}", предназначенное только для инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReAbstractionInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">Невозможно внедрить тип "{0}", так как он переопределяет абстракцию элемента базового интерфейса. Попробуйте задать для свойства "Внедрить типы взаимодействия" значение false (ложь).</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation">
<source>Target runtime doesn't support default interface implementation.</source>
<target state="translated">Целевая среда выполнения не поддерживает реализацию интерфейса по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember">
<source>Target runtime doesn't support 'Protected', 'Protected Friend', or 'Private Protected' accessibility for a member of an interface.</source>
<target state="translated">Целевая среда выполнения не поддерживает доступ "Protected", "Protected Friend" или "Private Protected" для элемента интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsHandlerInTheSameType">
<source>Events of shared WithEvents variables cannot be handled by methods in a different type.</source>
<target state="translated">События общих переменных WithEvents не могут обрабатывать методы другого типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnmanagedCallersOnlyNotSupported">
<source>'UnmanagedCallersOnly' attribute is not supported.</source>
<target state="translated">Атрибут "UnmanagedCallersOnly" не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CallerArgumentExpression">
<source>caller argument expression</source>
<target state="new">caller argument expression</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CommentsAfterLineContinuation">
<source>comments after line continuation</source>
<target state="translated">комментарии после продолжения строки</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InitOnlySettersUsage">
<source>assigning to or passing 'ByRef' properties with init-only setters</source>
<target state="translated">назначение свойств "ByRef" или их передача с помощью методов задания, предназначенных только для инициализации</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_UnconstrainedTypeParameterInConditional">
<source>unconstrained type parameters in binary conditional expressions</source>
<target state="translated">параметры неограниченного типа в двоичных условных выражениях</target>
<note />
</trans-unit>
<trans-unit id="IDS_VBCHelp">
<source> Visual Basic Compiler Options
- OUTPUT FILE -
-out:<file> Specifies the output file name.
-target:exe Create a console application (default).
(Short form: -t)
-target:winexe Create a Windows application.
-target:library Create a library assembly.
-target:module Create a module that can be added to an
assembly.
-target:appcontainerexe Create a Windows application that runs in
AppContainer.
-target:winmdobj Create a Windows Metadata intermediate file
-doc[+|-] Generates XML documentation file.
-doc:<file> Generates XML documentation file to <file>.
-refout:<file> Reference assembly output to generate
- INPUT FILES -
-addmodule:<file_list> Reference metadata from the specified modules
-link:<file_list> Embed metadata from the specified interop
assembly. (Short form: -l)
-recurse:<wildcard> Include all files in the current directory
and subdirectories according to the
wildcard specifications.
-reference:<file_list> Reference metadata from the specified
assembly. (Short form: -r)
-analyzer:<file_list> Run the analyzers from this assembly
(Short form: -a)
-additionalfile:<file list> Additional files that don't directly affect code
generation but may be used by analyzers for producing
errors or warnings.
- RESOURCES -
-linkresource:<resinfo> Links the specified file as an external
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -linkres)
-nowin32manifest The default manifest should not be embedded
in the manifest section of the output PE.
-resource:<resinfo> Adds the specified file as an embedded
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -res)
-win32icon:<file> Specifies a Win32 icon file (.ico) for the
default Win32 resources.
-win32manifest:<file> The provided file is embedded in the manifest
section of the output PE.
-win32resource:<file> Specifies a Win32 resource file (.res).
- CODE GENERATION -
-optimize[+|-] Enable optimizations.
-removeintchecks[+|-] Remove integer checks. Default off.
-debug[+|-] Emit debugging information.
-debug:full Emit full debugging information (default).
-debug:pdbonly Emit full debugging information.
-debug:portable Emit cross-platform debugging information.
-debug:embedded Emit cross-platform debugging information into
the target .dll or .exe.
-deterministic Produce a deterministic assembly
(including module version GUID and timestamp)
-refonly Produce a reference assembly in place of the main output
-instrument:TestCoverage Produce an assembly instrumented to collect
coverage information
-sourcelink:<file> Source link info to embed into PDB.
- ERRORS AND WARNINGS -
-nowarn Disable all warnings.
-nowarn:<number_list> Disable a list of individual warnings.
-warnaserror[+|-] Treat all warnings as errors.
-warnaserror[+|-]:<number_list> Treat a list of warnings as errors.
-ruleset:<file> Specify a ruleset file that disables specific
diagnostics.
-errorlog:<file>[,version=<sarif_version>]
Specify a file to log all compiler and analyzer
diagnostics in SARIF format.
sarif_version:{1|2|2.1} Default is 1. 2 and 2.1
both mean SARIF version 2.1.0.
-reportanalyzer Report additional analyzer information, such as
execution time.
-skipanalyzers[+|-] Skip execution of diagnostic analyzers.
- LANGUAGE -
-define:<symbol_list> Declare global conditional compilation
symbol(s). symbol_list:name=value,...
(Short form: -d)
-imports:<import_list> Declare global Imports for namespaces in
referenced metadata files.
import_list:namespace,...
-langversion:? Display the allowed values for language version
-langversion:<string> Specify language version such as
`default` (latest major version), or
`latest` (latest version, including minor versions),
or specific versions like `14` or `15.3`
-optionexplicit[+|-] Require explicit declaration of variables.
-optioninfer[+|-] Allow type inference of variables.
-rootnamespace:<string> Specifies the root Namespace for all type
declarations.
-optionstrict[+|-] Enforce strict language semantics.
-optionstrict:custom Warn when strict language semantics are not
respected.
-optioncompare:binary Specifies binary-style string comparisons.
This is the default.
-optioncompare:text Specifies text-style string comparisons.
- MISCELLANEOUS -
-help Display this usage message. (Short form: -?)
-noconfig Do not auto-include VBC.RSP file.
-nologo Do not display compiler copyright banner.
-quiet Quiet output mode.
-verbose Display verbose messages.
-parallel[+|-] Concurrent build.
-version Display the compiler version number and exit.
- ADVANCED -
-baseaddress:<number> The base address for a library or module
(hex).
-checksumalgorithm:<alg> Specify algorithm for calculating source file
checksum stored in PDB. Supported values are:
SHA1 or SHA256 (default).
-codepage:<number> Specifies the codepage to use when opening
source files.
-delaysign[+|-] Delay-sign the assembly using only the public
portion of the strong name key.
-publicsign[+|-] Public-sign the assembly using only the public
portion of the strong name key.
-errorreport:<string> Specifies how to handle internal compiler
errors; must be prompt, send, none, or queue
(default).
-filealign:<number> Specify the alignment used for output file
sections.
-highentropyva[+|-] Enable high-entropy ASLR.
-keycontainer:<string> Specifies a strong name key container.
-keyfile:<file> Specifies a strong name key file.
-libpath:<path_list> List of directories to search for metadata
references. (Semi-colon delimited.)
-main:<class> Specifies the Class or Module that contains
Sub Main. It can also be a Class that
inherits from System.Windows.Forms.Form.
(Short form: -m)
-moduleassemblyname:<string> Name of the assembly which this module will
be a part of.
-netcf Target the .NET Compact Framework.
-nostdlib Do not reference standard libraries
(system.dll and VBC.RSP file).
-pathmap:<K1>=<V1>,<K2>=<V2>,...
Specify a mapping for source path names output by
the compiler.
-platform:<string> Limit which platforms this code can run on;
must be x86, x64, Itanium, arm, arm64
AnyCPU32BitPreferred or anycpu (default).
-preferreduilang Specify the preferred output language name.
-nosdkpath Disable searching the default SDK path for standard library assemblies.
-sdkpath:<path> Location of the .NET Framework SDK directory
(mscorlib.dll).
-subsystemversion:<version> Specify subsystem version of the output PE.
version:<number>[.<number>]
-utf8output[+|-] Emit compiler output in UTF8 character
encoding.
@<file> Insert command-line settings from a text file
-vbruntime[+|-|*] Compile with/without the default Visual Basic
runtime.
-vbruntime:<file> Compile with the alternate Visual Basic
runtime in <file>.
</source>
<target state="translated"> Параметры компилятора Visual Basic
- Выходной файл -
-out:<file> Задает имя выходного файла.
-target:exe Создать консольное приложение (по умолчанию).
(Краткая форма: -t)
-target:winexe Создать Windows-приложение.
-target:library Создать библиотечную сборку.
-target:module Создать модуль, который может быть добавлен в
сборку.
-target:appcontainerexe Создать Windows-приложение, выполняемое в контейнере
AppContainer.
-target:winmdobj Создать промежуточный файл метаданных Windows
-doc[+|-] Создает XML-файл документации.
-doc:<file> Создает XML-файл документации <file>.
-refout:<file> Выходные данные создаваемой базовой сборки
- Входные файлы -
-addmodule:<file_list> Ссылка на метаданные из заданных модулей
-link:<file_list> Внедрить метаданные из указанной сборки
взаимодействия. (Краткая форма: -l)
-recurse:<wildcard> Включить все файлы в текущем каталоге
и подкаталогах в соответствии с
заданным шаблоном.
-reference:<file_list> Ссылка на метаданные из заданной
сборки. (Краткая форма: -r)
-analyzer:<file_list> Запускать анализаторы из этой сборки
(Краткая форма: -a)
-additionalfile:<file list> Дополнительные файлы, которые не оказывают прямого влияния на создание
кода, но могут использоваться анализаторами для вывода
ошибок или предупреждений.
- Ресурсы -
-linkresource:<resinfo> Привязывает указанный файл в качестве внешнего
ресурса сборки.
Данные о ресурсе:<file>[,<name>[,public|private]]
(Краткая форма: -linkres)
-nowin32manifest Манифест по умолчанию не должен внедряться
в раздел манифеста выходного PE-файла.
-resource:<resinfo> Добавляет указанный файл в качестве внедренного
ресурса сборки.
Данные о ресурсе:<file>[,<name>[,public|private]]
(Краткая форма: -res)
-win32icon:<file> Задает файл значка Win32 (ICO-файл) для
ресурсов Win32 по умолчанию.
-win32manifest:<file> Предоставленный файл внедряется в раздел
манифеста выходного PE-файла.
-win32resource:<file> Задает файл ресурсов Win32 (RES-файл).
- Создание кода -
-optimize[+|-] Включить оптимизацию.
-removeintchecks[+|-] Удалить целочисленные проверки. По умолчанию отключены.
-debug[+|-] Выдать отладочные данные.
-debug:full Выдать полные отладочные данные (по умолчанию).
-debug:pdbonly Выдать полные отладочные данные.
-debug:portable Выдать кроссплатформенные отладочные данные.
-debug:embedded Выдать кроссплатформенные отладочные данные в
целевой DLL-файл или EXE-файл.
-deterministic Создать детерминированную сборку
(включая GUID версии модуля и метку времени)
-refonly Создавать базовую сборку вместо основных выходных данных
-instrument:TestCoverage Создавать сборку, инструментированную для сбора
данных об объеме протестированного кода
-sourcelink:<file> Данные о ссылке на исходные файлы для внедрения в PDB.
- Ошибки и предупреждения -
-nowarn Отключить все предупреждения.
-nowarn:<number_list> Отключить отдельные предупреждения по списку.
-warnaserror[+|-] Обрабатывать все предупреждения как ошибки.
-warnaserror[+|-]:<number_list> Обрабатывать список предупреждений как ошибки.
-ruleset:<file> Указать файл набора правил, отключающий определенные
диагностические операции.
-errorlog:<file>[,version=<sarif_version>]
Указать файл для записи всех диагностических данных
компилятора и анализатора в формате SARIF.
sarif_version:{1|2|2.1} По умолчанию используются значения 1. 2 и 2.1,
обозначающие версию SARIF 2.1.0.
-reportanalyzer Сообщить дополнительные сведения об анализаторе, например
время выполнения.
-skipanalyzers[+|-] Пропустить выполнение анализаторов диагностики.
- Язык -
-define:<symbol_list> Объявить глобальные символы условной
компиляции. symbol_list:имя=значение,...
(Краткая форма: -d)
-imports:<import_list> Объявить глобальные импорты для пространств имен в
указанных файлах метаданных.
import_list:пространство_имен,...
-langversion:? Отображать допустимые значения версии языка
-langversion:<string> Указать версию языка, например
"default" (последний основной номер версии) или
"latest" (последняя версия, включая дополнительные номера),
или конкретные версии, например 14 или 15.3
-optionexplicit[+|-] Требовать явное объявление переменных.
-optioninfer[+|-] Разрешить вывод для типов переменных.
-rootnamespace:<string> Задает корневое пространство имен для всех объявлений
типов.
-optionstrict[+|-] Требовать строгую семантику языка.
-optionstrict:custom Предупреждать, когда не соблюдается строгая семантика
языка.
-optioncompare:binary Задает сравнение строк как двоичных данных.
Задано по умолчанию.
-optioncompare:text Задает сравнение строк как текста.
- Прочее -
-help Отображать это сообщение об использовании. (Краткая форма: -?)
-noconfig Не включать файл VBC.RSP в состав автоматически.
-nologo Не отображать заставку компилятора с информацией об авторских правах.
-quiet Режим вывода без сообщений.
-verbose Отображать подробные сообщения.
-parallel[+|-] Параллельная сборка.
-version Отобразить номер версии компилятора и выйти.
- Дополнительно -
-baseaddress:<number> Базовый адрес библиотеки или модуля
(шестнадцатеричный).
-checksumalgorithm:<alg> Задать алгоритм расчета контрольной суммы
исходного файла, хранимой в PDB. Поддерживаемые значения:
SHA1 или SHA256 (по умолчанию).
-codepage:<number> Указывает кодовую страницу, используемую при открытии
исходных файлов.
-delaysign[+|-] Использовать отложенную подпись для сборки, применяя только
открытую часть ключа строгого имени.
-publicsign[+|-] Выполнить общедоступную подпись сборки, используя только открытую
часть ключа строгого имени.
-errorreport:<string> Указывает способ обработки внутренних ошибок
компилятора; принимает prompt, send, none или queue
(по умолчанию).
-filealign:<number> Задать выравнивание для разделов выходных
файлов.
-highentropyva[+|-] Включить ASLR с высокой энтропией.
-keycontainer:<string> Задает контейнер ключа строгого имени.
-keyfile:<file> Задает файл ключа строгого имени.
-libpath:<path_list> Список каталогов для поиска ссылок на
метаданные. (Разделитель — точка с запятой.)
-main:<class> Задает класс или модуль, содержащий
Sub Main. Он может являться производным
классом от System.Windows.Forms.Form.
(Краткая форма: -m)
-moduleassemblyname:<string> Имя сборки, частью которой будет
данный модуль.
-netcf Целевая версия .NET Compact Framework.
-nostdlib Не обращаться к стандартным библиотекам
(файл system.dll и VBC.RSP).
-pathmap:<K1>=<V1>,<K2>=<V2>,...
Указать сопоставление для выходных данных имен исходного пути по
компилятору.
-platform:<string> Ограничить платформы, на которых может выполняться этот код:
x86, x64, Itanium, arm, arm64
AnyCPU32BitPreferred или anycpu (по умолчанию).
-preferreduilang Указать имя предпочтительного языка вывода.
-nosdkpath Отключить поиск пути пакета SDK по умолчанию для сборок стандартных библиотек.
-sdkpath:<path> Расположение каталога пакета SDK .NET Framework
(mscorlib.dll).
-subsystemversion:<version> Указать версию подсистемы выходного PE-файла.
version:<number>[.<number>]
-utf8output[+|-] Выдавать выходные данные компилятора в кодировке
UTF8.
@<file> Вставить параметры командной строки из текстового файла
-vbruntime[+|-|*] Скомпилировать с помощью или без использования стандартной среды выполнения
Visual Basic.
-vbruntime:<file> Скомпилировать с помощью альтернативной среды выполнения
Visual Basic в <file>.
</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoFunctionPointerTypesInVB">
<source>There are no function pointer types in VB.</source>
<target state="translated">В VB отсутствуют типы указателей на функции.</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoNativeIntegerTypesInVB">
<source>There are no native integer types in VB.</source>
<target state="translated">В VB нет собственных целочисленных типов.</target>
<note />
</trans-unit>
<trans-unit id="Trees0">
<source>trees({0})</source>
<target state="translated">деревья({0})</target>
<note />
</trans-unit>
<trans-unit id="TreesMustHaveRootNode">
<source>trees({0}) must have root node with SyntaxKind.CompilationUnit.</source>
<target state="translated">Деревья({0}) должны иметь корневой узел SyntaxKind.CompilationUnit.</target>
<note />
</trans-unit>
<trans-unit id="CannotAddCompilerSpecialTree">
<source>Cannot add compiler special tree</source>
<target state="translated">Не удается добавить особое дерево компилятора</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeAlreadyPresent">
<source>Syntax tree already present</source>
<target state="translated">Синтаксическое дерево уже имеется</target>
<note />
</trans-unit>
<trans-unit id="SubmissionCanHaveAtMostOneSyntaxTree">
<source>Submission can have at most one syntax tree.</source>
<target state="translated">Отправка может иметь максимум одно синтаксическое дерево.</target>
<note />
</trans-unit>
<trans-unit id="CannotRemoveCompilerSpecialTree">
<source>Cannot remove compiler special tree</source>
<target state="translated">Не удается удалить особое дерево компилятора</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeNotFoundToRemove">
<source>SyntaxTree '{0}' not found to remove</source>
<target state="translated">SyntaxTree "{0}" не найдено и не будет удалено.</target>
<note />
</trans-unit>
<trans-unit id="TreeMustHaveARootNodeWithCompilationUnit">
<source>Tree must have a root node with SyntaxKind.CompilationUnit</source>
<target state="translated">Деревья должны иметь корневой узел SyntaxKind.CompilationUnit.</target>
<note />
</trans-unit>
<trans-unit id="CompilationVisualBasic">
<source>Compilation (Visual Basic): </source>
<target state="translated">Компиляция (Visual Basic):</target>
<note />
</trans-unit>
<trans-unit id="NodeIsNotWithinSyntaxTree">
<source>Node is not within syntax tree</source>
<target state="translated">Узел не входит в синтаксическое дерево.</target>
<note />
</trans-unit>
<trans-unit id="CantReferenceCompilationFromTypes">
<source>Can't reference compilation of type '{0}' from {1} compilation.</source>
<target state="translated">Не удается создать ссылку на компиляцию типа "{0}" из компиляции {1}.</target>
<note />
</trans-unit>
<trans-unit id="PositionOfTypeParameterTooLarge">
<source>position of type parameter too large</source>
<target state="translated">Позиция типа параметра является слишком большой.</target>
<note />
</trans-unit>
<trans-unit id="AssociatedTypeDoesNotHaveTypeParameters">
<source>Associated type does not have type parameters</source>
<target state="translated">У связанного типа отсутствуют параметры типа.</target>
<note />
</trans-unit>
<trans-unit id="IDS_FunctionReturnType">
<source>function return type</source>
<target state="translated">тип возвращаемого функцией значения</target>
<note />
</trans-unit>
<trans-unit id="TypeArgumentCannotBeNothing">
<source>Type argument cannot be Nothing</source>
<target state="translated">Аргумент типа не может иметь значение Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework">
<source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source>
<target state="translated">Сборка "{0}", содержащая тип "{1}", ссылается на платформу .NET Framework, которая не поддерживается.</target>
<note>{1} is the type that was loaded, {0} is the containing assembly.</note>
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework_Title">
<source>The loaded assembly references .NET Framework, which is not supported.</source>
<target state="translated">Загруженная сборка ссылается на платформу .NET Framework, которая не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration">
<source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">Генератору "{0}" не удалось создать источник. Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}"</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">Генератор создал следующее исключение:
"{0}".</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Title">
<source>Generator failed to generate source.</source>
<target state="translated">Генератору не удалось создать источник.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization">
<source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">Не удалось инициализировать генератор "{0}". Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}"</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">Генератор создал следующее исключение:
"{0}".</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Title">
<source>Generator failed to initialize.</source>
<target state="translated">Не удалось инициализировать генератор.</target>
<note />
</trans-unit>
<trans-unit id="WrongNumberOfTypeArguments">
<source>Wrong number of type arguments</source>
<target state="translated">Неверное число аргументов типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileNotFound">
<source>file '{0}' could not be found</source>
<target state="translated">Не удалось найти файл "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoResponseFile">
<source>unable to open response file '{0}'</source>
<target state="translated">Не удается открыть файл ответов "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentRequired">
<source>option '{0}' requires '{1}'</source>
<target state="translated">параметр "{0}" требует "{1}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_SwitchNeedsBool">
<source>option '{0}' can be followed only by '+' or '-'</source>
<target state="translated">за параметром "{0}" может следовать только "+" или "-"</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSwitchValue">
<source>the value '{1}' is invalid for option '{0}'</source>
<target state="translated">значение "{1}" недопустимо для параметра "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_MutuallyExclusiveOptions">
<source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source>
<target state="translated">Параметры компиляции "{0}" и "{1}" невозможно использовать одновременно.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang">
<source>The language name '{0}' is invalid.</source>
<target state="translated">Недопустимое имя языка "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang_Title">
<source>The language name for /preferreduilang is invalid</source>
<target state="translated">Название языка для /preferreduilang недопустимо</target>
<note />
</trans-unit>
<trans-unit id="ERR_VBCoreNetModuleConflict">
<source>The options /vbruntime* and /target:module cannot be combined.</source>
<target state="translated">Невозможно объединить параметры /vbruntime* и /target:module.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatForGuidForOption">
<source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source>
<target state="translated">Ошибка в синтаксисе командной строки: Недопустимый формат Guid "{0}" для параметра "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingGuidForOption">
<source>Command-line syntax error: Missing Guid for option '{1}'</source>
<target state="translated">Ошибка в синтаксисе командной строки: Отсутствует Guid для параметра "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadChecksumAlgorithm">
<source>Algorithm '{0}' is not supported</source>
<target state="translated">Алгоритм "{0}" не поддерживается</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch">
<source>unrecognized option '{0}'; ignored</source>
<target state="translated">нераспознанный параметр "{0}"; проигнорирован</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch_Title">
<source>Unrecognized command-line option</source>
<target state="translated">Нераспознанный параметр командной строки</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSources">
<source>no input sources specified</source>
<target state="translated">не задано входящих источников</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded">
<source>source file '{0}' specified multiple times</source>
<target state="translated">Исходный файл "{0}" задан несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded_Title">
<source>Source file specified multiple times</source>
<target state="translated">Исходный файл указан несколько раз</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOpenFileWrite">
<source>can't open '{0}' for writing: {1}</source>
<target state="translated">не удается открыть "{0}" для записи: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCodepage">
<source>code page '{0}' is invalid or not installed</source>
<target state="translated">Кодовая страница "{0}" является недопустимой или не установлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryFile">
<source>the file '{0}' is not a text file</source>
<target state="translated">файл "{0}" не является текстовым</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibNotFound">
<source>could not find library '{0}'</source>
<target state="translated">Не удалось найти библиотеку "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataReferencesNotSupported">
<source>Metadata references not supported.</source>
<target state="translated">Ссылки на метаданные не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IconFileAndWin32ResFile">
<source>cannot specify both /win32icon and /win32resource</source>
<target state="translated">Не удается определить /win32icon и /win32resource</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile">
<source>ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">Параметр /noconfig проигнорирован, потому что он задан в файле ответов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile_Title">
<source>Ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">Параметр /noconfig пропущен, т. к. он задан в файле ответов</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId">
<source>warning number '{0}' for the option '{1}' is either not configurable or not valid</source>
<target state="translated">Номер предупреждения "{0}" для параметра "{1}" не настраивается или недопустим</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId_Title">
<source>Warning number is either not configurable or not valid</source>
<target state="translated">Номер предупреждения недоступен для настройки или недопустим</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSourcesOut">
<source>cannot infer an output file name from resource only input files; provide the '/out' option</source>
<target state="translated">Не удалось определить имя выходного файла из ресурса только входных файлов; укажите параметр "/out"</target>
<note />
</trans-unit>
<trans-unit id="ERR_NeedModule">
<source>the /moduleassemblyname option may only be specified when building a target of type 'module'</source>
<target state="translated">Параметр /moduleassemblyname может использоваться только при создании типа "module"</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyName">
<source>'{0}' is not a valid value for /moduleassemblyname</source>
<target state="translated">"{0}" не является допустимым значением для /moduleassemblyname</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingManifestSwitches">
<source>Error embedding Win32 manifest: Option /win32manifest conflicts with /nowin32manifest.</source>
<target state="translated">Ошибка при внедрении манифеста Win32: Параметр /win32manifest конфликтует с /nowin32manifest.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest">
<source>Option /win32manifest ignored. It can be specified only when the target is an assembly.</source>
<target state="translated">Параметр / win32manifest игнорируется. Он может быть задан, только если целевым объектом является сборка.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest_Title">
<source>Option /win32manifest ignored</source>
<target state="translated">Параметр /win32manifest пропускается</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInNamespace">
<source>Statement is not valid in a namespace.</source>
<target state="translated">Не допускается применение операторов в пространствах имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedType1">
<source>Type '{0}' is not defined.</source>
<target state="translated">Тип "{0}" не определен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNext">
<source>'Next' expected.</source>
<target state="translated">'Требуется "Next".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCharConstant">
<source>Character constant must contain exactly one character.</source>
<target state="translated">Символьная константа должна содержать ровно один символ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssemblyEvent3">
<source>Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется сборка, содержащая определение события "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModuleEvent3">
<source>Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется ссылка, содержащая определение события "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbExpectedEndIf">
<source>'#If' block must end with a matching '#End If'.</source>
<target state="translated">'Блок "#If" должен завершаться соответствующим блоком "#End If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbNoMatchingIf">
<source>'#ElseIf', '#Else', or '#End If' must be preceded by a matching '#If'.</source>
<target state="translated">'Блоку "#ElseIf", "#Else" или "#End If" должен предшествовать соответствующий оператор "#If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbBadElseif">
<source>'#ElseIf' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'Блоку "#ElseIf" должен предшествовать соответствующий блок "#If" или "#ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromRestrictedType1">
<source>Inheriting from '{0}' is not valid.</source>
<target state="translated">Наследование от "{0}" недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvOutsideProc">
<source>Labels are not valid outside methods.</source>
<target state="translated">Метки за пределами методов недействительны.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantImplement">
<source>Delegates cannot implement interface methods.</source>
<target state="translated">Делегаты не могут реализовывать методы интерфейсов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantHandleEvents">
<source>Delegates cannot handle events.</source>
<target state="translated">Делегаты не могут обрабатывать события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorRequiresReferenceTypes1">
<source>'Is' operator does not accept operands of type '{0}'. Operands must be reference or nullable types.</source>
<target state="translated">'Оператор "Is" не принимает операнды типа "{0}". Операнды должны быть ссылочными типами или типами, допускающими значения Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfRequiresReferenceType1">
<source>'TypeOf ... Is' requires its left operand to have a reference type, but this operand has the value type '{0}'.</source>
<target state="translated">'"TypeOf ... Is" требует, чтобы левый операнд имел ссылочный тип, но этот операнд имеет тип значения "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasSet">
<source>Properties declared 'ReadOnly' cannot have a 'Set'.</source>
<target state="translated">Свойства, объявленные как доступные только для чтения (ReadOnly), не могут иметь метод "Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasGet">
<source>Properties declared 'WriteOnly' cannot have a 'Get'.</source>
<target state="translated">Свойства, объявленные как доступные только для записи (WriteOnly), не могут иметь метод Get.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideProc">
<source>Statement is not valid inside a method.</source>
<target state="translated">Недопустимый оператор в методе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideBlock">
<source>Statement is not valid inside '{0}' block.</source>
<target state="translated">Недопустимый оператор в блоке "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedExpressionStatement">
<source>Expression statement is only allowed at the end of an interactive submission.</source>
<target state="translated">Выражение оператора допускается только в конце интерактивной отправки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndProp">
<source>Property missing 'End Property'.</source>
<target state="translated">В свойстве отсутствует "End Property".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSubExpected">
<source>'End Sub' expected.</source>
<target state="translated">'Требуется "End Sub".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndFunctionExpected">
<source>'End Function' expected.</source>
<target state="translated">'Требуется "End Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseNoMatchingIf">
<source>'#Else' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'Блоку "#Else" должен предшествовать соответствующий блок "#If" или "#ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantRaiseBaseEvent">
<source>Derived classes cannot raise base class events.</source>
<target state="translated">Производные классы не могут генерировать события базовых классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryWithoutCatchOrFinally">
<source>Try must have at least one 'Catch' or a 'Finally'.</source>
<target state="translated">Оператор "Try" должен содержать хотя бы один блок "Catch" или "Finally".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventsCantBeFunctions">
<source>Events cannot have a return type.</source>
<target state="translated">Событиям невозможно задать возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndBrack">
<source>Bracketed identifier is missing closing ']'.</source>
<target state="translated">У идентификатора в квадратных скобках отсутствует закрывающая скобка "]".</target>
<note />
</trans-unit>
<trans-unit id="ERR_Syntax">
<source>Syntax error.</source>
<target state="translated">Синтаксическая ошибка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_Overflow">
<source>Overflow.</source>
<target state="translated">Переполнение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalChar">
<source>Character is not valid.</source>
<target state="translated">Недопустимый символ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected">
<source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source>
<target state="translated">Указан аргумент stdin "-", но входные данные не были перенаправлены из стандартного входного потока.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectOperand1">
<source>Option Strict On prohibits operands of type Object for operator '{0}'.</source>
<target state="translated">Option Strict On запрещает операнды типа Object для оператора "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotBeProperty">
<source>Loop control variable cannot be a property or a late-bound indexed array.</source>
<target state="translated">Переменной цикла не может являться свойство или проиндексированный массив с поздним связыванием.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodBodyNotAtLineStart">
<source>First statement of a method body cannot be on the same line as the method declaration.</source>
<target state="translated">Первый оператор тела метода не может находиться на одной строке с объявлением этого метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MaximumNumberOfErrors">
<source>Maximum number of errors has been exceeded.</source>
<target state="translated">Превышено допустимое число ошибок.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordNotInInstanceMethod1">
<source>'{0}' is valid only within an instance method.</source>
<target state="translated">"{0}" допускается только в методе экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromStructure1">
<source>'{0}' is not valid within a structure.</source>
<target state="translated">"{0}" не является допустимым в структуре.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor1">
<source>Attribute constructor has a parameter of type '{0}', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types.</source>
<target state="translated">Конструктор атрибута имеет параметр типа "{0}", который не является ни целым числом или числом с плавающей запятой, ни перечислением, ни параметром одного из следующих типов: Object, Char, String, Boolean или System.Type, ни одномерным массивом этих типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWithOptArgs">
<source>Method cannot have both a ParamArray and Optional parameters.</source>
<target state="translated">Метод не может одновременно иметь параметры ParamArray и Optional.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedArray1">
<source>'{0}' statement requires an array.</source>
<target state="translated">'Оператор "{0}" требует массив.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayNotArray">
<source>ParamArray parameter must be an array.</source>
<target state="translated">Параметр ParamArray должен быть массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayRank">
<source>ParamArray parameter must be a one-dimensional array.</source>
<target state="translated">Параметр ParamArray должен быть одномерным массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayRankLimit">
<source>Array exceeds the limit of 32 dimensions.</source>
<target state="translated">Число измерений массива превышает максимально допустимое значение 32.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsNewArray">
<source>Arrays cannot be declared with 'New'.</source>
<target state="translated">Массивы не могут объявляться с помощью ключевого слова "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs1">
<source>Too many arguments to '{0}'.</source>
<target state="translated">Слишком много аргументов для "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedCase">
<source>Statements and labels are not valid between 'Select Case' and first 'Case'.</source>
<target state="translated">Операторы и метки между "Select Case" и первым блоком "Case" недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstExpr">
<source>Constant expression is required.</source>
<target state="translated">Требуется константное выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression.</source>
<target state="translated">Преобразование "{0}" в "{1}" не может происходить в константном выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMe">
<source>'Me' cannot be the target of an assignment.</source>
<target state="translated">'"Me" не может присваиваться значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyAssignment">
<source>'ReadOnly' variable cannot be the target of an assignment.</source>
<target state="translated">'Доступной только для чтения (ReadOnly) переменной нельзя присвоить значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSubOfFunc">
<source>'Exit Sub' is not valid in a Function or Property.</source>
<target state="translated">'Использование оператора "Exit Sub" в функциях и свойствах недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitPropNot">
<source>'Exit Property' is not valid in a Function or Sub.</source>
<target state="translated">'Использование оператора "Exit Property" в функциях и подпрограммах недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitFuncOfSub">
<source>'Exit Function' is not valid in a Sub or Property.</source>
<target state="translated">'Использование оператора "Exit Function" в подпрограммах и свойствах недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LValueRequired">
<source>Expression is a value and therefore cannot be the target of an assignment.</source>
<target state="translated">Выражение является значением, поэтому ему нельзя ничего присваивать.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForIndexInUse1">
<source>For loop control variable '{0}' already in use by an enclosing For loop.</source>
<target state="translated">Управляющая переменная цикла For "{0}" уже используется вложенным циклом For.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextForMismatch1">
<source>Next control variable does not match For loop control variable '{0}'.</source>
<target state="translated">Следующая переменная элемента управления не соответствует переменной "{0}" цикла For.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseElseNoSelect">
<source>'Case Else' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'"Case Else" может использоваться только в теле оператора "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseNoSelect">
<source>'Case' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'"Case" может использоваться только в теле оператора "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAssignToConst">
<source>Constant cannot be the target of an assignment.</source>
<target state="translated">Константе нельзя ничего присваивать.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedSubscript">
<source>Named arguments are not valid as array subscripts.</source>
<target state="translated">Недопустимо использовать именованные аргументы как индексы массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndIf">
<source>'If' must end with a matching 'End If'.</source>
<target state="translated">'Блок "If" должен заканчиваться соответствующим оператором "End If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWhile">
<source>'While' must end with a matching 'End While'.</source>
<target state="translated">'Блок "While" должен заканчиваться соответствующим оператором "End While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLoop">
<source>'Do' must end with a matching 'Loop'.</source>
<target state="translated">'Блок "Do" должен заканчиваться соответствующим оператором "Loop".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNext">
<source>'For' must end with a matching 'Next'.</source>
<target state="translated">'Блок "For" должен заканчиваться соответствующим оператором "Next".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWith">
<source>'With' must end with a matching 'End With'.</source>
<target state="translated">'Блок "With" должен заканчиваться соответствующим оператором "End With".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseNoMatchingIf">
<source>'Else' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'Оператору "ElseIf" должен предшествовать соответствующий "If" или "ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndIfNoMatchingIf">
<source>'End If' must be preceded by a matching 'If'.</source>
<target state="translated">'Оператору "End If" должен предшествовать соответствующий оператор "If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSelectNoSelect">
<source>'End Select' must be preceded by a matching 'Select Case'.</source>
<target state="translated">'Оператору "End Select" должен предшествовать соответствующий оператор "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitDoNotWithinDo">
<source>'Exit Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'"Exit Do" может использоваться только в теле оператора "Do".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWhileNoWhile">
<source>'End While' must be preceded by a matching 'While'.</source>
<target state="translated">'Оператору "End While" должен предшествовать соответствующий оператор "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopNoMatchingDo">
<source>'Loop' must be preceded by a matching 'Do'.</source>
<target state="translated">'Оператору "Loop" должен предшествовать соответствующий оператор "Do".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextNoMatchingFor">
<source>'Next' must be preceded by a matching 'For'.</source>
<target state="translated">'Оператору "Next" должен предшествовать соответствующий оператор "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWithWithoutWith">
<source>'End With' must be preceded by a matching 'With'.</source>
<target state="translated">'Оператору "End With" должен предшествовать соответствующий оператор "With".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefined1">
<source>Label '{0}' is already defined in the current method.</source>
<target state="translated">Метка "{0}" уже определена в текущем методе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSelect">
<source>'Select Case' must end with a matching 'End Select'.</source>
<target state="translated">'Блок "Select Case" должен заканчиваться соответствующим оператором "End Select".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitForNotWithinFor">
<source>'Exit For' can only appear inside a 'For' statement.</source>
<target state="translated">'"Exit For" может использоваться только в теле оператора "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitWhileNotWithinWhile">
<source>'Exit While' can only appear inside a 'While' statement.</source>
<target state="translated">'"Exit While" может использоваться только в теле оператора "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyProperty1">
<source>'ReadOnly' property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Свойство "ReadOnly" "{0}" не может быть целевым объектом назначения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSelectNotWithinSelect">
<source>'Exit Select' can only appear inside a 'Select' statement.</source>
<target state="translated">'"Exit Select" может использоваться только в теле оператора "Select".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BranchOutOfFinally">
<source>Branching out of a 'Finally' is not valid.</source>
<target state="translated">Переход из блока "Finally" является недопустимым.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualNotObjectRecord1">
<source>'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'.</source>
<target state="translated">'!' требует, чтобы левый операнд имел параметр типа, класс или тип интерфейса, но этот операнд имеет тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewIndices">
<source>Number of indices is less than the number of dimensions of the indexed array.</source>
<target state="translated">Число индексов меньше числа измерений индексированного массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyIndices">
<source>Number of indices exceeds the number of dimensions of the indexed array.</source>
<target state="translated">Число индексов больше числа измерений индексированного массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EnumNotExpression1">
<source>'{0}' is an Enum type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом Enum и не может использоваться как выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeNotExpression1">
<source>'{0}' is a type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом и не может использоваться в качестве выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassNotExpression1">
<source>'{0}' is a class type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом класса и не может использоваться как выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNotExpression1">
<source>'{0}' is a structure type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом структуры и не может использоваться в качестве выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotExpression1">
<source>'{0}' is an interface type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом интерфейса и не может использоваться как выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotExpression1">
<source>'{0}' is a namespace and cannot be used as an expression.</source>
<target state="translated">"{0}" является пространством имени и не может использоваться в качестве выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNamespaceName1">
<source>'{0}' is not a valid name and cannot be used as the root namespace name.</source>
<target state="translated">"{0}" является недопустимым именем и не может использоваться как имя корневого пространства имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlPrefixNotExpression">
<source>'{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object.</source>
<target state="translated">"{0}" является префиксом XML и не может использоваться в качестве выражения. Используйте оператор GetXmlNamespace для создания объекта пространства имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleExtends">
<source>'Inherits' can appear only once within a 'Class' statement and can only specify one class.</source>
<target state="translated">'В операторе "Class" ключевое слово "Inherits" может использоваться только один раз и задавать только один класс.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropMustHaveGetSet">
<source>Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.</source>
<target state="translated">Свойство без спецификаторов "ReadOnly" или "WriteOnly" должно содержать методы "Get" и "Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasNoWrite">
<source>'WriteOnly' property must provide a 'Set'.</source>
<target state="translated">'Свойство со спецификатором WriteOnly должно иметь метод Set.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasNoGet">
<source>'ReadOnly' property must provide a 'Get'.</source>
<target state="translated">'Свойство со спецификатором "ReadOnly" должно иметь метод "Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttribute1">
<source>Attribute '{0}' is not valid: Incorrect argument value.</source>
<target state="translated">Недопустимый атрибут "{0}": Неверное значение аргумента.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LabelNotDefined1">
<source>Label '{0}' is not defined.</source>
<target state="translated">Метка "{0}" не определена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ErrorCreatingWin32ResourceFile">
<source>Error creating Win32 resources: {0}</source>
<target state="translated">Ошибка при создании ресурсов Win32: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToCreateTempFile">
<source>Cannot create temporary file: {0}</source>
<target state="translated">Не удается создать временный файл: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCall2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" из "{1}" не имеет доступный "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMember3">
<source>{0} '{1}' must implement '{2}' for interface '{3}'.</source>
<target state="translated">{0} "{1}" должна реализовать "{2}" для интерфейса "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithRef">
<source>Leading '.' or '!' can only appear inside a 'With' statement.</source>
<target state="translated">"." или "!" в начале строки может использоваться только в теле оператора With.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAccessCategoryUsed">
<source>Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.</source>
<target state="translated">Можно указать только один из модификаторов: "Public", "Private", "Protected", "Friend", "Protected Friend" или "Private Protected".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateModifierCategoryUsed">
<source>Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.</source>
<target state="translated">Можно указать только одно из значений: "NotOverridable", "MustOverride" или "Overridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateSpecifier">
<source>Specifier is duplicated.</source>
<target state="translated">Повторяющийся спецификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeConflict6">
<source>{0} '{1}' and {2} '{3}' conflict in {4} '{5}'.</source>
<target state="translated">{0} "{1}" и {2} "{3}" конфликтуют в {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeKeyword">
<source>Keyword does not name a type.</source>
<target state="translated">Ключевое слово не задает имя типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraSpecifiers">
<source>Specifiers valid only at the beginning of a declaration.</source>
<target state="translated">Спецификаторы допустимы только в начале объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedType">
<source>Type expected.</source>
<target state="translated">Требуется тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfKeyword">
<source>Keyword is not valid as an identifier.</source>
<target state="translated">Ключевое слово не может использоваться как идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEnum">
<source>'End Enum' must be preceded by a matching 'Enum'.</source>
<target state="translated">'Оператору "End Enum" должен предшествовать соответствующий оператор "Enum".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEnum">
<source>'Enum' must end with a matching 'End Enum'.</source>
<target state="translated">'Блок "Enum" должен заканчиваться соответствующим блоком "End Enum".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDeclaration">
<source>Declaration expected.</source>
<target state="translated">Ожидалось объявление.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeLast">
<source>End of parameter list expected. Cannot define parameters after a paramarray parameter.</source>
<target state="translated">Требуется завершение списка параметров. Невозможно определить параметры, расположенные после параметра ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvalidOnInheritsImplOpt">
<source>Specifiers and attributes are not valid on this statement.</source>
<target state="translated">Для этого оператора спецификаторы и атрибуты являются недопустимыми.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSpecifier">
<source>Expected one of 'Dim', 'Const', 'Public', 'Private', 'Protected', 'Friend', 'Shadows', 'ReadOnly' or 'Shared'.</source>
<target state="translated">Требуется один из этих операторов: "Dim", "Const", "Public", "Private", "Protected", "Friend", "Shadows", "ReadOnly" или "Shared".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedComma">
<source>Comma expected.</source>
<target state="translated">Требуется запятая.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAs">
<source>'As' expected.</source>
<target state="translated">'Требуется "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRparen">
<source>')' expected.</source>
<target state="translated">'Требуется ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLparen">
<source>'(' expected.</source>
<target state="translated">'Требуется "(".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNewInType">
<source>'New' is not valid in this context.</source>
<target state="translated">'В этом контексте "New" является недействительным.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExpression">
<source>Expression expected.</source>
<target state="translated">Требуется выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptional">
<source>'Optional' expected.</source>
<target state="translated">'Требуется "Optional".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifier">
<source>Identifier expected.</source>
<target state="translated">Требуется идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIntLiteral">
<source>Integer constant expected.</source>
<target state="translated">Требуется целочисленная константа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEOS">
<source>End of statement expected.</source>
<target state="translated">Требуется завершение оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedForOptionStmt">
<source>'Option' must be followed by 'Compare', 'Explicit', 'Infer', or 'Strict'.</source>
<target state="translated">'После "Option" должно следовать "Compare", "Explicit", "Infer" или "Strict".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionCompare">
<source>'Option Compare' must be followed by 'Text' or 'Binary'.</source>
<target state="translated">'За оператором "Option Compare" должны следовать "Text" или "Binary".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptionCompare">
<source>'Compare' expected.</source>
<target state="translated">'Требуется Compare.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObject">
<source>Option Strict On requires all variable declarations to have an 'As' clause.</source>
<target state="translated">При использовании параметра "Strict On" все объявления переменных должны иметь предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitProc">
<source>Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.</source>
<target state="translated">При использовании параметра "Strict On" объявления функций, свойств и операторов должны иметь предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitArgs">
<source>Option Strict On requires that all method parameters have an 'As' clause.</source>
<target state="translated">Оператор "Option Strict On" требует, чтобы все параметры метода имели предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidParameterSyntax">
<source>Comma or ')' expected.</source>
<target state="translated">Требуется запятая или ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubFunction">
<source>'Sub' or 'Function' expected.</source>
<target state="translated">'Требуется "Sub" или "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedStringLiteral">
<source>String constant expected.</source>
<target state="translated">Ожидалась строковая константа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingLibInDeclare">
<source>'Lib' expected.</source>
<target state="translated">'Требуется "Lib".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateNoInvoke1">
<source>Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call.</source>
<target state="translated">Класс делегата "{0}" не содержит метода Invoke, поэтому выражение этого типа не может быть результатом вызова метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingIsInTypeOf">
<source>'Is' expected.</source>
<target state="translated">'Требуется "Is".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateOption1">
<source>'Option {0}' statement can only appear once per file.</source>
<target state="translated">'Оператор "Option {0}" можно использовать в файле только один раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantInherit">
<source>'Inherits' not valid in Modules.</source>
<target state="translated">'Оператор "Inherits" недопустим в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantImplement">
<source>'Implements' not valid in Modules.</source>
<target state="translated">'Оператор "Implements" недопустим в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadImplementsType">
<source>Implemented type must be an interface.</source>
<target state="translated">Реализованный тип должен представлять интерфейс.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstFlags1">
<source>'{0}' is not valid on a constant declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении константы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithEventsFlags1">
<source>'{0}' is not valid on a WithEvents declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении WithEvents.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDimFlags1">
<source>'{0}' is not valid on a member variable declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении переменной-члена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParamName1">
<source>Parameter already declared with name '{0}'.</source>
<target state="translated">Параметр уже объявлен с именем "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopDoubleCondition">
<source>'Loop' cannot have a condition if matching 'Do' has one.</source>
<target state="translated">'Оператор "Loop" не может содержать условие, если соответствующий оператор "Do" содержит условие.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRelational">
<source>Relational operator expected.</source>
<target state="translated">Требуется оператор отношения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExitKind">
<source>'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'.</source>
<target state="translated">'За оператором "Exit" должно следовать слово "Sub", "Function", "Property", "Do", "For", "While", "Select" или "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgumentInAttributeList">
<source>Named argument expected.</source>
<target state="translated">Ожидается именованный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation">
<source>Named argument specifications must appear after all fixed arguments have been specified in a late bound invocation.</source>
<target state="translated">Спецификации именованных аргументов должны создаваться после всех указанных фиксированных аргументов в вызове с поздним связыванием.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgument">
<source>Named argument expected. Please use language version {0} or greater to use non-trailing named arguments.</source>
<target state="translated">Ожидается именованный аргумент. Используйте версию языка {0} или более позднюю, чтобы использовать неконечные аргументы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMethodFlags1">
<source>'{0}' is not valid on a method declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEventFlags1">
<source>'{0}' is not valid on an event declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDeclareFlags1">
<source>'{0}' is not valid on a Declare.</source>
<target state="translated">"{0}" является недопустимым для Declare.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalConstFlags1">
<source>'{0}' is not valid on a local constant declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении локальной константы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalDimFlags1">
<source>'{0}' is not valid on a local variable declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении локальной переменной.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedConditionalDirective">
<source>'If', 'ElseIf', 'Else', 'Const', 'Region', 'ExternalSource', 'ExternalChecksum', 'Enable', 'Disable', 'End' or 'R' expected.</source>
<target state="translated">'Ожидались операторы If, ElseIf, Else, Const, Region, ExternalSource, ExternalChecksum, Enable, Disable, End или R.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEQ">
<source>'=' expected.</source>
<target state="translated">'Требуется "=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorNotFound1">
<source>Type '{0}' has no constructors.</source>
<target state="translated">Тип "{0}" не имеет конструкторов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndInterface">
<source>'End Interface' must be preceded by a matching 'Interface'.</source>
<target state="translated">'Оператору "End Interface" должен предшествовать соответствующий оператор "Interface".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndInterface">
<source>'Interface' must end with a matching 'End Interface'.</source>
<target state="translated">'Блок "Interface" должен заканчиваться соответствующим оператором "End Interface".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFrom2">
<source>
'{0}' inherits from '{1}'.</source>
<target state="translated">
"{0}" наследует от "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNestedIn2">
<source>
'{0}' is nested in '{1}'.</source>
<target state="translated">
"{0}" вложено в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycle1">
<source>Class '{0}' cannot inherit from itself: {1}</source>
<target state="translated">Класс "{0}" не может наследовать от себя самого: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonClass">
<source>Classes can inherit only from other classes.</source>
<target state="translated">Классы могут наследовать только от других классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedType3">
<source>'{0}' is already declared as '{1}' in this {2}.</source>
<target state="translated">"{0}" уже объявлено как "{1}" в {2}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverrideAccess2">
<source>'{0}' cannot override '{1}' because they have different access levels.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку у них разные уровни доступа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideNotOverridable2">
<source>'{0}' cannot override '{1}' because it is declared 'NotOverridable'.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку он объявлен как "NotOverridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDef1">
<source>'{0}' has multiple definitions with identical signatures.</source>
<target state="translated">"{0}" имеет несколько определений с одинаковыми сигнатурами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDefWithDifferentTupleNames2">
<source>'{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'.</source>
<target state="translated">"{0}" имеет несколько определений с одинаковыми подписями, но разными именами элементов кортежа, в том числе "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceMethodFlags1">
<source>'{0}' is not valid on an interface method declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением метода интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound2">
<source>'{0}' is not a parameter of '{1}'.</source>
<target state="translated">"{0}" не является параметром "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfacePropertyFlags1">
<source>'{0}' is not valid on an interface property declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением свойства интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice2">
<source>Parameter '{0}' of '{1}' already has a matching argument.</source>
<target state="translated">Параметр "{0}" "{1}" уже имеет соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCantUseEventSpecifier1">
<source>'{0}' is not valid on an interface event declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением события интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNoMatch2">
<source>Type character '{0}' does not match declared data type '{1}'.</source>
<target state="translated">Тип символа "{0}" не соответствует объявленному типу данных "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubOrFunction">
<source>'Sub' or 'Function' expected after 'Delegate'.</source>
<target state="translated">'После "Delegate" требуется "Sub" или "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEmptyEnum1">
<source>Enum '{0}' must contain at least one member.</source>
<target state="translated">Перечисление "{0}" должно содержать хотя бы один член.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidConstructorCall">
<source>Constructor call is valid only as the first statement in an instance constructor.</source>
<target state="translated">Вызов конструктора допустим только как первый оператор в конструкторе экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideConstructor">
<source>'Sub New' cannot be declared 'Overrides'.</source>
<target state="translated">'"Sub New" не может объявляться как "Overrides".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorCannotBeDeclaredPartial">
<source>'Sub New' cannot be declared 'Partial'.</source>
<target state="translated">'"Sub New" нельзя объявить как "Partial".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleEmitFailure">
<source>Failed to emit module '{0}': {1}</source>
<target state="translated">Не удалось выдать модуль "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncUpdateFailedMissingAttribute">
<source>Cannot update '{0}'; attribute '{1}' is missing.</source>
<target state="translated">Невозможно обновить "{0}"; нет атрибута "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideNotNeeded3">
<source>{0} '{1}' cannot be declared 'Overrides' because it does not override a {0} in a base class.</source>
<target state="translated">{0} "{1}" не может быть объявлен как "Overrides", так как он не переопределяет {0} в базовом классе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDot">
<source>'.' expected.</source>
<target state="translated">'Требуется ".".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocals1">
<source>Local variable '{0}' is already declared in the current block.</source>
<target state="translated">Локальная переменная "{0}" уже объявлена в текущем блоке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProc">
<source>Statement cannot appear within a method body. End of method assumed.</source>
<target state="translated">Оператор не может присутствовать в теле метода. Предполагается, что метод закончен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalSameAsFunc">
<source>Local variable cannot have the same name as the function containing it.</source>
<target state="translated">Имя локальной переменной не может совпадать с именем содержащей ее функции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordEmbeds2">
<source>
'{0}' contains '{1}' (variable '{2}').</source>
<target state="translated">
"{0}" содержит "{1}" (переменная "{2}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordCycle2">
<source>Structure '{0}' cannot contain an instance of itself: {1}</source>
<target state="translated">Структура "{0}" не может содержать экземпляр самой себя: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCycle1">
<source>Interface '{0}' cannot inherit from itself: {1}</source>
<target state="translated">Интерфейс "{0}" не может наследовать от себя самого: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle2">
<source>
'{0}' calls '{1}'.</source>
<target state="translated">
"{0}" вызывает "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle1">
<source>Constructor '{0}' cannot call itself: {1}</source>
<target state="translated">Конструктор "{0}" не может вызывать сам себя: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromCantInherit3">
<source>'{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'.</source>
<target state="translated">"{0}" не может наследовать от {2} "{1}", поскольку "{1}" объявлен как "NotInheritable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithOptional2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by optional parameters.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по необязательным параметрам.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithReturnType2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by return types.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по возвращаемым типам.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharWithType1">
<source>Type character '{0}' cannot be used in a declaration with an explicit type.</source>
<target state="translated">Тип символа "{0}" не может быть использован в объявлении с явным типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnSub">
<source>Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.</source>
<target state="translated">Символ типа не может использоваться в объявлении "Sub", так как "Sub" не возвращает значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithDefault2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по значениям по умолчанию необязательных параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingSubscript">
<source>Array subscript expression missing.</source>
<target state="translated">Отсутствует выражение для индексов массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithDefault2">
<source>'{0}' cannot override '{1}' because they differ by the default values of optional parameters.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по значениям по умолчанию необязательных параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptional2">
<source>'{0}' cannot override '{1}' because they differ by optional parameters.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по необязательным параметрам.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldOfValueFieldOfMarshalByRef3">
<source>Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class.</source>
<target state="translated">Невозможно обратиться к "{0}", так как он является членом поля типа значения "{1}" класса "{2}", базовым классом которого является "System.MarshalByRefObject".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}'.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseAfterCaseElse">
<source>'Case' cannot follow a 'Case Else' in the same 'Select' statement.</source>
<target state="translated">'В операторе "Select" блок "Case" не может задаваться после "Case Else".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayMismatch4">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}", поскольку "{2}" не является производным от "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertObjectArrayMismatch3">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}", поскольку "{2}" не является ссылочным типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopType1">
<source>'For' loop control variable cannot be of type '{0}' because the type does not support the required operators.</source>
<target state="translated">'Управляющая переменная цикла "For" не может быть типа "{0}", так как этот тип не поддерживают требуемые операторы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithByref2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ByRef" или "ByVal".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonInterface">
<source>Interface can inherit only from another interface.</source>
<target state="translated">Интерфейс может наследовать только от другого интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceOrderOnInherits">
<source>'Inherits' statements must precede all declarations in an interface.</source>
<target state="translated">'Операторы "Inherits" должны предшествовать всем объявлениям в интерфейсе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateDefaultProps1">
<source>'Default' can be applied to only one property name in a {0}.</source>
<target state="translated">'"Default" может указываться только для одного имени свойства в {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMissingFromProperty2">
<source>'{0}' and '{1}' cannot overload each other because only one is declared 'Default'.</source>
<target state="translated">"{0}" и "{1}" не могут перегружать друг друга, т. к. только один из них объявлен как "Default".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingPropertyKind2">
<source>'{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по типу "ReadOnly" или "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInInterface">
<source>'Sub New' cannot be declared in an interface.</source>
<target state="translated">'"Sub New" нельзя объявлять в интерфейсе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNew1">
<source>'Sub New' cannot be declared '{0}'.</source>
<target state="translated">'"Sub New" нельзя объявить как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadingPropertyKind2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по "ReadOnly" или "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDefaultNotExtend1">
<source>Class '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">Класс "{0}" не может быть индексирован, так как не имеет свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithArrayVsParamArray2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ParamArray".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInstanceMemberAccess">
<source>Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.</source>
<target state="translated">Невозможно обратиться к члену экземпляра класса из общего метода или общего инициализатора члена без явного указания экземпляра этого класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRbrace">
<source>'}' expected.</source>
<target state="translated">'Требуется "}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleAsType1">
<source>Module '{0}' cannot be used as a type.</source>
<target state="translated">Модуль "{0}" не может использоваться как тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnNonClass">
<source>'New' cannot be used on an interface.</source>
<target state="translated">'"New" не может использоваться для интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchAfterFinally">
<source>'Catch' cannot appear after 'Finally' within a 'Try' statement.</source>
<target state="translated">'В операторе "Try" ключевое слово "Catch" не может указываться после "Finally".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNoMatchingTry">
<source>'Catch' cannot appear outside a 'Try' statement.</source>
<target state="translated">'"Catch" не может использоваться вне оператора "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyAfterFinally">
<source>'Finally' can only appear once in a 'Try' statement.</source>
<target state="translated">'"Finally" в операторе "Try" может использоваться только один раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyNoMatchingTry">
<source>'Finally' cannot appear outside a 'Try' statement.</source>
<target state="translated">'"Finally" не может находиться за пределами оператора "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndTryNoTry">
<source>'End Try' must be preceded by a matching 'Try'.</source>
<target state="translated">'Оператору "End Try" должен предшествовать соответствующий оператор "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndTry">
<source>'Try' must end with a matching 'End Try'.</source>
<target state="translated">'Блок "Try" должен заканчиваться соответствующим "End Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDelegateFlags1">
<source>'{0}' is not valid on a Delegate declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как его базовый класс "{1}" не имеет доступного "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleSymbol2">
<source>'{0}' is not accessible in this context because it is '{1}'.</source>
<target state="translated">"{0}" в этом контексте недоступен, так как он является "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleMember3">
<source>'{0}.{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">"{0}.{1}" в этом контексте недоступен, так как он является "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNotException1">
<source>'Catch' cannot catch type '{0}' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.</source>
<target state="translated">'"Catch" не может перехватить тип "{0}", так как не является "System.Exception" или классом, наследующим от "System.Exception".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitTryNotWithinTry">
<source>'Exit Try' can only appear inside a 'Try' statement.</source>
<target state="translated">'"Exit Try" может использоваться только в теле оператора "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRecordFlags1">
<source>'{0}' is not valid on a Structure declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении Structure.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEnumFlags1">
<source>'{0}' is not valid on an Enum declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении перечисления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceFlags1">
<source>'{0}' is not valid on an Interface declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithByref2">
<source>'{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по параметру, который помечен как ByRef" относительно "ByVal".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyBaseAbstractCall1">
<source>'MyBase' cannot be used with method '{0}' because it is declared 'MustOverride'.</source>
<target state="translated">'"MyBase" не может использоваться с методом "{0}", объявленным как "MustOverride".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentNotMemberOfInterface4">
<source>'{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'.</source>
<target state="translated">"{0}" не может реализовать "{1}", поскольку нет соответствующего {2} в интерфейсе "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementingInterfaceWithDifferentTupleNames5">
<source>'{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'.</source>
<target state="translated">"{0}" не может реализовать {1} "{2}" в интерфейсе "{3}", так как имена элементов кортежа в "{4}" не соответствуют именам в "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsRequiresClass">
<source>'WithEvents' variables must have an 'As' clause.</source>
<target state="translated">'Объявления переменных с модификатором "WithEvents" должны иметь предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsAsStruct">
<source>'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.</source>
<target state="translated">'Типы переменных с модификатором "WithEvents" могут быть только классами, интерфейсами или параметрами типов с ограничениями классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayRankMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}' because the array types have different numbers of dimensions.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}", так как в типах массивов указано различное количество измерений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimRankMismatch">
<source>'ReDim' cannot change the number of dimensions of an array.</source>
<target state="translated">'"ReDim" не может изменять число измерений массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartupCodeNotFound1">
<source>'Sub Main' was not found in '{0}'.</source>
<target state="translated">'Не удалось найти "Sub Main" в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstAsNonConstant">
<source>Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.</source>
<target state="translated">Константы должны быть значениями встроенного типа или типа перечисления, а не классом, структурой, параметром-типом или массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSub">
<source>'End Sub' must be preceded by a matching 'Sub'.</source>
<target state="translated">'Оператору "End Sub" должен предшествовать соответствующий оператор "Sub".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndFunction">
<source>'End Function' must be preceded by a matching 'Function'.</source>
<target state="translated">'Оператору "End Function" должен предшествовать соответствующий оператор "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndProperty">
<source>'End Property' must be preceded by a matching 'Property'.</source>
<target state="translated">'Оператору "End Property" должен предшествовать соответствующий оператор "Property".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseMethodSpecifier1">
<source>Methods in a Module cannot be declared '{0}'.</source>
<target state="translated">Методы в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseEventSpecifier1">
<source>Events in a Module cannot be declared '{0}'.</source>
<target state="translated">События в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseVarSpecifier1">
<source>Members in a Structure cannot be declared '{0}'.</source>
<target state="translated">Члены в структуре не могут быть объявлены как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOverrideDueToReturn2">
<source>'{0}' cannot override '{1}' because they differ by their return types.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как их возвращаемые типы различны.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2">
<source>'{0}' cannot override '{1}' because they differ by their tuple element names.</source>
<target state="translated">"{0}" не может переопределять "{1}", так как они отличаются именами элементов кортежа.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2_Title">
<source>Member cannot override because it differs by its tuple element names.</source>
<target state="translated">Переопределение с помощью члена невозможно, так как его имена элементов кортежа отличаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantWithNoValue">
<source>Constants must have a value.</source>
<target state="translated">Константы должны иметь значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionOverflow1">
<source>Constant expression not representable in type '{0}'.</source>
<target state="translated">Константное выражение не может быть представлено как имеющее тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertyGet">
<source>'Get' is already declared.</source>
<target state="translated">'Процедура "Get" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertySet">
<source>'Set' is already declared.</source>
<target state="translated">'Процедура "Set" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotDeclared1">
<source>'{0}' is not declared. It may be inaccessible due to its protection level.</source>
<target state="translated">"{0}" не объявлена. Возможно, она недоступна из-за своего уровня защиты.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperands3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'.</source>
<target state="translated">Оператор "{0}" не определен для типов "{1}" и "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedProcedure">
<source>Expression is not a method.</source>
<target state="translated">Выражение не является методом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument2">
<source>Argument not specified for parameter '{0}' of '{1}'.</source>
<target state="translated">Аргумент, не указанный для параметра "{0}" метода "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMember2">
<source>'{0}' is not a member of '{1}'.</source>
<target state="translated">"{0}" не является членом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndClassNoClass">
<source>'End Class' must be preceded by a matching 'Class'.</source>
<target state="translated">'Оператору "End Class" должен предшествовать соответствующий оператор "Class".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadClassFlags1">
<source>Classes cannot be declared '{0}'.</source>
<target state="translated">Классы не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportsMustBeFirst">
<source>'Imports' statements must precede any declarations.</source>
<target state="translated">'Операторы "Imports" должны указываться до любых объявлений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonNamespaceOrClassOnImport2">
<source>'{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module.</source>
<target state="translated">"{1}" для Imports "{0}" не ссылается на Namespace, Class, Structure, Enum или Module.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNotallowed">
<source>Type declaration characters are not valid in this context.</source>
<target state="translated">Символы объявления типа недопустимы в этом контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectReferenceNotSupplied">
<source>Reference to a non-shared member requires an object reference.</source>
<target state="translated">Для ссылки на член, не используемый совместно, требуется ссылка на объект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassNotInClass">
<source>'MyClass' cannot be used outside of a class.</source>
<target state="translated">'"MyClass" не может использоваться вне класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndexedNotArrayOrProc">
<source>Expression is not an array or a method, and cannot have an argument list.</source>
<target state="translated">Выражение не является массивом или методом и не может иметь список аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventSourceIsArray">
<source>'WithEvents' variables cannot be typed as arrays.</source>
<target state="translated">'Переменные с модификатором "WithEvents" не могут являться массивами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorWithParams">
<source>Shared 'Sub New' cannot have any parameters.</source>
<target state="translated">Общий конструктор "Sub New" не может иметь параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorIllegalSpec1">
<source>Shared 'Sub New' cannot be declared '{0}'.</source>
<target state="translated">Невозможно объявить общий "Sub New" как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndClass">
<source>'Class' statement must end with a matching 'End Class'.</source>
<target state="translated">'Блок Class должен заканчиваться соответствующим оператором End Class.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryOperand2">
<source>Operator '{0}' is not defined for type '{1}'.</source>
<target state="translated">Оператор "{0}" не определен для типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsWithDefault1">
<source>'Default' cannot be combined with '{0}'.</source>
<target state="translated">'"Default" не может использоваться вместе с "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidValue">
<source>Expression does not produce a value.</source>
<target state="translated">Выражение не порождает значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorFunction">
<source>Constructor must be declared as a Sub, not as a Function.</source>
<target state="translated">Конструктор должен объявляться как подпрограмма (Sub), а не как функция (Function).</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLiteralExponent">
<source>Exponent is not valid.</source>
<target state="translated">Показатель степени является недопустимым.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewCannotHandleEvents">
<source>'Sub New' cannot handle events.</source>
<target state="translated">'Конструктор "Sub New" не может обрабатывать события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularEvaluation1">
<source>Constant '{0}' cannot depend on its own value.</source>
<target state="translated">Константа "{0}" не может зависеть от своего собственного значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedMeth1">
<source>'Shared' cannot be combined with '{0}' on a method declaration.</source>
<target state="translated">'"Shared" не может использоваться вместе с "{0}" в объявлении метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedProperty1">
<source>'Shared' cannot be combined with '{0}' on a property declaration.</source>
<target state="translated">'"Shared" не может использоваться вместе с "{0}" в объявлении свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnStdModuleProperty1">
<source>Properties in a Module cannot be declared '{0}'.</source>
<target state="translated">Свойства в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedOnProcThatImpl">
<source>Methods or events that implement interface members cannot be declared 'Shared'.</source>
<target state="translated">Методы или события, которые реализуют члены интерфейса, не могут объявляться как "Shared".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoWithEventsVarOnHandlesList">
<source>Handles clause requires a WithEvents variable defined in the containing type or one of its base types.</source>
<target state="translated">Для предложения Handles требуется переменная с модификатором WithEvents, определенная во вмещающем типе или в одном из его базовых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatch5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} до {3} "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionDisallowed2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'.</source>
<target state="translated">Option Strict On не разрешает неявные преобразования "{0}" к "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoArgumentCountOverloadCandidates1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of arguments.</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступного "{0}", который принимает такое число аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoViableOverloadCandidates1">
<source>Overload resolution failed because no '{0}' is accessible.</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступа к "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoCallableOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called with these arguments:{1}</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как отсутствует доступный "{0}", который можно вызвать с этими аргументами: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called:{1}</source>
<target state="translated">Сбой при разрешении перегрузки, поскольку ни один из доступных "{0}" не может быть вызван:{1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonNarrowingOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called without a narrowing conversion:{1}</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступных "{0}", которые можно вызвать без сужающего преобразования:{1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing3">
<source>Argument matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">Аргумент, соответствующий параметру "{0}", сужен с "{1}" до "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoMostSpecificOverload2">
<source>Overload resolution failed because no accessible '{0}' is most specific for these arguments:{1}</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступного "{0}", который бы являлся наиболее конкретным для этих аргументов: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotMostSpecificOverload">
<source>Not most specific.</source>
<target state="translated">Не является наиболее подходящим.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate2">
<source>
'{0}': {1}</source>
<target state="translated">
"{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGetProperty1">
<source>Property '{0}' is 'WriteOnly'.</source>
<target state="translated">Свойство "{0}" помечено как "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSetProperty1">
<source>Property '{0}' is 'ReadOnly'.</source>
<target state="translated">Свойство "{0}" помечено как "ReadOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamTypingInconsistency">
<source>All parameters must be explicitly typed if any of them are explicitly typed.</source>
<target state="translated">Типы всех параметров должны быть указаны явно, если хотя бы один тип указан явно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamNameFunctionNameCollision">
<source>Parameter cannot have the same name as its defining function.</source>
<target state="translated">Параметр не может иметь имя, совпадающее с именем определяющей его функции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DateToDoubleConversion">
<source>Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method.</source>
<target state="translated">Для преобразования из типа Date в Double требуется вызов метода Date.ToOADate.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoubleToDateConversion">
<source>Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method.</source>
<target state="translated">Для преобразования из типа Date в Double требуется вызов метода Date.FromOADate.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ZeroDivide">
<source>Division by zero occurred while evaluating this expression.</source>
<target state="translated">При вычислении этого выражения произошло деление на нуль.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryAndOnErrorDoNotMix">
<source>Method cannot contain both a 'Try' statement and an 'On Error' or 'Resume' statement.</source>
<target state="translated">Метод не может одновременно содержать оператор "Try" и оператор "On Error" или "Resume".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyAccessIgnored">
<source>Property access must assign to the property or use its value.</source>
<target state="translated">Доступ к свойству должен выполняться для присваивания или считывания его значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNoDefault1">
<source>'{0}' cannot be indexed because it has no default property.</source>
<target state="translated">"{0}" невозможно индексировать, поскольку он не содержит свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyAttribute1">
<source>Attribute '{0}' cannot be applied to an assembly.</source>
<target state="translated">Атрибут "{0}" невозможно применить к сборке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidModuleAttribute1">
<source>Attribute '{0}' cannot be applied to a module.</source>
<target state="translated">Атрибут "{0}" невозможно применить к модулю.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInUnnamedNamespace1">
<source>'{0}' is ambiguous.</source>
<target state="translated">"{0}" неоднозначен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMemberNotProperty1">
<source>Default member of '{0}' is not a property.</source>
<target state="translated">Член по умолчанию "{0}" не является свойством.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespace2">
<source>'{0}' is ambiguous in the namespace '{1}'.</source>
<target state="translated">"{0}" неоднозначен в пространстве имен "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInImports2">
<source>'{0}' is ambiguous, imported from the namespaces or types '{1}'.</source>
<target state="translated">"{0}", импортированный из пространств имен или типов "{1}", является неоднозначным.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInModules2">
<source>'{0}' is ambiguous between declarations in Modules '{1}'.</source>
<target state="translated">"{0}" неоднозначен для объявлений в модулях "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespaces2">
<source>'{0}' is ambiguous between declarations in namespaces '{1}'.</source>
<target state="translated">"{0}" неоднозначен для объявлений в пространствах имен "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooFewDimensions">
<source>Array initializer has too few dimensions.</source>
<target state="translated">Недостаточное число измерений инициализатора массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooManyDimensions">
<source>Array initializer has too many dimensions.</source>
<target state="translated">Чрезмерное число измерений инициализатора массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooFewElements1">
<source>Array initializer is missing {0} elements.</source>
<target state="translated">Количество отсутствующих элементов в инициализаторе массива: {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooManyElements1">
<source>Array initializer has {0} too many elements.</source>
<target state="translated">В инициализаторе массива слишком много элементов {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewOnAbstractClass">
<source>'New' cannot be used on a class that is declared 'MustInherit'.</source>
<target state="translated">'"New" не может использоваться для класса, объявленного как "MustInherit".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateNamedImportAlias1">
<source>Alias '{0}' is already declared.</source>
<target state="translated">Псевдоним "{0}" уже объявлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePrefix">
<source>XML namespace prefix '{0}' is already declared.</source>
<target state="translated">Префикс пространства имен XML "{0}" уже объявлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsLateBinding">
<source>Option Strict On disallows late binding.</source>
<target state="translated">Оператор "Option Strict On" не разрешает позднее связывание.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfOperandNotMethod">
<source>'AddressOf' operand must be the name of a method (without parentheses).</source>
<target state="translated">'Операндом "AddressOf" должно быть имя метода; круглые скобки не требуются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndExternalSource">
<source>'#End ExternalSource' must be preceded by a matching '#ExternalSource'.</source>
<target state="translated">'Оператору "#End ExternalSource" должен предшествовать соответствующий оператор "#ExternalSource".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndExternalSource">
<source>'#ExternalSource' statement must end with a matching '#End ExternalSource'.</source>
<target state="translated">'Оператор "#ExternalSource" должен заканчиваться соответствующим оператором "#End ExternalSource".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedExternalSource">
<source>'#ExternalSource' directives cannot be nested.</source>
<target state="translated">'Директивы "#ExternalSource" не могут быть вложенными.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">'Выражение "AddressOf" нельзя преобразовать в "{0}", поскольку "{0}" не является типом делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyncLockRequiresReferenceType1">
<source>'SyncLock' operand cannot be of type '{0}' because '{0}' is not a reference type.</source>
<target state="translated">'Операнд "SyncLock" не может быть типа "{0}", так как "{0}" не является ссылочным типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodAlreadyImplemented2">
<source>'{0}.{1}' cannot be implemented more than once.</source>
<target state="translated">"{0}.{1}" невозможно реализовать более одного раза.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateInInherits1">
<source>'{0}' cannot be inherited more than once.</source>
<target state="translated">"{0}" не может наследоваться несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamArrayArgument">
<source>Named argument cannot match a ParamArray parameter.</source>
<target state="translated">Именованный аргумент не должен соответствовать параметру ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedParamArrayArgument">
<source>Omitted argument cannot match a ParamArray parameter.</source>
<target state="translated">Пропущенный аргумент не может соответствовать параметру ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayArgumentMismatch">
<source>Argument cannot match a ParamArray parameter.</source>
<target state="translated">Аргумент не может соответствовать параметру ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNotFound1">
<source>Event '{0}' cannot be found.</source>
<target state="translated">Не удается найти событие "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseVariableSpecifier1">
<source>Variables in Modules cannot be declared '{0}'.</source>
<target state="translated">Переменные в модулях не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsSharedHandler">
<source>Events of shared WithEvents variables cannot be handled by non-shared methods.</source>
<target state="translated">События из общих переменных "WithEvents" не могут обрабатываться методами, не являющимися общими.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedMinus">
<source>'-' expected.</source>
<target state="translated">'Требуется "-".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceMemberSyntax">
<source>Interface members must be methods, properties, events, or type definitions.</source>
<target state="translated">Членами интерфейса могут быть только методы, свойства, события и определения типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideInterface">
<source>Statement cannot appear within an interface body.</source>
<target state="translated">Оператор не может присутствовать в теле интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsInterface">
<source>Statement cannot appear within an interface body. End of interface assumed.</source>
<target state="translated">Оператор не может присутствовать в теле интерфейса. Предполагается конец интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsInNotInheritableClass1">
<source>'NotInheritable' classes cannot have members declared '{0}'.</source>
<target state="translated">'Классы "NotInheritable" не могут содержать членов, объявленных как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseOnlyClassesMustBeExplicit2">
<source>Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}.</source>
<target state="translated">Класс "{0}" должен либо быть объявлен как "MustInherit", либо переопределять следующие члены, помеченные как "MustOverride": {1}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritEventNotOverridden">
<source>'{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit.</source>
<target state="translated">"{0}" является событием MustOverride в базовом классе "{1}". Visual Basic не поддерживает переопределение событий. Необходимо предоставить реализацию события в базовом классе или задать для класса "{2}" значение MustInherit.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NegativeArraySize">
<source>Array dimensions cannot have a negative size.</source>
<target state="translated">Размерности массива не могут иметь отрицательные значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassAbstractCall1">
<source>'MustOverride' method '{0}' cannot be called with 'MyClass'.</source>
<target state="translated">'Метод "{0}", помеченный как "MustOverride", не может вызываться с помощью "MyClass".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndDisallowedInDllProjects">
<source>'End' statement cannot be used in class library projects.</source>
<target state="translated">'Оператор "End" не может использоваться в проектах библиотек классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BlockLocalShadowing1">
<source>Variable '{0}' hides a variable in an enclosing block.</source>
<target state="translated">Переменная "{0}" скрывает переменную во внешнем блоке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleNotAtNamespace">
<source>'Module' statements can occur only at file or namespace level.</source>
<target state="translated">'Операторы "Module" могут использоваться только на уровне файлов и пространств имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAtNamespace">
<source>'Namespace' statements can occur only at file or namespace level.</source>
<target state="translated">'Операторы "Namespace" могут использоваться только на уровне файлов и пространств имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEnum">
<source>Statement cannot appear within an Enum body.</source>
<target state="translated">Оператор не может присутствовать в теле перечисления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEnum">
<source>Statement cannot appear within an Enum body. End of Enum assumed.</source>
<target state="translated">Оператор не может присутствовать в теле перечисления. Предполагается, что перечисление завершено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrict">
<source>'Option Strict' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'За "Option Strict" может следовать только "On" или "Off".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndStructureNoStructure">
<source>'End Structure' must be preceded by a matching 'Structure'.</source>
<target state="translated">'Оператору "End Structure" должен предшествовать соответствующий оператор "Structure".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndModuleNoModule">
<source>'End Module' must be preceded by a matching 'Module'.</source>
<target state="translated">'Оператору "End Module" должен предшествовать соответствующий оператор "Module".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndNamespaceNoNamespace">
<source>'End Namespace' must be preceded by a matching 'Namespace'.</source>
<target state="translated">'Оператору "End Namespace" должен предшествовать соответствующий оператор "Namespace".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndStructure">
<source>'Structure' statement must end with a matching 'End Structure'.</source>
<target state="translated">'Оператор "Structure" должен заканчиваться соответствующим оператором "End Structure".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndModule">
<source>'Module' statement must end with a matching 'End Module'.</source>
<target state="translated">'Оператор "Module" должен заканчиваться соответствующим оператором "End Module".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndNamespace">
<source>'Namespace' statement must end with a matching 'End Namespace'.</source>
<target state="translated">'Оператор "Namespace" должен заканчиваться соответствующим оператором "End Namespace".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionStmtWrongOrder">
<source>'Option' statements must precede any declarations or 'Imports' statements.</source>
<target state="translated">'Оператор "Option" должен находиться перед любыми объявлениями или операторами "Imports".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantInherit">
<source>Structures cannot have 'Inherits' statements.</source>
<target state="translated">Структуры не могут содержать операторов "Inherits".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInStruct">
<source>Structures cannot declare a non-shared 'Sub New' with no parameters.</source>
<target state="translated">Структуры не могут объявлять неразделяемый конструктор "Sub New" при отсутствии параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndGet">
<source>'End Get' must be preceded by a matching 'Get'.</source>
<target state="translated">'Оператору "End Get" должен предшествовать соответствующий оператор "Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndGet">
<source>'Get' statement must end with a matching 'End Get'.</source>
<target state="translated">'Оператор "Get" должен заканчиваться соответствующим оператором "End Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSet">
<source>'End Set' must be preceded by a matching 'Set'.</source>
<target state="translated">'Оператору "End Set" должен предшествовать соответствующий оператор "Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndSet">
<source>'Set' statement must end with a matching 'End Set'.</source>
<target state="translated">'Оператор "Set" должен заканчиваться соответствующим оператором "End Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProperty">
<source>Statement cannot appear within a property body. End of property assumed.</source>
<target state="translated">Оператор не может присутствовать в теле свойства. Предполагается, что свойство завершено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateWriteabilityCategoryUsed">
<source>'ReadOnly' and 'WriteOnly' cannot be combined.</source>
<target state="translated">'"ReadOnly" и "WriteOnly" не могут использоваться вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedGreater">
<source>'>' expected.</source>
<target state="translated">'Требуется ">".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeStmtWrongOrder">
<source>Assembly or Module attribute statements must precede any declarations in a file.</source>
<target state="translated">Операторы атрибута сборки или модуля в файле должны указываться до объявлений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoExplicitArraySizes">
<source>Array bounds cannot appear in type specifiers.</source>
<target state="translated">Границы массивов не могут присутствовать в спецификаторах типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyFlags1">
<source>Properties cannot be declared '{0}'.</source>
<target state="translated">Свойства не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionExplicit">
<source>'Option Explicit' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'За "Option Explicit" может следовать только "On" или "Off".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleParameterSpecifiers">
<source>'ByVal' and 'ByRef' cannot be combined.</source>
<target state="translated">'"ByVal" и "ByRef" не могут использоваться вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleOptionalParameterSpecifiers">
<source>'Optional' and 'ParamArray' cannot be combined.</source>
<target state="translated">'"Optional" и "ParamArray" не могут использоваться вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedProperty1">
<source>Property '{0}' is of an unsupported type.</source>
<target state="translated">Свойство "{0}" относится к неподдерживаемому типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionalParameterUsage1">
<source>Attribute '{0}' cannot be applied to a method with optional parameters.</source>
<target state="translated">Атрибут "{0}" не может использоваться для метода с необязательными параметрами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonFunction">
<source>'Return' statement in a Sub or a Set cannot return a value.</source>
<target state="translated">'Оператор "Return" в "Sub" или "Set" не может возвращать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnterminatedStringLiteral">
<source>String constants must end with a double quote.</source>
<target state="translated">Строковые константы должны завершаться двойной кавычкой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedType1">
<source>'{0}' is an unsupported type.</source>
<target state="translated">"{0}" является неподдерживаемым типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEnumBase">
<source>Enums must be declared as an integral type.</source>
<target state="translated">Перечисления должны объявляться как целочисленный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefIllegal1">
<source>{0} parameters cannot be declared 'ByRef'.</source>
<target state="translated">параметры {0} не могут быть объявлены как "ByRef".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssembly3">
<source>Reference required to assembly '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется сборка, содержащая тип "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModule3">
<source>Reference required to module '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется ссылка, содержащая тип "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnWithoutValue">
<source>'Return' statement in a Function, Get, or Operator must return a value.</source>
<target state="translated">'Оператор "Return" в Function, Get или Operator должен возвращать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedField1">
<source>Field '{0}' is of an unsupported type.</source>
<target state="translated">Поле "{0}" относится к неподдерживаемому типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedMethod1">
<source>'{0}' has a return type that is not supported or parameter types that are not supported.</source>
<target state="translated">"{0}" имеет возвращаемый тип или типы параметров, которые не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonIndexProperty1">
<source>Property '{0}' with no parameters cannot be found.</source>
<target state="translated">Не удается найти свойство "{0}" без параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributePropertyType1">
<source>Property or field '{0}' does not have a valid attribute type.</source>
<target state="translated">Свойство или поле "{0}" не имеет атрибута допустимого типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalsCannotHaveAttributes">
<source>Attributes cannot be applied to local variables.</source>
<target state="translated">Атрибуты не могут использоваться для локальных переменных.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyOrFieldNotDefined1">
<source>Field or property '{0}' is not found.</source>
<target state="translated">Не найдено поле или свойство "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsage2">
<source>Attribute '{0}' cannot be applied to '{1}' because the attribute is not valid on this declaration type.</source>
<target state="translated">Атрибут "{0}" не может использоваться для "{1}", поскольку данный атрибут не допускается для этого типа объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsageOnAccessor">
<source>Attribute '{0}' cannot be applied to '{1}' of '{2}' because the attribute is not valid on this declaration type.</source>
<target state="translated">Атрибут "{0}" не может использоваться для "{1}" из "{2}", поскольку данный атрибут не допускается для этого типа объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedTypeInInheritsClause2">
<source>Class '{0}' cannot reference its nested type '{1}' in Inherits clause.</source>
<target state="translated">Класс "{0}" не может ссылаться на вложенный тип "{1}" в предложении Inherits.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInItsInheritsClause1">
<source>Class '{0}' cannot reference itself in Inherits clause.</source>
<target state="translated">Класс "{0}" не может ссылаться на себя в предложении Inherits.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseTypeReferences2">
<source>
Base type of '{0}' needs '{1}' to be resolved.</source>
<target state="translated">
Базовому типу "{0}" требуется, чтобы "{1}" был разрешен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalBaseTypeReferences3">
<source>Inherits clause of {0} '{1}' causes cyclic dependency: {2}</source>
<target state="translated">Наследует предложение {0} "{1}", вызывающее циклическую зависимость: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsage1">
<source>Attribute '{0}' cannot be applied multiple times.</source>
<target state="translated">Атрибут "{0}" не может использоваться несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsageInNetModule2">
<source>Attribute '{0}' in '{1}' cannot be applied multiple times.</source>
<target state="translated">Атрибут "{0}" в "{1}" не может использоваться несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantThrowNonException">
<source>'Throw' operand must derive from 'System.Exception'.</source>
<target state="translated">'Операнд оператора "Throw" должен быть производным от "System.Exception".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeInCatchToRethrow">
<source>'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.</source>
<target state="translated">'В операторе "Throw" запрещается пропускать операнд вне оператора "Catch" или в теле оператора "Finally".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeByVal">
<source>ParamArray parameters must be declared 'ByVal'.</source>
<target state="translated">Параметры типа ParamArray должны объявляться как "ByVal".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">"{0}" является устаревшим: "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimNoSizes">
<source>'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.</source>
<target state="translated">В операторе "ReDim" требуется задать в круглых скобках список новых границ для каждого измерения массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithMultipleDeclarators">
<source>Explicit initialization is not permitted with multiple variables declared with a single type specifier.</source>
<target state="translated">Для нескольких переменных, объявленных с одним спецификатором типа, явная инициализация не разрешена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithExplicitArraySizes">
<source>Explicit initialization is not permitted for arrays declared with explicit bounds.</source>
<target state="translated">Явная инициализация массивов, объявленных с границами явно, запрещена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSyncLockNoSyncLock">
<source>'End SyncLock' must be preceded by a matching 'SyncLock'.</source>
<target state="translated">'Оператору "End SyncLock" должен предшествовать соответствующий оператор "SyncLock".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSyncLock">
<source>'SyncLock' statement must end with a matching 'End SyncLock'.</source>
<target state="translated">'Оператор "SyncLock" должен заканчиваться соответствующим оператором "End SyncLock".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotEvent2">
<source>'{0}' is not an event of '{1}'.</source>
<target state="translated">"{0}" не является событием "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddOrRemoveHandlerEvent">
<source>'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.</source>
<target state="translated">'Операндом события оператора "AddHandler" или "RemoveHandler" должно быть выражение с точкой или простое имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedEnd">
<source>'End' statement not valid.</source>
<target state="translated">'Недопустимый оператор "End".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitForNonArray2">
<source>Array initializers are valid only for arrays, but the type of '{0}' is '{1}'.</source>
<target state="translated">Инициализаторы массивов допустимы только для массивов, а "{0}" имеет тип "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndRegionNoRegion">
<source>'#End Region' must be preceded by a matching '#Region'.</source>
<target state="translated">'Оператору "#End Region" должен предшествовать соответствующий оператор "#Region".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndRegion">
<source>'#Region' statement must end with a matching '#End Region'.</source>
<target state="translated">'Оператор "#Region" должен заканчиваться соответствующим оператором "#End Region".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsStmtWrongOrder">
<source>'Inherits' statement must precede all declarations in a class.</source>
<target state="translated">'Оператор "Inherits" должен предшествовать всем объявлениям в классе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousAcrossInterfaces3">
<source>'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'.</source>
<target state="translated">'"Неоднозначность: "{0}" относится к наследуемым интерфейсам "{1}" и "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyAmbiguousAcrossInterfaces4">
<source>Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'.</source>
<target state="translated">Неоднозначность при доступе к свойству по умолчанию между членами "{0}" наследуемого интерфейса "{1}" и "{2}" интерфейса "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceEventCantUse1">
<source>Events in interfaces cannot be declared '{0}'.</source>
<target state="translated">События в интерфейсах не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExecutableAsDeclaration">
<source>Statement cannot appear outside of a method body.</source>
<target state="translated">Оператор не может находиться вне тела метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNoDefault1">
<source>Structure '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">Структуру "{0}" нельзя проиндексировать, так как не имеет свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustShadow2">
<source>{0} '{1}' must be declared 'Shadows' because another member with this name is declared 'Shadows'.</source>
<target state="translated">{0} "{1}" должна быть объявлена как "Shadows", потому что другой член с таким именем объявлен как "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptionalTypes2">
<source>'{0}' cannot override '{1}' because they differ by the types of optional parameters.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по типам необязательных параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndOfExpression">
<source>End of expression expected.</source>
<target state="translated">Ожидался конец выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructsCannotHandleEvents">
<source>Methods declared in structures cannot have 'Handles' clauses.</source>
<target state="translated">Методы, объявляемые в структурах, не могут содержать предложения "Handles".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridesImpliesOverridable">
<source>Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.</source>
<target state="translated">Методы, объявленные оператором "Overrides", не могут объявляться как "Overridable", поскольку возможность их переопределения подразумевается неявно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParam1">
<source>'{0}' is already declared as a parameter of this method.</source>
<target state="translated">"{0}" уже объявлена как параметр этого метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParamInLambda1">
<source>Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression.</source>
<target state="translated">Переменная "{0}" уже объявлена как параметр этого или внешнего лямбда-выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseTypeSpecifier1">
<source>Type in a Module cannot be declared '{0}'.</source>
<target state="translated">Тип в модуле не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InValidSubMainsFound1">
<source>No accessible 'Main' method with an appropriate signature was found in '{0}'.</source>
<target state="translated">В "{0}" не найдено доступного метода "Main" с подходящей сигнатурой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MoreThanOneValidMainWasFound2">
<source>'Sub Main' is declared more than once in '{0}': {1}</source>
<target state="translated">'"Sub Main" объявлен в "{0}" более одного раза: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotConvertValue2">
<source>Value '{0}' cannot be converted to '{1}'.</source>
<target state="translated">Значение "{0}" нельзя преобразовать в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInSyncLock">
<source>'On Error' statements are not valid within 'SyncLock' statements.</source>
<target state="translated">'Операторы "On Error" в теле оператора "SyncLock" недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionCollection2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type.</source>
<target state="translated">Option Strict On не разрешает неявные преобразования "{0}" к "{1}"; тип коллекции Visual Basic 6.0 несовместим с типом коллекции .NET Framework.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoTryHandler">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "Try", "Catch" или "Finally", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoSyncLock">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'SyncLock' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "SyncLock", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoWith">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'With' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "With", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoFor">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'For' or 'For Each' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора ''For" или "For Each", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicConstructor">
<source>Attribute cannot be used because it does not have a Public constructor.</source>
<target state="translated">Использование атрибута невозможно, так как для него отсутствует открытый конструктор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultEventNotFound1">
<source>Event '{0}' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.</source>
<target state="translated">Событие "{0}" с атрибутом "DefaultEvent" не является общедоступным для данного класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNonSerializedUsage">
<source>'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.</source>
<target state="translated">'Атрибут "NonSerialized" не затронет данный член, поскольку класс, содержащий его, не предоставлен как "Serializable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedContinueKind">
<source>'Continue' must be followed by 'Do', 'For' or 'While'.</source>
<target state="translated">'После "Continue" должны следовать "Do", "For" или "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueDoNotWithinDo">
<source>'Continue Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'"Continue Do" может присутствовать только в операторе "Do".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueForNotWithinFor">
<source>'Continue For' can only appear inside a 'For' statement.</source>
<target state="translated">'"Continue For" может присутствовать только в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueWhileNotWithinWhile">
<source>'Continue While' can only appear inside a 'While' statement.</source>
<target state="translated">'"Continue While" может присутствовать только в операторе "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParameterSpecifier">
<source>Parameter specifier is duplicated.</source>
<target state="translated">Спецификатор параметра встречается второй раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a Module cannot be declared '{0}'.</source>
<target state="translated">'Операторы "Declare" в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a structure cannot be declared '{0}'.</source>
<target state="translated">'Операторы "Declare" в структуре не могут быть объявлены как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfValueType1">
<source>'TryCast' operand must be reference type, but '{0}' is a value type.</source>
<target state="translated">'Операнд "TryCast" должен быть ссылочного типа, а "{0}" является типом значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfUnconstrainedTypeParam1">
<source>'TryCast' operands must be class-constrained type parameter, but '{0}' has no class constraint.</source>
<target state="translated">'Операнды "TryCast" должны быть параметром типа с ограничением класса, а "{0}" не имеет ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousDelegateBinding2">
<source>No accessible '{0}' is most specific: {1}</source>
<target state="translated">Отсутствие доступного "{0}" является наиболее характерным: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedStructMemberCannotSpecifyNew">
<source>Non-shared members in a Structure cannot be declared 'New'.</source>
<target state="translated">Члены структуры, не являющиеся общими, не могут быть объявлены как "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericSubMainsFound1">
<source>None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types.</source>
<target state="translated">Ни один из доступных методов "Main" с подходящими подписями в "{0}" не может быть стартовым методом, поскольку они все либо универсального типа, либо вложены в универсальный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GeneralProjectImportsError3">
<source>Error in project-level import '{0}' at '{1}' : {2}</source>
<target state="translated">Ошибка импорта на уровне проекта "{0}" в "{1}": {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidTypeForAliasesImport2">
<source>'{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.</source>
<target state="translated">"{1}" псевдонима Imports для "{0}" не ссылается на Namespace, Class, Structure, Interface, Enum или Module.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedConstant2">
<source>Field '{0}.{1}' has an invalid constant value.</source>
<target state="translated">Поле "{0}.{1}" имеет недопустимое константное значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteArgumentsNeedParens">
<source>Method arguments must be enclosed in parentheses.</source>
<target state="translated">Аргументы метода должны быть заключены в круглые скобки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLineNumbersAreLabels">
<source>Labels that are numbers must be followed by colons.</source>
<target state="translated">После числовых меток следует ставить двоеточие.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteStructureNotType">
<source>'Type' statements are no longer supported; use 'Structure' statements instead.</source>
<target state="translated">'Операторы "Type" больше не поддерживаются; используйте операторы "Structure".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteObjectNotVariant">
<source>'Variant' is no longer a supported type; use the 'Object' type instead.</source>
<target state="translated">'Тип "Variant" больше не поддерживается; используйте тип "Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLetSetNotNeeded">
<source>'Let' and 'Set' assignment statements are no longer supported.</source>
<target state="translated">'Операторы назначения "Let" и "Set" больше не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoletePropertyGetLetSet">
<source>Property Get/Let/Set are no longer supported; use the new Property declaration syntax.</source>
<target state="translated">Операторы "Property Get/Let/Set" больше не поддерживаются; используйте новый синтаксис объявления свойств.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteWhileWend">
<source>'Wend' statements are no longer supported; use 'End While' statements instead.</source>
<target state="translated">'Операторы "Wend" больше не поддерживаются; используйте операторы "End While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteRedimAs">
<source>'ReDim' statements can no longer be used to declare array variables.</source>
<target state="translated">'Операторы "ReDim" больше не используются при объявлении переменных-массивов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOptionalWithoutValue">
<source>Optional parameters must specify a default value.</source>
<target state="translated">Для необязательных параметров должны быть заданы значения по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGosub">
<source>'GoSub' statements are no longer supported.</source>
<target state="translated">'Операторы "GoSub" больше не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOnGotoGosub">
<source>'On GoTo' and 'On GoSub' statements are no longer supported.</source>
<target state="translated">'Операторы "On GoTo" и "On GoSub" больше не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteEndIf">
<source>'EndIf' statements are no longer supported; use 'End If' instead.</source>
<target state="translated">'Операторы "EndIf" больше не поддерживаются; используйте "End If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteExponent">
<source>'D' can no longer be used to indicate an exponent, use 'E' instead.</source>
<target state="translated">'"D" больше не может использоваться для обозначения показателя степени; используйте "E".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteAsAny">
<source>'As Any' is not supported in 'Declare' statements.</source>
<target state="translated">'"As Any" в операторах "Declare" не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGetStatement">
<source>'Get' statements are no longer supported. File I/O functionality is available in the 'Microsoft.VisualBasic' namespace.</source>
<target state="translated">'Операторы "Get" больше не поддерживаются. Возможности ввода/вывода файлов доступны в пространстве имен Microsoft.VisualBasic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithArrayVsParamArray2">
<source>'{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по параметрам, объявленным как "ParamArray".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularBaseDependencies4">
<source>This inheritance causes circular dependencies between {0} '{1}' and its nested or base type '{2}'.</source>
<target state="translated">Данное наследование приводит к циклической зависимости между {0} "{1}" и вложенным в него или базовым типом "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedBase2">
<source>{0} '{1}' cannot inherit from a type nested within it.</source>
<target state="translated">{0} "{1}" не может наследовать из вложенного в него типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchOutsideAssembly4">
<source>'{0}' cannot expose type '{1}' outside the project through {2} '{3}'.</source>
<target state="translated">"{0}" не может представлять тип "{1}" вне проекта посредством {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatchOutside3">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} за пределы сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело: '{2}'.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent6">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'.</source>
<target state="translated">"{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует в {2} "{3}" посредством {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent4">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'.</source>
<target state="translated">"{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует вне проекта посредством {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycleInImportedType1">
<source>Type '{0}' is not supported because it either directly or indirectly inherits from itself.</source>
<target state="translated">Тип "{0}" не поддерживается, поскольку он прямо или косвенно наследует от себя самого.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший: "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший: "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatch7">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" до {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatchOutside5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" за пределы данной сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeAccessMismatch3">
<source>Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types.</source>
<target state="translated">Указанный доступ "{0}" для "{1}" не соответствует доступу "{2}", указанному для одного из других разделяемых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeBadMustInherit1">
<source>'MustInherit' cannot be specified for partial type '{0}' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.</source>
<target state="translated">'"MustInherit" не может быть указан для разделяемого типа "{0}", так как не может быть объединен с "NotInheritable", указанным для одного из других разделяемых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverOnNotInheritPartClsMem1">
<source>'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.</source>
<target state="translated">'Невозможно определить "MustOverride" для этого члена, поскольку он находится в разделяемом типе, объявленном как "NotInheritable" в другом частичном определении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseMismatchForPartialClass3">
<source>Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types.</source>
<target state="translated">Базовый класс "{0}", указанный для класса "{1}", не может отличаться от базового класса "{2}" для одного из его других разделяемых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeTypeParamNameMismatch3">
<source>Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'.</source>
<target state="translated">Имя параметра типа "{0}" не соответствует имени "{1}" параметра соответствующего типа, определенного на одном из других разделяемых типов "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeConstraintMismatch1">
<source>Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'.</source>
<target state="translated">Ограничения для этого параметра типа не соответствуют ограничениям для соответствующего типа параметра, определенного на одном из других разделяемых типов "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LateBoundOverloadInterfaceCall1">
<source>Late bound overload resolution cannot be applied to '{0}' because the accessing instance is an interface type.</source>
<target state="translated">Разрешение перегрузки позднего связывания нельзя применить к "{0}", поскольку экземпляр, к которому осуществляется доступ, является типом интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredAttributeConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression used as an argument to an attribute.</source>
<target state="translated">Преобразование "{0}" в "{1}" не может происходить в константном выражении, используемом в качестве аргумента атрибута.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousOverrides3">
<source>Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2}</source>
<target state="translated">Член "{0}", соответствующий данной сигнатуре, не может быть переопределен, поскольку класс "{1}" содержит несколько членов с таким же именем и сигнатурой: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverriddenCandidate1">
<source>
'{0}'</source>
<target state="translated">
"{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplements3">
<source>Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature:
'{3}'
'{4}'</source>
<target state="translated">Член "{0}.{1}", соответствующий данной сигнатуре, не может быть реализован, поскольку интерфейс "{2}" содержит несколько членов с таким же именем и сигнатурой:
"{3}"
"{4}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotCreatableDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">'Выражение "AddressOf" нельзя преобразовать в "{0}", поскольку тип "{0}" объявлен как "MustInherit" и не может быть создан.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassGenericMethod">
<source>Generic methods cannot be exposed to COM.</source>
<target state="translated">Обобщенные методы не могут быть предоставлены в COM.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntaxInCastOp">
<source>Syntax error in cast operator; two arguments separated by comma are required.</source>
<target state="translated">Синтаксическая ошибка в операторе приведения; требуются два аргумента, разделенные запятой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerForNonConstDim">
<source>Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'.</source>
<target state="translated">Инициализатор массива не может быть задан для переменной размерности; используйте пустой инициализатор "{}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingFailure3">
<source>No accessible method '{0}' has a signature compatible with delegate '{1}':{2}</source>
<target state="translated">Нет доступного метода "{0}" с сигнатурой, совместимой с делегатом "{1}": {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructLayoutAttributeNotAllowed">
<source>Attribute 'StructLayout' cannot be applied to a generic type.</source>
<target state="translated">Атрибут "StructLayout" нельзя применять к универсальному типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal1">
<source>Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression.</source>
<target state="translated">Переменная диапазона "{0}" скрывает переменную во внешнем блоке или ранее определенную переменную в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionInfer">
<source>'Option Infer' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'За "Option Infer" может следовать только "On" или "Off".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularInference1">
<source>Type of '{0}' cannot be inferred from an expression containing '{0}'.</source>
<target state="translated">Не удается получить тип "{0}" из выражения, содержащего "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleOverridingMethod5">
<source>'{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible.</source>
<target state="translated">"{0}" в классе "{1}" не может переопределять "{2}" в классе "{3}", поскольку недоступен промежуточный класс "{4}", переопределяющий "{2}" в классе "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableWidestType1">
<source>Type of '{0}' cannot be inferred because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">Невозможно получить тип "{0}", так как границы цикла и выражение шага не преобразуют в тот же тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousWidestType3">
<source>Type of '{0}' is ambiguous because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">Тип "{0}" неоднозначен, так как привязки цикла и выражение шага не преобразуются в один тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperatorInInit">
<source>'=' expected (object initializer).</source>
<target state="translated">'Ожидается "=" (инициализатор объекта).</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQualifiedNameInInit">
<source>Name of field or property being initialized in an object initializer must start with '.'.</source>
<target state="translated">Имя поля или свойства, которое инициализируется с помощью инициализатора объектов, должно начинаться с ".".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLbrace">
<source>'{' expected.</source>
<target state="translated">'Требуется "{".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeOrWith">
<source>Type or 'With' expected.</source>
<target state="translated">Требуется тип или "With".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAggrMemberInit1">
<source>Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression.</source>
<target state="translated">Несколько инициализаций "{0}". Поля и свойства можно инициализировать только один раз в выражении инициализатора объекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonFieldPropertyAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is not a field or property.</source>
<target state="translated">Член "{0}" не может быть инициализирован в выражении инициализатора объекта, так как он не является полем или свойством.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedMemberAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is shared.</source>
<target state="translated">Член "{0}" не может быть инициализирован в выражении инициализатора объекта, потому что он является общим.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterizedPropertyInAggrInit1">
<source>Property '{0}' cannot be initialized in an object initializer expression because it requires arguments.</source>
<target state="translated">Свойство "{0}" нельзя инициализировать в выражении инициализатора объекта, так как оно требует использования аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoZeroCountArgumentInitCandidates1">
<source>Property '{0}' cannot be initialized in an object initializer expression because all accessible overloads require arguments.</source>
<target state="translated">Свойство "{0}" не может быть инициализировано в выражении инициализатора объекта, так как все перегрузки требуют использования аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AggrInitInvalidForObject">
<source>Object initializer syntax cannot be used to initialize an instance of 'System.Object'.</source>
<target state="translated">Синтаксис инициализатора объектов нельзя применять для инициализации экземпляра "System.Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerExpected">
<source>Initializer expected.</source>
<target state="translated">Требуется инициализатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LineContWithCommentOrNoPrecSpace">
<source>The line continuation character '_' must be preceded by at least one white space and it must be followed by a comment or the '_' must be the last character on the line.</source>
<target state="translated">Перед символом продолжения строки "_" должен стоять по меньшей мере один пробел, а после этого символа должен идти комментарий, либо "_" должен быть последним символом в строке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFile1">
<source>Unable to load module file '{0}': {1}</source>
<target state="translated">Не удалось загрузить файл модуля "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRefLib1">
<source>Unable to load referenced library '{0}': {1}</source>
<target state="translated">Не удается загрузить указанную библиотеку "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventHandlerSignatureIncompatible2">
<source>Method '{0}' cannot handle event '{1}' because they do not have a compatible signature.</source>
<target state="translated">Методу "{0}" не удается обработать событие "{1}", поскольку они не содержат совместимую сигнатуру.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionalCompilationConstantNotValid">
<source>Conditional compilation constant '{1}' is not valid: {0}</source>
<target state="translated">Константа условной компиляции "{1}" недопустима: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwice1">
<source>Interface '{0}' can be implemented only once by this type.</source>
<target state="translated">Интерфейс "{0}" может быть реализован этим типом только один раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">Интерфейс "{0}" может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">Интерфейс "{0}" может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{1}" (реализован через "{2}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{2}" (реализован через "{3}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">Интерфейс "{0}" может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">Интерфейс "{0}" может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{1}" (реализован через '{2}').</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{2}" (реализован через "{3}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotImplemented1">
<source>Interface '{0}' is not implemented by this class.</source>
<target state="translated">Интерфейс "{0}" в данном классе не реализован.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplementsMember3">
<source>'{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface.</source>
<target state="translated">"{0}" существует в нескольких базовых интерфейсах. Используйте имя данного интерфейса, которое объявляет "{0}" в предложении "Implements", а не имя производного интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsOnNew">
<source>'Sub New' cannot implement interface members.</source>
<target state="translated">'"Sub New" не может содержать реализации членов интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitInStruct">
<source>Arrays declared as structure members cannot be declared with an initial size.</source>
<target state="translated">Массивы, объявляемые как члены структуры, не могут объявляться с начальным размером.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventTypeNotDelegate">
<source>Events declared with an 'As' clause must have a delegate type.</source>
<target state="translated">События, объявляемые с помощью предложения "As", должны иметь тип делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ProtectedTypeOutsideClass">
<source>Protected types can only be declared inside of a class.</source>
<target state="translated">Защищенные типы могут объявляться только в теле класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyWithNoParams">
<source>Properties with no required parameters cannot be declared 'Default'.</source>
<target state="translated">Свойства без обязательных параметров не могут объявляться как "Default".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerInStruct">
<source>Initializers on structure members are valid only for 'Shared' members and constants.</source>
<target state="translated">Инициализаторы членов структур допустимы только для членов "Shared" и констант.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateImport1">
<source>Namespace or type '{0}' has already been imported.</source>
<target state="translated">Пространство имен или тип "{0}" уже импортированы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFlags1">
<source>Modules cannot be declared '{0}'.</source>
<target state="translated">Модули не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsStmtWrongOrder">
<source>'Implements' statements must follow any 'Inherits' statement and precede all declarations in a class.</source>
<target state="translated">'После каждого оператора "Inherits" до первого объявления в классе должен присутствовать оператор "Implements".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithSynth7">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member implicitly declared for {3} '{4}' in {5} '{6}'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", что конфликтует с членом, который был неявно объявлен для {3} "{4}" в {5} "{6}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithMember5">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member of the same name in {3} '{4}'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", который конфликтует с членом с тем же именем в {3} "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberClashesWithSynth6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in {4} '{5}'.</source>
<target state="translated">{0} "{1}" конфликтует с членом, неявно объявленным для {2} "{3}" в {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeClashesWithVbCoreType4">
<source>{0} '{1}' conflicts with a Visual Basic Runtime {2} '{3}'.</source>
<target state="translated">{0} "{1}" конфликтует со средой выполнения Visual Basic {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeMissingAction">
<source>First argument to a security attribute must be a valid SecurityAction.</source>
<target state="translated">Первый аргумент для атрибута безопасности должен быть допустимым атрибутом SecurityAction.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidAction">
<source>Security attribute '{0}' has an invalid SecurityAction value '{1}'.</source>
<target state="translated">Атрибут безопасности "{0}" имеет недопустимое значение SecurityAction "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionAssembly">
<source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly.</source>
<target state="translated">Значение SecurityAction "{0}" является недопустимым для атрибутов безопасности, применяемых к сборке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod">
<source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method.</source>
<target state="translated">Значение SecurityAction "{0}" является недопустимым для атрибутов безопасности, применяемых к типу или методу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrincipalPermissionInvalidAction">
<source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute.</source>
<target state="translated">значение SecurityAction "{0}" недопустимо для атрибута PrincipalPermission.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeInvalidFile">
<source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute.</source>
<target state="translated">Не удается найти путь к файлу "{0}", указанному для именованного аргумента "{1}" для атрибута PermissionSet.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeFileReadError">
<source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'.</source>
<target state="translated">Ошибка чтения файла "{0}", указанного для именованного аргумента "{1}" для атрибута PermissionSet: '{2}'.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasOnlyOneParam">
<source>'Set' method cannot have more than one parameter.</source>
<target state="translated">'Метод "Set" не может иметь более одного параметра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetValueNotPropertyType">
<source>'Set' parameter must have the same type as the containing property.</source>
<target state="translated">'Тип параметра метода "Set" должен совпадать с типом содержащего его свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasToBeByVal1">
<source>'Set' parameter cannot be declared '{0}'.</source>
<target state="translated">'Невозможно объявить параметр "Set" как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureCantUseProtected">
<source>Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.</source>
<target state="translated">Метод в структуре нельзя объявлять как "Protected", "Protected Friend" или "Private Protected".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceDelegateSpecifier1">
<source>Delegate in an interface cannot be declared '{0}'.</source>
<target state="translated">Делегат в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceEnumSpecifier1">
<source>Enum in an interface cannot be declared '{0}'.</source>
<target state="translated">Перечисление в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceClassSpecifier1">
<source>Class in an interface cannot be declared '{0}'.</source>
<target state="translated">Класс в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceStructSpecifier1">
<source>Structure in an interface cannot be declared '{0}'.</source>
<target state="translated">Структура в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceInterfaceSpecifier1">
<source>Interface in an interface cannot be declared '{0}'.</source>
<target state="translated">Интерфейс в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">"{0}" является устаревшим.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotAssembly">
<source>'{0}' is a module and cannot be referenced as an assembly.</source>
<target state="translated">"{0}" является модулем и не может указываться в ссылках как сборка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotModule">
<source>'{0}' is an assembly and cannot be referenced as a module.</source>
<target state="translated">"{0}" является сборкой и не может указываться в ссылках как модуль.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceComparison3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types.</source>
<target state="translated">Оператор "{0}" не определен для типов "{1}" и "{2}". Используйте оператор "Is" для сравнения двух ссылочных типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchVariableNotLocal1">
<source>'{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.</source>
<target state="translated">"{0}" не является локальной переменной или параметром и поэтому не может использоваться как переменная оператора "Catch".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleMemberCantImplement">
<source>Members in a Module cannot implement interface members.</source>
<target state="translated">Методы в модуле не могут содержать реализацию членов интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventDelegatesCantBeFunctions">
<source>Events cannot be declared with a delegate type that has a return type.</source>
<target state="translated">События не могут объявляться типом делегата, обладающим возвращаемым типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDate">
<source>Date constant is not valid.</source>
<target state="translated">Константа даты является недействительной.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverride4">
<source>'{0}' cannot override '{1}' because it is not declared 'Overridable'.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку он не объявлен как "Overridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArraysOnBoth">
<source>Array modifiers cannot be specified on both a variable and its type.</source>
<target state="translated">Модификаторы массива не могут задаваться одновременно для переменной и ее типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotOverridableRequiresOverrides">
<source>'NotOverridable' cannot be specified for methods that do not override another method.</source>
<target state="translated">'"NotOverridable" не может назначаться для методов, не переопределяющих другие методы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrivateTypeOutsideType">
<source>Types declared 'Private' must be inside another type.</source>
<target state="translated">Типы, объявленные как "Private", должны находиться внутри других типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeRefResolutionError3">
<source>Import of type '{0}' from assembly or module '{1}' failed.</source>
<target state="translated">Импортирование типа "{0}" из сборки или модуля "{1}" невозможно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleTypeRefResolutionError1">
<source>Predefined type '{0}' is not defined or imported.</source>
<target state="translated">Предопределенный тип "{0}" не определен и не импортирован.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWrongType">
<source>ParamArray parameters must have an array type.</source>
<target state="translated">Параметры ParamArray должны быть массивами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CoClassMissing2">
<source>Implementing class '{0}' for interface '{1}' cannot be found.</source>
<target state="translated">Не удается найти класс реализации "{0}" для интерфейса "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidCoClass1">
<source>Type '{0}' cannot be used as an implementing class.</source>
<target state="translated">Тип "{0}" не может использоваться как класс реализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMeReference">
<source>Reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">При вызове другого конструктора ссылки на объект, находящийся в процессе построения, недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitMeReference">
<source>Implicit reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">При вызове другого конструктора неявные ссылки на объект, находящийся в процессе построения, недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeMemberNotFound2">
<source>Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'.</source>
<target state="translated">Член "{0}" не может быть найден в классе "{1}". Это условие, как правило, является результатом несоответствия "Microsoft.VisualBasic.dll".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags">
<source>Property accessors cannot be declared '{0}'.</source>
<target state="translated">Методы доступа к свойствам нельзя объявить как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlagsRestrict">
<source>Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.</source>
<target state="translated">Модификатор доступа "{0}" недействителен. Модификатор доступа для "Get" и "Set" должен быть более ограничивающим, чем уровень доступа к свойству.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneAccessorForGetSet">
<source>Access modifier can only be applied to either 'Get' or 'Set', but not both.</source>
<target state="translated">Модификатор доступа может применяться либо к "Get", либо к "Set", но не к обоим методам одновременно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleSet">
<source>'Set' accessor of property '{0}' is not accessible.</source>
<target state="translated">'Метод доступа свойства "Set" "{0}" недоступен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleGet">
<source>'Get' accessor of property '{0}' is not accessible.</source>
<target state="translated">'Метод доступа свойства "Get" "{0}" недоступен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyNoAccessorFlag">
<source>'WriteOnly' properties cannot have an access modifier on 'Set'.</source>
<target state="translated">'Свойства со спецификатором WriteOnly не могут иметь модификатор доступа для Set.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyNoAccessorFlag">
<source>'ReadOnly' properties cannot have an access modifier on 'Get'.</source>
<target state="translated">'Свойства со спецификатором "ReadOnly" не могут иметь модификатор доступа для "Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags1">
<source>Property accessors cannot be declared '{0}' in a 'NotOverridable' property.</source>
<target state="translated">Методы доступа к свойствам нельзя объявить как "{0}" в свойстве "NotOverridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags2">
<source>Property accessors cannot be declared '{0}' in a 'Default' property.</source>
<target state="translated">Методы доступа к свойствам нельзя объявить "{0}" в свойстве "Default".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags3">
<source>Property cannot be declared '{0}' because it contains a 'Private' accessor.</source>
<target state="translated">Свойство не может быть объявлено "{0}", поскольку оно содержит метод доступа "Private".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleCoClass3">
<source>Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">Реализация класса "{0}" для интерфейса "{1}" недоступна в этом контексте, поскольку он является "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingValuesForArraysInApplAttrs">
<source>Arrays used as attribute arguments are required to explicitly specify values for all elements.</source>
<target state="translated">Для массивов, используемых как аргументы атрибутов, требуется явное указание значений для всех элементов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitEventMemberNotInvalid">
<source>'Exit AddHandler', 'Exit RemoveHandler' and 'Exit RaiseEvent' are not valid. Use 'Return' to exit from event members.</source>
<target state="translated">'"Exit AddHandler", "Exit RemoveHandler" и "Exit RaiseEvent" недопустимы. Используйте "Return" для выхода из членов-событий.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEvent">
<source>Statement cannot appear within an event body. End of event assumed.</source>
<target state="translated">Оператор не может появляться в теле события. Подразумевается завершение события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEvent">
<source>'Custom Event' must end with a matching 'End Event'.</source>
<target state="translated">'Оператор "Custom Event" должен завершаться соответствующим оператором "End Event".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndAddHandler">
<source>'AddHandler' declaration must end with a matching 'End AddHandler'.</source>
<target state="translated">'Объявление "AddHandler" должно завершаться соответствующим оператором "End AddHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRemoveHandler">
<source>'RemoveHandler' declaration must end with a matching 'End RemoveHandler'.</source>
<target state="translated">'Объявление "RemoveHandler" должно завершаться соответствующим оператором "End RemoveHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRaiseEvent">
<source>'RaiseEvent' declaration must end with a matching 'End RaiseEvent'.</source>
<target state="translated">'Объявление "RaiseEvent" должно завершаться соответствующим оператором "End RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventInvInInterface">
<source>'Custom' modifier is not valid on events declared in interfaces.</source>
<target state="translated">'Модификатор Custom недопустим для событий, объявленных в интерфейсах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventRequiresAs">
<source>'Custom' modifier is not valid on events declared without explicit delegate types.</source>
<target state="translated">'Модификатор "Custom" недопустим для событий, объявленных без явных типов делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEvent">
<source>'End Event' must be preceded by a matching 'Custom Event'.</source>
<target state="translated">'Оператору "End Event" должен предшествовать соответствующий оператор "Custom Event".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndAddHandler">
<source>'End AddHandler' must be preceded by a matching 'AddHandler' declaration.</source>
<target state="translated">'Оператору "End AddHandler "должно предшествовать соответствующее объявление "AddHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRemoveHandler">
<source>'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.</source>
<target state="translated">'Оператору "End RemoveHandler" должно предшествовать соответствующее объявление "RemoveHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRaiseEvent">
<source>'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.</source>
<target state="translated">'Оператору "End RaiseEvent" должно предшествовать соответствующее объявление "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAddHandlerDef">
<source>'AddHandler' is already declared.</source>
<target state="translated">'"AddHandler" уже объявлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRemoveHandlerDef">
<source>'RemoveHandler' is already declared.</source>
<target state="translated">'Процедура "RemoveHandler" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRaiseEventDef">
<source>'RaiseEvent' is already declared.</source>
<target state="translated">'Процедура "RaiseEvent" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingAddHandlerDef1">
<source>'AddHandler' definition missing for event '{0}'.</source>
<target state="translated">'Отсутствует определение "AddHandler" события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRemoveHandlerDef1">
<source>'RemoveHandler' definition missing for event '{0}'.</source>
<target state="translated">'Отсутствует определение "RemoveHandler" события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRaiseEventDef1">
<source>'RaiseEvent' definition missing for event '{0}'.</source>
<target state="translated">'Отсутствует определение "RaiseEvent" события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveHasOnlyOneParam">
<source>'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.</source>
<target state="translated">'У методов "AddHandler" и "RemoveHandler" должен быть ровно один параметр.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveByrefParamIllegal">
<source>'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.</source>
<target state="translated">'Параметры методов "AddHandler" и "RemoveHandler" не могут быть объявлены как "ByRef".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvOnEventMethod">
<source>Specifiers are not valid on 'AddHandler', 'RemoveHandler' and 'RaiseEvent' methods.</source>
<target state="translated">Спецификаторы не применимы к методам "AddHandler", "RemoveHandler" и "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddRemoveParamNotEventType">
<source>'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.</source>
<target state="translated">'Параметры методов "AddHandler" и "RemoveHandler" должны иметь такой же тип делегата, как содержащее их событие.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RaiseEventShapeMismatch1">
<source>'RaiseEvent' method must have the same signature as the containing event's delegate type '{0}'.</source>
<target state="translated">'Метод "RaiseEvent" должен иметь одинаковую сигнатуру с типом делегата содержащегося события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventMethodOptionalParamIllegal1">
<source>'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared '{0}'.</source>
<target state="translated">'Параметры методов "AddHandler", "RemoveHandler" и "RaiseEvent" не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReferToMyGroupInsideGroupType1">
<source>'{0}' cannot refer to itself through its default instance; use 'Me' instead.</source>
<target state="translated">"{0}" не может ссылаться на себя с помощью экземпляра по умолчанию; вместо этого используйте "Me".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfCustomModifier">
<source>'Custom' modifier can only be used immediately before an 'Event' declaration.</source>
<target state="translated">'Модификатор "Custom" может использоваться только непосредственно перед объявлением "Event".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrictCustom">
<source>Option Strict Custom can only be used as an option to the command-line compiler (vbc.exe).</source>
<target state="translated">Option Strict Custom может использоваться только как параметр компилятора командной строки (vbc.exe).</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteInvalidOnEventMember">
<source>'{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.</source>
<target state="translated">"{0}" не может быть применен к определениям "AddHandler", "RemoveHandler" или "RaiseEvent". При необходимости примените атрибут непосредственно к событию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible2">
<source>Method '{0}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">Метод расширения "{0}" не имеет сигнатуры, совместимой с делегатом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlName">
<source>XML name expected.</source>
<target state="translated">Ожидалось XML-имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedXmlPrefix">
<source>XML namespace prefix '{0}' is not defined.</source>
<target state="translated">Префикс пространства имен XML "{0}" не определен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateXmlAttribute">
<source>Duplicate XML attribute '{0}'.</source>
<target state="translated">Повторяющийся атрибут XML "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MismatchedXmlEndTag">
<source>End tag </{0}{1}{2}> expected.</source>
<target state="translated">Требуется конечный тег </{0}{1}{2}>.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingXmlEndTag">
<source>Element is missing an end tag.</source>
<target state="translated">В элементе отсутствует конечный тег.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlPrefix">
<source>XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed.</source>
<target state="translated">Префикс пространства имен XML "{0}" зарезервирован для использования XML, и пространство имен URI не может быть изменено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingVersionInXmlDecl">
<source>Required attribute 'version' missing from XML declaration.</source>
<target state="translated">В объявлении XML отсутствует необходимый атрибут "version".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalAttributeInXmlDecl">
<source>XML declaration does not allow attribute '{0}{1}{2}'.</source>
<target state="translated">В объявлении XML не может быть атрибута "{0}{1}{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_QuotedEmbeddedExpression">
<source>Embedded expression cannot appear inside a quoted attribute value. Try removing quotes.</source>
<target state="translated">Вложенное выражение не может появляться внутри значения атрибута в кавычках. Попробуйте убрать кавычки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VersionMustBeFirstInXmlDecl">
<source>XML attribute 'version' must be the first attribute in XML declaration.</source>
<target state="translated">Атрибут XML "version" должен быть первым атрибутом в объявлении XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOrder">
<source>XML attribute '{0}' must appear before XML attribute '{1}'.</source>
<target state="translated">Атрибут XML "{0}" должен предшествовать атрибуту XML "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndEmbedded">
<source>Expected closing '%>' for embedded expression.</source>
<target state="translated">Для вложенного выражения требуются закрывающие символы "%>".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndPI">
<source>Expected closing '?>' for XML processor instruction.</source>
<target state="translated">В инструкции XML-процессора требуется закрывающие символы "?>".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndComment">
<source>Expected closing '-->' for XML comment.</source>
<target state="translated">В комментарии XML требуются закрывающие символы "-->".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndCData">
<source>Expected closing ']]>' for XML CDATA section.</source>
<target state="translated">Требуются закрывающие символы "]]>" для XML-секции CDATA.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSQuote">
<source>Expected matching closing single quote for XML attribute value.</source>
<target state="translated">Для значения атрибута XML требуется закрывающая одинарная кавычка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQuote">
<source>Expected matching closing double quote for XML attribute value.</source>
<target state="translated">Для значения атрибута XML требуется закрывающая двойная кавычка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLT">
<source>Expected beginning '<' for an XML tag.</source>
<target state="translated">Для XML-тега требуется открывающий символ "<".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartAttributeValue">
<source>Expected quoted XML attribute value or embedded expression.</source>
<target state="translated">Требуется заключенное в кавычки значение атрибута XML или вложенное выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDiv">
<source>Expected '/' for XML end tag.</source>
<target state="translated">Для закрывающего XML-тега требуется символ "/".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoXmlAxesLateBinding">
<source>XML axis properties do not support late binding.</source>
<target state="translated">Свойства оси XML не поддерживают позднее связывание.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlStartNameChar">
<source>Character '{0}' ({1}) is not allowed at the beginning of an XML name.</source>
<target state="translated">Не допускается использование символа "{0}" ({1}) в начале имени XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlNameChar">
<source>Character '{0}' ({1}) is not allowed in an XML name.</source>
<target state="translated">Не допускается использование символа "{0}" ({1}) в имени XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlCommentChar">
<source>Character sequence '--' is not allowed in an XML comment.</source>
<target state="translated">Последовательность символов "--" недопустима в XML-комментарии.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmbeddedExpression">
<source>An embedded expression cannot be used here.</source>
<target state="translated">Вложенное выражение не может быть здесь использовано.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlWhiteSpace">
<source>Missing required white space.</source>
<target state="translated">Отсутствует обязательный пробел.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalProcessingInstructionName">
<source>XML processing instruction name '{0}' is not valid.</source>
<target state="translated">Недопустимое имя инструкции по обработке XML "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DTDNotSupported">
<source>XML DTDs are not supported.</source>
<target state="translated">Шаблоны DTD XML не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlWhiteSpace">
<source>White space cannot appear here.</source>
<target state="translated">Здесь не может находиться пробел.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSColon">
<source>Expected closing ';' for XML entity.</source>
<target state="translated">Для XML-сущности требуется закрывающий знак ";".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlBeginEmbedded">
<source>Expected '%=' at start of an embedded expression.</source>
<target state="translated">В начале вложенного выражения требуется "%=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEntityReference">
<source>XML entity references are not supported.</source>
<target state="translated">Ссылки на специальный символ XML не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue1">
<source>Attribute value is not valid; expecting '{0}'.</source>
<target state="translated">Недопустимое значение атрибута; ожидается значение "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue2">
<source>Attribute value is not valid; expecting '{0}' or '{1}'.</source>
<target state="translated">Недопустимое значение атрибута; ожидается значение "{0}" или "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlNamespace">
<source>Prefix '{0}' cannot be bound to namespace name reserved for '{1}'.</source>
<target state="translated">Префикс "{0}" не может быть привязан к имени пространства имен, зарезервированных для "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalDefaultNamespace">
<source>Namespace declaration with prefix cannot have an empty value inside an XML literal.</source>
<target state="translated">Объявление пространства имен вместе с префиксом не может иметь пустое значение внутри XML-литерала.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualifiedNameNotAllowed">
<source>':' is not allowed. XML qualified names cannot be used in this context.</source>
<target state="translated">'Символ ":" не допустим. Не удается использовать уточненные XML-имена в этом контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlns">
<source>Namespace declaration must start with 'xmlns'.</source>
<target state="translated">Объявление пространства имен должно начинаться с "xmlns".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlnsPrefix">
<source>Element names cannot use the 'xmlns' prefix.</source>
<target state="translated">В именах элементов не может использоваться префикс "xmlns".</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlFeaturesNotAvailable">
<source>XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.</source>
<target state="translated">Литералы XML и свойства оси XML недоступны. Добавьте ссылки на System.Xml, System.Xml.Linq и System.Core или другие сборки, объявляющие типы System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute и System.Xml.Linq.XNamespace.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToReadUacManifest2">
<source>Unable to open Win32 manifest file '{0}' : {1}</source>
<target state="translated">Не удалось открыть файл манифеста Win32 "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3">
<source>Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">Не удается преобразовать "{0}" в "{1}". Вы можете использовать свойство "Value", чтобы получить строковое значение первого элемента "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3_Title">
<source>Cannot convert IEnumerable(Of XElement) to String</source>
<target state="translated">Невозможно преобразовать IEnumerable(XElement) в строку</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatchForXml3">
<source>Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}". Вы можете использовать свойство "Value", чтобы получить строковое значение первого элемента "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperandsForXml4">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'.</source>
<target state="translated">Оператор "{0}" не определен для типов "{1}" и "{2}". Вы можете использовать свойство "Value", чтобы получить строковое значение первого элемента "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FullWidthAsXmlDelimiter">
<source>Full width characters are not valid as XML delimiters.</source>
<target state="translated">Широкие символы не допускаются в качестве разделителей XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSubsystemVersion">
<source>The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise.</source>
<target state="translated">Значение "{0}" не является допустимой версией подсистемы. Для ARM или AppContainerExe должна быть указана версия 6.02 или выше, в остальных случаях — версия 4.00 или выше.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFileAlignment">
<source>Invalid file section alignment '{0}'</source>
<target state="translated">Недопустимое выравнивание разделов файла "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOutputName">
<source>Invalid output name: {0}</source>
<target state="translated">Недопустимое имя выходных данных: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInformationFormat">
<source>Invalid debug information format: {0}</source>
<target state="translated">Недопустимый формат отладочной информации: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibAnycpu32bitPreferredConflict">
<source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe.</source>
<target state="translated">Параметр /platform:anycpu32bitpreferred можно использовать только вместе с параметрами /t:exe, /t:winexe и /t:appcontainerexe.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedAccess">
<source>Expression has the type '{0}' which is a restricted type and cannot be used to access members inherited from 'Object' or 'ValueType'.</source>
<target state="translated">Выражение имеет тип "{0}", который является ограниченным типом и не может использоваться для доступа к членам, унаследованным из "Object" или "ValueType".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedConversion1">
<source>Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'.</source>
<target state="translated">Выражение типа "{0}" невозможно преобразовать в "Object" или "ValueType".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInLabel">
<source>Type characters are not allowed in label identifiers.</source>
<target state="translated">Символы типа недопустимы в идентификаторах меток.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedType1">
<source>'{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.</source>
<target state="translated">"{0}" не может принимать значение Null и не может быть использовано в качестве типа данных элемента массива, поля, анонимного типа члена, аргумента типа, параметра "ByRef" или оператора return.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInAlias">
<source>Type characters are not allowed on Imports aliases.</source>
<target state="translated">Символы типа недопустимы для псевдонимов Imports.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleConstructorOnBase">
<source>Class '{0}' has no accessible 'Sub New' and cannot be inherited.</source>
<target state="translated">Класс "{0}" не имеет доступного "Sub New" и не может быть унаследован.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInStruct">
<source>Local variables within methods of structures cannot be declared 'Static'.</source>
<target state="translated">Локальные переменные в методах структур не могут объявляться как "Static".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalStatic1">
<source>Static local variable '{0}' is already declared.</source>
<target state="translated">Статическая локальная переменная "{0}" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportAliasConflictsWithType2">
<source>Imports alias '{0}' conflicts with '{1}' declared in the root namespace.</source>
<target state="translated">Псевдоним Imports "{0}" конфликтует с "{1}", объявленном в корневом пространстве имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantShadowAMustOverride1">
<source>'{0}' cannot shadow a method declared 'MustOverride'.</source>
<target state="translated">"{0}" не может сделать теневым метод, объявленный как "MustOverride".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleEventImplMismatch3">
<source>Event '{0}' cannot implement event '{2}.{1}' because its delegate type does not match the delegate type of another event implemented by '{0}'.</source>
<target state="translated">Событию "{0}" не удается реализовать событие "{2}.{1}", поскольку его тип делегата не соответствует типу делегата другого события, реализованного "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSpecifierCombo2">
<source>'{0}' and '{1}' cannot be combined.</source>
<target state="translated">"{0}" и "{1}" объединять нельзя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeOverloads2">
<source>{0} '{1}' must be declared 'Overloads' because another '{1}' is declared 'Overloads' or 'Overrides'.</source>
<target state="translated">{0} "{1}" должно быть объявлено как "Overloads", поскольку другая переменная "{1}" объявлена как "Overloads" или "Overrides".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverridesInClass1">
<source>'{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.</source>
<target state="translated">"{0}" должна быть объявлена как "MustInherit", потому что она содержит методы, объявленные как "MustOverride".</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInClass">
<source>'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.</source>
<target state="translated">'В "Handles" в классах должна указываться переменная, объявленная с модификатором "WithEvents", либо объект "MyBase", "MyClass" или "Me", ограниченный одним идентификатором.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberShadowsMustOverride5">
<source>'{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'.</source>
<target state="translated">"{0}", неявно объявленный для {1} "{2}", не может затенять метод "MustOverride" в базе {3} "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotOverrideInAccessibleMember">
<source>'{0}' cannot override '{1}' because it is not accessible in this context.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку он недоступен в данном контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInModule">
<source>'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.</source>
<target state="translated">'В "Handles" в модулях должна указываться переменная с модификатором WithEvents, ограниченная одним идентификатором.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOpRequiresReferenceTypes1">
<source>'IsNot' requires operands that have reference types, but this operand has the value type '{0}'.</source>
<target state="translated">'Для "IsNot" требуются операнды ссылочных типов, а этот операнд имеет тип значения "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClashWithReservedEnumMember1">
<source>'{0}' conflicts with the reserved member by this name that is implicitly declared in all enums.</source>
<target state="translated">"{0}" конфликтует с зарезервированным членом по данному имени, которое явно объявлено во всех перечислениях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedEnumMember2">
<source>'{0}' is already declared in this {1}.</source>
<target state="translated">"{0}" уже объявлено в {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadUseOfVoid">
<source>'System.Void' can only be used in a GetType expression.</source>
<target state="translated">'System.Void можно использовать только в выражении GetType.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplMismatch5">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because their delegate types '{3}' and '{4}' do not match.</source>
<target state="translated">Событию "{0}" не удается реализовать событие "{1}" в интерфейсе "{2}" из-за несовпадения их типов делегатов "{3}" и "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeUnavailable3">
<source>Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'.</source>
<target state="translated">Тип "{0}" в сборке "{1}" переадресован в сборку "{2}". Либо ссылка на "{2}" отсутствует в вашем проекте, либо тип "{0}" отсутствует в сборке "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeFwdCycle2">
<source>'{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type.</source>
<target state="translated">"{0}" в сборке "{1}" был перемещен к себе и поэтому является недопустимым типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeInCCExpression">
<source>Non-intrinsic type names are not allowed in conditional compilation expressions.</source>
<target state="translated">Имена типов, отличных от встроенных, недопустимы в выражениях условной компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCCExpression">
<source>Syntax error in conditional compilation expression.</source>
<target state="translated">Синтаксическая ошибка в выражении условной компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidArrayDisallowed">
<source>Arrays of type 'System.Void' are not allowed in this expression.</source>
<target state="translated">Массивы типа "System.Void" недопустимы в данном выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataMembersAmbiguous3">
<source>'{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'.</source>
<target state="translated">"{0}" неоднозначно, поскольку несколько видов членов с данным именем существует в {1} "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfExprAlwaysFalse2">
<source>Expression of type '{0}' can never be of type '{1}'.</source>
<target state="translated">Выражение типа "{0}" не может относиться к типу "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyPrivatePartialMethods1">
<source>Partial methods must be declared 'Private' instead of '{0}'.</source>
<target state="translated">Разделяемые методы должны быть объявлены "Private", а не "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBePrivate">
<source>Partial methods must be declared 'Private'.</source>
<target state="translated">Разделяемые методы должны быть объявлены как "Private".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOnePartialMethodAllowed2">
<source>Method '{0}' cannot be declared 'Partial' because only one method '{1}' can be marked 'Partial'.</source>
<target state="translated">Метод "{0}" не может быть объявлен "Partial", так как только один метод "{1}" может быть помечен как "Partial".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneImplementingMethodAllowed3">
<source>Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method.</source>
<target state="translated">Метод "{0}" не может реализовывать разделяемый метод "{1}", так как "{2}" он уже реализован. Только один метод может реализовать разделяемый метод.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodMustBeEmpty">
<source>Partial methods must have empty method bodies.</source>
<target state="translated">Разделяемые методы должны иметь пустое тело метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBeSub1">
<source>'{0}' cannot be declared 'Partial' because partial methods must be Subs.</source>
<target state="translated">"{0}" не может быть объявлен "Partial", так как разделяемые методы должны быть Subs.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodGenericConstraints2">
<source>Method '{0}' does not have the same generic constraints as the partial method '{1}'.</source>
<target state="translated">Метод "{0}" не имеет те же универсальные ограничения, что и разделяемый метод "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialDeclarationImplements1">
<source>Partial method '{0}' cannot use the 'Implements' keyword.</source>
<target state="translated">Разделяемый метод "{0}" не может использовать ключевое слово "Implements".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPartialMethodInAddressOf1">
<source>'AddressOf' cannot be applied to '{0}' because '{0}' is a partial method without an implementation.</source>
<target state="translated">'"AddressOf" не может быть применен к "{0}", так как "{0}" является разделяемым методом без реализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementationMustBePrivate2">
<source>Method '{0}' must be declared 'Private' in order to implement partial method '{1}'.</source>
<target state="translated">Метод "{0}" должен быть объявлен как "Private", чтобы реализовать частичный метод "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamNamesMustMatch3">
<source>Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'.</source>
<target state="translated">Имя параметра "{0}" не соответствует имени соответствующего параметра "{1}", определенного для объявления разделяемого метода "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodTypeParamNameMismatch3">
<source>Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'.</source>
<target state="translated">Имя параметра типа "{0}" не соответствует "{1}", соответствующий параметр типа, определенный для объявления разделяемого метода "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeSharedProperty1">
<source>'Shared' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Свойству атрибута "Shared" "{0}" нельзя присваивать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeReadOnlyProperty1">
<source>'ReadOnly' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Свойству атрибута "ReadOnly" "{0}" нельзя присваивать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceName1">
<source>Resource name '{0}' cannot be used more than once.</source>
<target state="translated">Имя ресурса "{0}" не может использоваться более одного раза.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceFileName1">
<source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly.</source>
<target state="translated">Каждый связанный ресурс и модуль должны иметь уникальное имя файла. Имя файла "{0}" определено более одного раза в этой сборке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustBeClassNotStruct1">
<source>'{0}' cannot be used as an attribute because it is not a class.</source>
<target state="translated">"{0}" нельзя использовать как атрибут, поскольку он не является классом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustInheritSysAttr">
<source>'{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'.</source>
<target state="translated">"{0}" нельзя использовать как атрибут, так как он не является производным от "System.Attribute".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeCannotBeAbstract">
<source>'{0}' cannot be used as an attribute because it is declared 'MustInherit'.</source>
<target state="translated">"{0}" не может использоваться как атрибут, поскольку он объявлен как "MustInherit".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToOpenResourceFile1">
<source>Unable to open resource file '{0}': {1}</source>
<target state="translated">Не удалось открыть файл ресурсов "{0}". {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicProperty1">
<source>Attribute member '{0}' cannot be the target of an assignment because it is not declared 'Public'.</source>
<target state="translated">Члену атрибута "{0}" нельзя присваивать значение, поскольку он не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_STAThreadAndMTAThread0">
<source>'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.</source>
<target state="translated">'Атрибуты "System.STAThreadAttribute" и "System.MTAThreadAttribute" не могут вместе использоваться для одного метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndirectUnreferencedAssembly4">
<source>Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project.</source>
<target state="translated">В проекте "{0}" имеется косвенная ссылка на сборку "{1}", которая содержит "{2}". Добавьте к проекту ссылку на файл "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicType1">
<source>Type '{0}' cannot be used in an attribute because it is not declared 'Public'.</source>
<target state="translated">Тип "{0}" нельзя использовать в атрибуте, поскольку он не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicContType2">
<source>Type '{0}' cannot be used in an attribute because its container '{1}' is not declared 'Public'.</source>
<target state="translated">Тип "{0}" нельзя использовать в атрибуте, поскольку его контейнер "{1}" не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnNonEmptySubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к блоку Sub, Function или Operator с непустым телом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnDeclare">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Declare.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не применим к оператору Declare.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnGetOrSet">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Get or Set.</source>
<target state="translated">'Атрибут System.Runtime.InteropServices.DllImportAttribute не может применяться к оператору Get или Set.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnGenericSubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a method that is generic or contained in a generic type.</source>
<target state="translated">'Атрибут System.Runtime.InteropServices.DllImportAttribute не может применяться к универсальному методу или методу, содержащемуся в универсальном типе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassOnGeneric">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute не может применяться к универсальному классу или классу, содержащемуся в универсальном типе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInstanceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методу экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInterfaceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to interface methods.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методам интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnEventMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to 'AddHandler', 'RemoveHandler' or 'RaiseEvent' method.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методам "AddHandler", "RemoveHandler" и "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadArguments">
<source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source>
<target state="translated">Недопустимая дружественная ссылка на сборку "{0}". Объявления InternalsVisibleTo не содержат определения версии, языка и региональных параметров, токена открытого ключа или архитектуры процессора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyStrongNameRequired">
<source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source>
<target state="translated">Недопустимая дружественная ссылка на сборку "{0}". Сборки, подписанные строгим именем, должны содержать в объявлении InternalsVisibleTo открытый ключ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyNameInvalid">
<source>Friend declaration '{0}' is invalid and cannot be resolved.</source>
<target state="translated">Дружественное объявление "{0}" недопустимо и не может быть разрешено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadAccessOverride2">
<source>Member '{0}' cannot override member '{1}' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.</source>
<target state="translated">Член "{0}" не может переопределить член "{1}", определенный в другой сборке или проекте, так как модификатор доступа "Protected Friend" расширяет доступность. Вместо него используйте "Protected".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfLocalBeforeDeclaration1">
<source>Local variable '{0}' cannot be referred to before it is declared.</source>
<target state="translated">Невозможно указать локальную переменную "{0}" до ее объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromModule1">
<source>'{0}' is not valid within a Module.</source>
<target state="translated">"{0}" не является допустимым в модуле.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BogusWithinLineIf">
<source>Statement cannot end a block outside of a line 'If' statement.</source>
<target state="translated">Нельзя завершить блок, внешний по отношению к однострочному оператору If.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CharToIntegralTypeMismatch1">
<source>'Char' values cannot be converted to '{0}'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit.</source>
<target state="translated">'Значения "Char" невозможно преобразовать в "{0}". Используйте "Microsoft.VisualBasic.AscW" для интерпретации символа как символа Юникода или "Microsoft.VisualBasic.Val" для интерпретации его как цифры.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IntegralToCharTypeMismatch1">
<source>'{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit.</source>
<target state="translated">'"Значения "{0}" невозможно преобразовать в "Char". Используйте "Microsoft.VisualBasic.ChrW" для интерпретации числового значения как символа Юникода или сначала преобразуйте его в значение типа "String" для получения цифры.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDirectDelegateConstruction1">
<source>Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.</source>
<target state="translated">Делегат "{0}" требует выражение "AddressOf" или лямбда-выражение в качестве единственного аргумента конструктора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodMustBeFirstStatementOnLine">
<source>Method declaration statements must be the first statement on a logical line.</source>
<target state="translated">Операторы объявления методов должны указываться первыми в логической строке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrAssignmentNotFieldOrProp1">
<source>'{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property.</source>
<target state="translated">"{0}" нельзя указать как параметр в описателе атрибута, поскольку он не является полем или свойством.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectComparison1">
<source>Option Strict On disallows operands of type Object for operator '{0}'. Use the 'Is' operator to test for object identity.</source>
<target state="translated">Option Strict On не разрешает операнды типа Object для оператора "{0}". Используйте оператор "Is" для проверки идентификатора объекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstituentArraySizes">
<source>Bounds can be specified only for the top-level array when initializing an array of arrays.</source>
<target state="translated">При инициализации массива массивов границы могут задаваться только для массива верхнего уровня.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileAttributeNotAssemblyOrModule">
<source>'Assembly' or 'Module' expected.</source>
<target state="translated">'Требуется "Assembly" или "Module".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FunctionResultCannotBeIndexed1">
<source>'{0}' has no parameters and its return type cannot be indexed.</source>
<target state="translated">"{0}" не имеет параметров, поэтому невозможно проиндексировать его возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentSyntax">
<source>Comma, ')', or a valid expression continuation expected.</source>
<target state="translated">Требуется запятая, ")" или допустимое продолжение выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedResumeOrGoto">
<source>'Resume' or 'GoTo' expected.</source>
<target state="translated">'Требуется "Resume" или "GoTo".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperator">
<source>'=' expected.</source>
<target state="translated">'Требуется "=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted2">
<source>Parameter '{0}' in '{1}' already has a matching omitted argument.</source>
<target state="translated">Параметр "{0}" в "{1}" уже имеет соответствующий пропущенный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotCallEvent1">
<source>'{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.</source>
<target state="translated">"{0}" является событием и не может вызываться напрямую. Для порождения события используйте оператор "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachCollectionDesignPattern1">
<source>Expression is of type '{0}', which is not a collection type.</source>
<target state="translated">Выражение имеет тип "{0}", не являющийся типом коллекции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultValueForNonOptionalParam">
<source>Default values cannot be supplied for parameters that are not declared 'Optional'.</source>
<target state="translated">Значения по умолчанию не могут задаваться для параметров, не объявленных как "Optional".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyBase">
<source>'MyBase' must be followed by '.' and an identifier.</source>
<target state="translated">'После "MyBase" должны следовать "." и идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyClass">
<source>'MyClass' must be followed by '.' and an identifier.</source>
<target state="translated">'После "MyClass" должны следовать "." и идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictArgumentCopyBackNarrowing3">
<source>Option Strict On disallows narrowing from type '{1}' to type '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">Option Strict On не разрешает сужение из типа "{1}" в тип "{2}" при копировании значения параметра "ByRef" "{0}" обратно в соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseifAfterElse">
<source>'#ElseIf' cannot follow '#Else' as part of a '#If' block.</source>
<target state="translated">'Блок "#ElseIf" не может следовать за "#Else" в пределах блока "#If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StandaloneAttribute">
<source>Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.</source>
<target state="translated">Спецификатор атрибута не является законченным оператором. Для назначения атрибута следующему оператору используйте символ продолжения строки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoUniqueConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как его базовый класс "{1}" имеет более чем один доступный "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraNextVariable">
<source>'Next' statement names more variables than there are matching 'For' statements.</source>
<target state="translated">'В операторе "Next" указано больше переменных, чем в соответствующих операторах "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCallTooMany2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" из "{1}" имеет более чем один доступный "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForCtlVarArraySizesSpecified">
<source>Array declared as for loop control variable cannot be declared with an initial size.</source>
<target state="translated">Массив, объявляемый для переменной цикла For, не может объявляться с начальным размером.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNewOverloads">
<source>The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'.</source>
<target state="translated">Ключевое слово "{0}" используется для перегрузки наследуемых членов. Не используйте ключевое слово "{0}" при перегрузке "Sub New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnGenericParam">
<source>Type character cannot be used in a type parameter declaration.</source>
<target state="translated">Символ типа нельзя использовать в объявлении параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments1">
<source>Too few type arguments to '{0}'.</source>
<target state="translated">Слишком мало аргументов типа в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments1">
<source>Too many type arguments to '{0}'.</source>
<target state="translated">Слишком много аргументов типа в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericConstraintNotSatisfied2">
<source>Type argument '{0}' does not inherit from or implement the constraint type '{1}'.</source>
<target state="translated">Аргумент типа "{0}" не наследует или реализует строгий тип "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric1">
<source>'{0}' has no type parameters and so cannot have type arguments.</source>
<target state="translated">"{0}" не имеет параметров типа и поэтому не может иметь аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnGenericParam">
<source>'New' cannot be used on a type parameter that does not have a 'New' constraint.</source>
<target state="translated">'"New" нельзя использовать для параметра-типа, у которого нет ограничения "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleClassConstraints1">
<source>Type parameter '{0}' can only have one constraint that is a class.</source>
<target state="translated">Параметр типа "{0}" может иметь только одно ограничение, которое является классом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstNotClassInterfaceOrTypeParam1">
<source>Type constraint '{0}' must be either a class, interface or type parameter.</source>
<target state="translated">Тип ограничения "{0}" должен быть классом, интерфейсом или параметром типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateTypeParamName1">
<source>Type parameter already declared with name '{0}'.</source>
<target state="translated">Параметр типа уже объявлен с именем "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam2">
<source>Type parameter '{0}' for '{1}' cannot be inferred.</source>
<target state="translated">Невозможно получить параметр типа "{0}" для "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorGenericParam1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'Операнд "Is" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является параметром типа без ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentCopyBackNarrowing3">
<source>Copying the value of 'ByRef' parameter '{0}' back to the matching argument narrows from type '{1}' to type '{2}'.</source>
<target state="translated">Копирование значения параметра "ByRef" "{0}" обратно в соответствующий аргумент сводит тип "{1}" к типу "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingGenericParamWithMember1">
<source>'{0}' has the same name as a type parameter.</source>
<target state="translated">"{0}" имеет такое же имя, как и параметр типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamBase2">
<source>{0} '{1}' cannot inherit from a type parameter.</source>
<target state="translated">{0} "{1}" не может наследовать от параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsGenericParam">
<source>Type parameter not allowed in 'Implements' clause.</source>
<target state="translated">Параметр-тип нельзя использовать в предложении "Implements".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyNullLowerBound">
<source>Array lower bounds can be only '0'.</source>
<target state="translated">Нижняя граница массива должна равняться 0.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassConstraintNotInheritable1">
<source>Type constraint cannot be a 'NotInheritable' class.</source>
<target state="translated">Ограничение типа не может быть классом, объявленным как "NotInheritable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintIsRestrictedType1">
<source>'{0}' cannot be used as a type constraint.</source>
<target state="translated">"{0}" нельзя использовать как ограничение типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamsOnInvalidMember">
<source>Type parameters cannot be specified on this declaration.</source>
<target state="translated">Параметры типа нельзя указать в этом объявлении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericArgsOnAttributeSpecifier">
<source>Type arguments are not valid because attributes cannot be generic.</source>
<target state="translated">Недопустимые аргументы типа, поскольку атрибуты не могут быть универсального типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrCannotBeGenerics">
<source>Type parameters, generic types or types contained in generic types cannot be used as attributes.</source>
<target state="translated">Параметры-типы, универсальные типы и типы, содержащиеся внутри универсальных типов, нельзя использовать в качестве атрибутов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInGenericMethod">
<source>Local variables within generic methods cannot be declared 'Static'.</source>
<target state="translated">Локальные переменные в универсальных методах не могут объявляться как "Static".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntMemberShadowsGenericParam3">
<source>{0} '{1}' implicitly defines a member '{2}' which has the same name as a type parameter.</source>
<target state="translated">{0} "{1}" неявно определяет член "{2}", который имеет то же имя в качестве параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintAlreadyExists1">
<source>Constraint type '{0}' already specified for this type parameter.</source>
<target state="translated">Тип ограничения "{0}" уже указан для этого параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfacePossiblyImplTwice2">
<source>Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку это может вызвать конфликт с реализацией другого существующего интерфейса "{1}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModulesCannotBeGeneric">
<source>Modules cannot be generic.</source>
<target state="translated">Модули не могут быть общими.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericClassCannotInheritAttr">
<source>Classes that are generic or contained in a generic type cannot inherit from an attribute class.</source>
<target state="translated">Универсальные классы и классы, содержащиеся в универсальном типе, не могут наследовать от класса атрибута.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DeclaresCantBeInGeneric">
<source>'Declare' statements are not allowed in generic types or types contained in generic types.</source>
<target state="translated">'Операторы "Declare" нельзя использовать в универсальных типах или типах, содержащихся в универсальных типах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithConstraintMismatch2">
<source>'{0}' cannot override '{1}' because they differ by type parameter constraints.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по ограничениям параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsWithConstraintMismatch3">
<source>'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints.</source>
<target state="translated">"{0}" не может реализовать "{1}.{2}", поскольку они отличаются ограничениями параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OpenTypeDisallowed">
<source>Type parameters or types constructed with type parameters are not allowed in attribute arguments.</source>
<target state="translated">Параметры-типы или типы, содержащие параметры-типы, нельзя использовать в аргументах атрибутов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesInvalidOnGenericMethod">
<source>Generic methods cannot use 'Handles' clause.</source>
<target state="translated">В универсальных методах нельзя использовать предложение "Handles".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleNewConstraints">
<source>'New' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'Ограничение "New" нельзя указывать несколько раз для одного параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritForNewConstraint2">
<source>Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" объявлен как "MustInherit" и не удовлетворяет ограничению "New", накладываемому на параметр типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableNewForNewConstraint2">
<source>Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" должен иметь конструктор открытого экземпляра без параметров для удовлетворения ограничения "New" для параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGenericParamForNewConstraint2">
<source>Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">Параметр типа "{0}" должен иметь либо ограничение "New", либо ограничение "Structure" в соответствии с ограничением "New" параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewArgsDisallowedForTypeParam">
<source>Arguments cannot be passed to a 'New' used on a type parameter.</source>
<target state="translated">Аргументы нельзя передать в оператор "New" для параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRawGenericTypeImport1">
<source>Generic type '{0}' cannot be imported more than once.</source>
<target state="translated">Универсальный тип "{0}" нельзя импортировать более одного раза.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypeArgumentCountOverloadCand1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of type arguments.</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как "{0}" принимает такое число аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeArgsUnexpected">
<source>Type arguments unexpected.</source>
<target state="translated">Непредвиденные аргументы типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameSameAsMethodTypeParam1">
<source>'{0}' is already declared as a type parameter of this method.</source>
<target state="translated">"{0}" уже объявлен в качестве параметра типа этого метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamNameFunctionNameCollision">
<source>Type parameter cannot have the same name as its defining function.</source>
<target state="translated">Имя параметра-типа не может совпадать с именем определяющей его функции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstraintSyntax">
<source>Type or 'New' expected.</source>
<target state="translated">Требуется тип или "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OfExpected">
<source>'Of' required when specifying type arguments for a generic type or method.</source>
<target state="translated">'При задании аргументов-типов для универсального типа или метода, необходимо использовать "Of".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayOfRawGenericInvalid">
<source>'(' unexpected. Arrays of uninstantiated generic types are not allowed.</source>
<target state="translated">'Непредвиденная круглая скобка "(". Массивы не-экземплярных общих типов не допустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachAmbiguousIEnumerable1">
<source>'For Each' on type '{0}' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'.</source>
<target state="translated">Оператор "For Each" с типом "{0}" неоднозначен, поскольку этот тип реализует создание множества экземпляров "System.Collections.Generic.IEnumerable(Of T)".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorGenericParam1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'Операнд "IsNot" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является параметром типа без ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamQualifierDisallowed">
<source>Type parameters cannot be used as qualifiers.</source>
<target state="translated">Параметры-типы нельзя использовать в качестве определителей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingCommaOrRParen">
<source>Comma or ')' expected.</source>
<target state="translated">Требуется запятая или ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingAsCommaOrRParen">
<source>'As', comma or ')' expected.</source>
<target state="translated">'Требуется "As", запятая или ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleReferenceConstraints">
<source>'Class' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'Ограничение "Class" нельзя указывать несколько раз для одного параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleValueConstraints">
<source>'Structure' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'Ограничение "Structure" нельзя указывать несколько раз для одного параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewAndValueConstraintsCombined">
<source>'New' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'Ограничения "New" и "Structure" нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndValueConstraintsCombined">
<source>'Class' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'Ограничения Class и Structure нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraint2">
<source>Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" не удовлетворяет ограничению "Structure" для параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForRefConstraint2">
<source>Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" не удовлетворяет ограничению "Class" для параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndClassTypeConstrCombined">
<source>'Class' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'Ограничение "Class" и ограничение c указанием конкретного типа класса нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueAndClassTypeConstrCombined">
<source>'Structure' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'Ограничение "Structure" и ограничение c указанием конкретного типа класса нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectIndirect4">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'.</source>
<target state="translated">Косвенное ограничение "{0}", полученное из ограничения параметра типа "{1}", конфликтует с косвенным ограничением "{2}", полученным из ограничения параметра типа "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashDirectIndirect3">
<source>Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'.</source>
<target state="translated">Ограничение "{0}" конфликтует с косвенным ограничением "{1}", полученным из ограничения параметра типа "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectDirect3">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'.</source>
<target state="translated">Косвенное ограничение "{0}", полученное из ограничения параметра типа "{1}", конфликтует с ограничением "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycleLink2">
<source>
'{0}' is constrained to '{1}'.</source>
<target state="translated">
"{0}' ограничен значением "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycle2">
<source>Type parameter '{0}' cannot be constrained to itself: {1}</source>
<target state="translated">Параметр типа "{0}" не может быть ограничен самим собой: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamWithStructConstAsConst">
<source>Type parameter with a 'Structure' constraint cannot be used as a constraint.</source>
<target state="translated">Параметр-тип с ограничением "Structure" нельзя использовать в качестве ограничения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableDisallowedForStructConstr1">
<source>'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed.</source>
<target state="translated">'"System.Nullable" не удовлетворяет ограничению "Structure" для параметра типа "{0}". Разрешены только типы "Structure", не допускающие значения Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingDirectConstraints3">
<source>Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'.</source>
<target state="translated">Ограничение "{0}" конфликтует с ограничением "{1}", уже указанным для параметра типа "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithInterface2">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку он может совпадать с интерфейсом "{1}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseUnifiesWithInterfaces3">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с интерфейсом "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceBaseUnifiesWithBase4">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the interface '{3}' inherits for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с интерфейсом "{2}", от которого наследуется интерфейс "{3}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithBase3">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' from which the interface '{2}' inherits for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку он может совпадать с интерфейсом "{1}", от которого наследуется интерфейс "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsBaseUnifiesWithInterfaces3">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to implemented interface '{2}' for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с реализованным интерфейсом "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceBaseUnifiesWithBase4">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the implemented interface '{3}' inherits for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с интерфейсом "{2}", от которого наследуется реализованный интерфейс "{3}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceUnifiesWithBase3">
<source>Cannot implement interface '{0}' because it could be identical to interface '{1}' from which the implemented interface '{2}' inherits for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку он может совпадать с интерфейсом "{1}", от которого наследуется реализованный интерфейс "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalsCantBeStructGenericParams">
<source>Generic parameters used as optional parameter types must be class constrained.</source>
<target state="translated">Общие параметры, используемые в качестве необязательных параметров типов, должны иметь ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNullableMethod">
<source>Methods of 'System.Nullable(Of T)' cannot be used as operands of the 'AddressOf' operator.</source>
<target state="translated">Методы, принадлежащие "System.Nullable(Of T)", не могут использоваться как операнды для оператора "AddressOf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorNullable1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'Операнд "Is" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является типом, допускающим значение Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorNullable1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'Операнд "IsNot" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является типом, допускающим значение Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingTypeOutsideClass1">
<source>'{0}' cannot be declared 'Shadows' outside of a class, structure, or interface.</source>
<target state="translated">"{0}" невозможно объявить "Shadows" вне области класса, структуры или интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertySetParamCollisionWithValue">
<source>Property parameters cannot have the name 'Value'.</source>
<target state="translated">Параметры свойств не могут иметь имя "Value".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SxSIndirectRefHigherThanDirectRef3">
<source>The project currently contains references to more than one version of '{0}', a direct reference to version {2} and an indirect reference to version {1}. Change the direct reference to use version {1} (or higher) of {0}.</source>
<target state="translated">В настоящее время проект содержит ссылки на более чем одну версию "{0}", прямую ссылку на версию {2} и косвенную ссылку на версию {1}. Измените прямую ссылку на использование версии {1} (или выше) для {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReferenceStrong">
<source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source>
<target state="translated">Импортировано несколько сборок с одинаковыми удостоверениями: "{0}" и "{1}". Удалите одну из повторяющихся ссылок.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReference2">
<source>Project already has a reference to assembly '{0}'. A second reference to '{1}' cannot be added.</source>
<target state="translated">Проект уже содержит ссылку на сборку "{0}". Вторую ссылку на "{1}" добавить нельзя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCallOrIndex">
<source>Illegal call expression or index expression.</source>
<target state="translated">Некорректное выражение call или index.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictDefaultPropertyAttribute">
<source>Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'.</source>
<target state="translated">Свойство по умолчанию конфликтует с "DefaultMemberAttribute", определенным в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeUuid2">
<source>'{0}' cannot be applied because the format of the GUID '{1}' is not correct.</source>
<target state="translated">"{0}" не может использоваться из-за неверного формата GUID "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassAndReservedAttribute1">
<source>'Microsoft.VisualBasic.ComClassAttribute' and '{0}' cannot both be applied to the same class.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" и "{0}" не могут быть назначены одному классу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass2">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because its container '{1}' is not declared 'Public'.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" нельзя использовать для "{0}", так как контейнер "{1}" не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispIdZero1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property.</source>
<target state="translated">'"System.Runtime.InteropServices.DispIdAttribute" нельзя использовать для "{0}", так как "Microsoft.VisualBasic.ComClassAttribute" резервирует нулевое значение для свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispId1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero.</source>
<target state="translated">'"System.Runtime.InteropServices.DispIdAttribute" нельзя использовать для "{0}", так как "Microsoft.VisualBasic.ComClassAttribute" резервирует значения меньше нуля.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassDuplicateGuids1">
<source>'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on '{0}' cannot have the same value.</source>
<target state="translated">'Значения параметров "InterfaceId" и "EventsId" для "Microsoft.VisualBasic.ComClassAttribute" в "{0}" не могут совпадать.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassCantBeAbstract0">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute не может применяться к классу, объявленному с модификатором MustInherit.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass1">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because it is not declared 'Public'.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" нельзя использовать для "{0}", так как он не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnknownOperator">
<source>Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">В объявлении оператора должен использоваться один из следующих операторов: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateConversionCategoryUsed">
<source>'Widening' and 'Narrowing' cannot be combined.</source>
<target state="translated">'"Widening" и "Narrowing" нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorNotOverloadable">
<source>Operator is not overloadable. Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">Оператор не поддерживает перегрузку. В объявлении оператора должен использоваться один из следующих операторов: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHandles">
<source>'Handles' is not valid on operator declarations.</source>
<target state="translated">'Недопустимое использование "Handles" в объявлении оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplements">
<source>'Implements' is not valid on operator declarations.</source>
<target state="translated">'Недопустимое использование "Implements" в объявлении оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorExpected">
<source>'End Operator' expected.</source>
<target state="translated">'Требуется оператор "End Operator".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorNotAtLineStart">
<source>'End Operator' must be the first statement on a line.</source>
<target state="translated">'Оператор "End Operator" должен быть первым выражением в строке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndOperator">
<source>'End Operator' must be preceded by a matching 'Operator'.</source>
<target state="translated">'Оператору "End Operator" должен предшествовать соответствующий оператор "Operator".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitOperatorNotValid">
<source>'Exit Operator' is not valid. Use 'Return' to exit an operator.</source>
<target state="translated">'Недопустимое применение оператора Exit Operator. Используйте "Return", чтобы выйти из оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayIllegal1">
<source>'{0}' parameters cannot be declared 'ParamArray'.</source>
<target state="translated">'"Параметры {0}" не могут быть объявлены "ParamArray".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalIllegal1">
<source>'{0}' parameters cannot be declared 'Optional'.</source>
<target state="translated">"{0}" не могут быть объявлены "Optional".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBePublic">
<source>Operators must be declared 'Public'.</source>
<target state="translated">Операторы необходимо объявить как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBeShared">
<source>Operators must be declared 'Shared'.</source>
<target state="translated">Операторы необходимо объявить как "Shared".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOperatorFlags1">
<source>Operators cannot be declared '{0}'.</source>
<target state="translated">Операторы не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneParameterRequired1">
<source>Operator '{0}' must have one parameter.</source>
<target state="translated">Оператор "{0}" должен иметь один параметр.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TwoParametersRequired1">
<source>Operator '{0}' must have two parameters.</source>
<target state="translated">Оператор "{0}" должен иметь два параметра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneOrTwoParametersRequired1">
<source>Operator '{0}' must have either one or two parameters.</source>
<target state="translated">Оператор "{0}" должен иметь один или два параметра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvMustBeWideningOrNarrowing">
<source>Conversion operators must be declared either 'Widening' or 'Narrowing'.</source>
<target state="translated">Операторы преобразования должны быть объявлены как Widening или Narrowing.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorDeclaredInModule">
<source>Operators cannot be declared in modules.</source>
<target state="translated">Операторы нельзя объявлять в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSpecifierOnNonConversion1">
<source>Only conversion operators can be declared '{0}'.</source>
<target state="translated">Только операторы преобразования могут быть объявлены как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryParamMustBeContainingType1">
<source>Parameter of this unary operator must be of the containing type '{0}'.</source>
<target state="translated">Тип параметра унарного оператора должен быть вмещающим "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryParamMustBeContainingType1">
<source>At least one parameter of this binary operator must be of the containing type '{0}'.</source>
<target state="translated">По крайней мере один из параметров данного бинарного оператора должен иметь вмещающий тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvParamMustBeContainingType1">
<source>Either the parameter type or the return type of this conversion operator must be of the containing type '{0}'.</source>
<target state="translated">Тип параметр или возвращаемый тип данного оператора преобразования должны иметь вмещающий тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresBoolReturnType1">
<source>Operator '{0}' must have a return type of Boolean.</source>
<target state="translated">Оператор "{0}" должен иметь логический возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToSameType">
<source>Conversion operators cannot convert from a type to the same type.</source>
<target state="translated">Операторы преобразования не могут приводить тип к этому же типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToInterfaceType">
<source>Conversion operators cannot convert to an interface type.</source>
<target state="translated">Операторы преобразования не могут приводить к типу интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToBaseType">
<source>Conversion operators cannot convert from a type to its base type.</source>
<target state="translated">Операторы преобразования не могут приводить тип к его базовому типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToDerivedType">
<source>Conversion operators cannot convert from a type to its derived type.</source>
<target state="translated">Операторы преобразования не могут приводить тип к его производному типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToObject">
<source>Conversion operators cannot convert to Object.</source>
<target state="translated">Операторы преобразования не могут приводить к объекту.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromInterfaceType">
<source>Conversion operators cannot convert from an interface type.</source>
<target state="translated">Исходным типом оператора преобразования не может быть тип интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromBaseType">
<source>Conversion operators cannot convert from a base type.</source>
<target state="translated">Исходным типом оператора преобразования не может быть базовый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromDerivedType">
<source>Conversion operators cannot convert from a derived type.</source>
<target state="translated">Исходным типом оператора преобразования не может быть производный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromObject">
<source>Conversion operators cannot convert from Object.</source>
<target state="translated">Исходным типом оператора преобразования не может быть объект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MatchingOperatorExpected2">
<source>Matching '{0}' operator is required for '{1}'.</source>
<target state="translated">Соответствующий оператор "{0}" требуется для "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableLogicalOperator3">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression.</source>
<target state="translated">Типы возврата и параметров "{0}" должны быть "{1}" для использования в выражении "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionOperatorRequired3">
<source>Type '{0}' must define operator '{1}' to be used in a '{2}' expression.</source>
<target state="translated">Тип "{0}" должен указывать оператор "{1}" для использования в выражении "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CopyBackTypeMismatch3">
<source>Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'.</source>
<target state="translated">Не удается скопировать значение параметра "ByRef" "{0}" обратно в соответствующий аргумент, поскольку тип "{1}" невозможно преобразовать в тип "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopOperatorRequired2">
<source>Type '{0}' must define operator '{1}' to be used in a 'For' statement.</source>
<target state="translated">Тип "{0}" должен определять оператор "{1}" для использования в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopOperator2">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">Типы возврата и параметров "{0}" должны быть "{1}" для использования в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopRelOperator2">
<source>Parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">Типы параметров "{0}" должны быть "{1}" для использования в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresIntegerParameter1">
<source>Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'.</source>
<target state="translated">Оператор "{0}" должен иметь второй параметр типа "Integer" или "Integer?".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyNullableOnBoth">
<source>Nullable modifier cannot be specified on both a variable and its type.</source>
<target state="translated">Модификатор, допускающий значений NULL, не может быть одновременно применен к переменной и ее типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraintNull">
<source>Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.</source>
<target state="translated">Тип "{0}" должен быть типом значения или аргументом типа, ограниченным "Structure" для использования с "Nullable" или с модификатором "?", допускающим значение Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArrayAndNullableOnBoth">
<source>Nullable modifier '?' and array modifiers '(' and ')' cannot be specified on both a variable and its type.</source>
<target state="translated">Модификатор "?", допускающий значения NULL, и модификаторы массива "(" и ")" не могут быть применены к переменной и ее типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyTypeCharacterOnIIF">
<source>Expressions used with an 'If' expression cannot contain type characters.</source>
<target state="translated">Выражения, используемые с выражением "If", не могут содержать символы типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFName">
<source>'If' operands cannot be named arguments.</source>
<target state="translated">'Операндами "If" не могут быть именованные аргументы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion">
<source>Cannot infer a common type for the second and third operands of the 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">Не удается определить общий тип второго и третьего операнда бинарного оператора "If". Один из них должен иметь расширяющее преобразование в другой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCondTypeInIIF">
<source>First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type.</source>
<target state="translated">Первым операндом в бинарном выражении "If" должен быть тип, допускающий значения NULL, или ссылочный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCallIIF">
<source>'If' operator cannot be used in a 'Call' statement.</source>
<target state="translated">'Оператор "If" не может использоваться в операторе "Call".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyAsNewAndNullable">
<source>Nullable modifier cannot be specified in variable declarations with 'As New'.</source>
<target state="translated">Модификатор, допускающий значения NULL, не может быть задан в объявлениях переменных с "As New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion2">
<source>Cannot infer a common type for the first and second operands of the binary 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">Не удается определить общий тип первого и второго операнда бинарного оператора "If". Один из них должен иметь расширяющее преобразование в другой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNullTypeInCCExpression">
<source>Nullable types are not allowed in conditional compilation expressions.</source>
<target state="translated">Типы, допускающие значения NULL, нельзя использовать в выражениях условной компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableImplicit">
<source>Nullable modifier cannot be used with a variable whose implicit type is 'Object'.</source>
<target state="translated">Модификатор, допускающий значения NULL, не может быть использован с переменной, чьим неявным типом является "Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRuntimeHelper">
<source>Requested operation is not available because the runtime library function '{0}' is not defined.</source>
<target state="translated">Запрошенная операция недоступна, поскольку не определена функция библиотеки среды выполнения "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterGlobalNameSpace">
<source>'Global' must be followed by '.' and an identifier.</source>
<target state="translated">'За "Global" должны идти "." и идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalExpectedIdentifier">
<source>'Global' not allowed in this context; identifier expected.</source>
<target state="translated">'"Global" нельзя использовать в данном контексте; требуется идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalInHandles">
<source>'Global' not allowed in handles; local name expected.</source>
<target state="translated">'"Global" нельзя использовать в обработчиках; требуется локальное имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseIfNoMatchingIf">
<source>'ElseIf' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'Оператору "ElseIf" должен предшествовать соответствующий "If" или "ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor2">
<source>Attribute constructor has a 'ByRef' parameter of type '{0}'; cannot use constructors with byref parameters to apply the attribute.</source>
<target state="translated">Конструктор атрибута имеет параметр "ByRef" типа "{0}"; для работы с атрибутами нельзя использовать конструкторы с параметрами byref.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndUsingWithoutUsing">
<source>'End Using' must be preceded by a matching 'Using'.</source>
<target state="translated">'Оператору "End Using" должен предшествовать соответствующий ему оператор "Using".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndUsing">
<source>'Using' must end with a matching 'End Using'.</source>
<target state="translated">'Операнд "Using" должен завершаться соответствующим операндом "End Using".</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoUsing">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Using' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "Using", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingRequiresDisposePattern">
<source>'Using' operand of type '{0}' must implement 'System.IDisposable'.</source>
<target state="translated">'Операнд "Using" типа "{0}" должен реализовать "System.IDisposable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarNeedsInitializer">
<source>'Using' resource variable must have an explicit initialization.</source>
<target state="translated">'Для переменной ресурса в "Using" требуется явная инициализация.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarCantBeArray">
<source>'Using' resource variable type can not be array type.</source>
<target state="translated">'Тип переменной ресурса в операторе "Using" не может быть массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInUsing">
<source>'On Error' statements are not valid within 'Using' statements.</source>
<target state="translated">'Операторы "On Error" нельзя использовать в операторе "Using".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyNameConflictInMyCollection">
<source>'{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace.</source>
<target state="translated">"{0}" имеет то же имя, что и член, используемый для типа "{1}" в группе "My". Переименуйте тип или его вложенное пространство имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitVar">
<source>Implicit variable '{0}' is invalid because of '{1}'.</source>
<target state="translated">Неявная переменная "{0}" недопустима из-за "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectInitializerRequiresFieldName">
<source>Object initializers require a field name to initialize.</source>
<target state="translated">Инициализаторы объектов требуют для инициализации имя поля.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedFrom">
<source>'From' expected.</source>
<target state="translated">'Требуется "From".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch1">
<source>Nested function does not have the same signature as delegate '{0}'.</source>
<target state="translated">Вложенная функция не имеет одинаковой подписи с делегатом "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch2">
<source>Nested sub does not have a signature that is compatible with delegate '{0}'.</source>
<target state="translated">Подпись вложенного подчиненного несовместима с делегатом "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamQuery1">
<source>'ByRef' parameter '{0}' cannot be used in a query expression.</source>
<target state="translated">'Параметр "ByRef" "{0}" нельзя использовать в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionTreeNotSupported">
<source>Expression cannot be converted into an expression tree.</source>
<target state="translated">Выражение не может быть преобразовано в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeQuery">
<source>Instance members and 'Me' cannot be used within query expressions in structures.</source>
<target state="translated">Члены экземпляров и "Me" не могут быть использованы в выражениях запроса в структурах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InferringNonArrayType1">
<source>Variable cannot be initialized with non-array type '{0}'.</source>
<target state="translated">Не удается инициализировать переменную с типом "{0}", не являющимся массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefParamInExpressionTree">
<source>References to 'ByRef' parameters cannot be converted to an expression tree.</source>
<target state="translated">Ссылки на параметры "ByRef" не могут быть преобразованы в дерево выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAnonTypeMemberName1">
<source>Anonymous type member or property '{0}' is already declared.</source>
<target state="translated">Анонимный член типа или свойство "{0}" уже объявлены.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAnonymousTypeForExprTree">
<source>Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.</source>
<target state="translated">Не удается преобразовать анонимный тип к дереву выражения, так как свойство типа используется для инициализации другого свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftAnonymousType1">
<source>Anonymous type property '{0}' cannot be used in the definition of a lambda expression within the same initialization list.</source>
<target state="translated">Нельзя использовать свойство анонимного типа "{0}" в определении лямбда-выражения в рамках одного списка инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionOnlyAllowedOnModuleSubOrFunction">
<source>'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations.</source>
<target state="translated">'Атрибут "Extension" можно применять только к объявлениям "Module", "Sub" или "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNotInModule">
<source>Extension methods can be defined only in modules.</source>
<target state="translated">Методы расширения могут определяться только в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNoParams">
<source>Extension methods must declare at least one parameter. The first parameter specifies which type to extend.</source>
<target state="translated">Методы расширения должны объявлять не менее одного параметра. Первый параметр указывает тип для расширения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOptionalFirstArg">
<source>'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'"Optional" нельзя применять к первому параметру метода расширения. Первый параметр указывает тип для расширения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodParamArrayFirstArg">
<source>'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'"ParamArray" нельзя применять к первому параметру метода расширения. Первый параметр указывает тип для расширения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeFieldNameInference">
<source>Anonymous type member name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">Имя члена анонимного типа может быть определено только из простого или полного имени без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMemberOfAnonymousType2">
<source>'{0}' is not a member of '{1}'; it does not exist in the current context.</source>
<target state="translated">"{0}" не является членом "{1}"; он не существует в текущем контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionAttributeInvalid">
<source>The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods.</source>
<target state="translated">Нестандартная версия атрибута "System.Runtime.CompilerServices.ExtensionAttribute", обнаруженная компилятором, недопустима. Флаги использования ее атрибутов должны быть установлены таким образом, чтобы задействовать сборки, классы и методы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypePropertyOutOfOrder1">
<source>Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established.</source>
<target state="translated">Свойство члена анонимного типа "{0}" нельзя использовать для определения типа другого свойства члена, поскольку тип "{0}" еще не установлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in anonymous type declarations.</source>
<target state="translated">Символы типа не могут быть использованы в объявлении анонимного типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleLiteralDisallowsTypeChar">
<source>Type characters cannot be used in tuple literals.</source>
<target state="translated">Символы типа невозможно использовать в литералах кортежа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewWithTupleTypeSyntax">
<source>'New' cannot be used with tuple type. Use a tuple literal expression instead.</source>
<target state="translated">'"New" невозможно использовать с типом кортежа. Вместо этого примените литеральное выражение кортежа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct">
<source>Predefined type '{0}' must be a structure.</source>
<target state="translated">Предопределенный тип "{0}" должен быть структурой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodUncallable1">
<source>Extension method '{0}' has type constraints that can never be satisfied.</source>
<target state="translated">Метод расширения "{0}" содержит ограничения типа, которые не могут быть соблюдены.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate3">
<source>
Extension method '{0}' defined in '{1}': {2}</source>
<target state="translated">
Метод расширения "{0}" определен в "{1}": {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatch">
<source>Method does not have a signature compatible with the delegate.</source>
<target state="translated">Метод не имеет сигнатуры, совместимой с сигнатурой делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingTypeInferenceFails">
<source>Type arguments could not be inferred from the delegate.</source>
<target state="translated">Аргументы-типы не могут быть определены из делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs">
<source>Too many arguments.</source>
<target state="translated">Слишком много аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted1">
<source>Parameter '{0}' already has a matching omitted argument.</source>
<target state="translated">Параметр "{0}" уже имеет соответствующий пропущенный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice1">
<source>Parameter '{0}' already has a matching argument.</source>
<target state="translated">Параметр "{0}" уже имеет соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound1">
<source>'{0}' is not a method parameter.</source>
<target state="translated">"{0}" не является параметром метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument1">
<source>Argument not specified for parameter '{0}'.</source>
<target state="translated">Аргумент, не указанный для параметра "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam1">
<source>Type parameter '{0}' cannot be inferred.</source>
<target state="translated">Невозможно получить параметр типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate2">
<source>
Extension method '{0}' defined in '{1}'.</source>
<target state="translated">
Метод расширения "{0}" определен в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNeedField">
<source>Anonymous type must contain at least one member.</source>
<target state="translated">Анонимный тип должен содержать по крайней мере один член.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNameWithoutPeriod">
<source>Anonymous type member name must be preceded by a period.</source>
<target state="translated">Имени члена анонимного типа должна предшествовать точка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeExpectedIdentifier">
<source>Identifier expected, preceded with a period.</source>
<target state="translated">Требуется идентификатор, перед которым должна стоять точка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs2">
<source>Too many arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">Слишком много аргументов в методе расширения "{0}", определенном в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted3">
<source>Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument.</source>
<target state="translated">Параметр "{0}" метода расширения "{1}", заданного в "{2}", уже имеет соответствующий пропущенный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice3">
<source>Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument.</source>
<target state="translated">Параметр "{0}" метода расширения "{1}", заданного в "{2}", уже имеет соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound3">
<source>'{0}' is not a parameter of extension method '{1}' defined in '{2}'.</source>
<target state="translated">"{0}" не является параметром метода расширения "{1}", определенного в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument3">
<source>Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'.</source>
<target state="translated">Аргумент, не указанный для параметра "{0}" метода расширения "{1}", определен в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam3">
<source>Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred.</source>
<target state="translated">Невозможно получить параметр типа "{0}" для метода расширения "{1}", определенного в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments2">
<source>Too few type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">Слишком мало аргументов типа в методе расширения "{0}", определенном в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments2">
<source>Too many type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">Слишком много аргументов типа в методе расширения "{0}", определенного в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInOrEq">
<source>'In' or '=' expected.</source>
<target state="translated">'Требуется "In" или "=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQueryableSource">
<source>Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.</source>
<target state="translated">Выражение типа "{0}" недоступно для запроса. Убедитесь, что не пропущена ссылка на сборку и (или) импорт пространства имен для поставщика LINQ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryOperatorNotFound">
<source>Definition of method '{0}' is not accessible in this context.</source>
<target state="translated">Определение метода "{0}" недоступно в этом контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseOnErrorGotoWithClosure">
<source>Method cannot contain both a '{0}' statement and a definition of a variable that is used in a lambda or query expression.</source>
<target state="translated">Метод не может одновременно содержать оператор "{0}" и определение переменной, которая используется в лямбда-выражении или выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotGotoNonScopeBlocksWithClosure">
<source>'{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression.</source>
<target state="translated">"{0}{1}" является недопустимым, поскольку "{2}" находится внутри области, которая определяет переменную, используемую в лямбда-выражении или выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeQuery">
<source>Instance of restricted type '{0}' cannot be used in a query expression.</source>
<target state="translated">Экземпляр ограниченного типа "{0}" нельзя использовать в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeFieldNameInference">
<source>Range variable name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">Имя переменной диапазона может выводиться только из простого или проверенного имени без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryDuplicateAnonTypeMemberName1">
<source>Range variable '{0}' is already declared.</source>
<target state="translated">Переменная диапазона "{0}" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in range variable declarations.</source>
<target state="translated">Не удается использовать символы типа в объявлениях переменной диапазона.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyInClosure">
<source>'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.</source>
<target state="translated">'Доступной только для чтения переменной (ReadOnly) нельзя присваивать значение в лямбда-выражении внутри конструктора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoMultiDimArrayCreation">
<source>Multi-dimensional array cannot be converted to an expression tree.</source>
<target state="translated">Многомерный массив не может быть преобразован в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoLateBind">
<source>Late binding operations cannot be converted to an expression tree.</source>
<target state="translated">Операции позднего связывания не могут быть преобразованы в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedBy">
<source>'By' expected.</source>
<target state="translated">'Требуется "By".</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryInvalidControlVariableName1">
<source>Range variable name cannot match the name of a member of the 'Object' class.</source>
<target state="translated">Имя переменной диапазона не может совпадать с именем члена класса "Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIn">
<source>'In' expected.</source>
<target state="translated">'Требуется "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryNameNotDeclared">
<source>Name '{0}' is either not declared or not in the current scope.</source>
<target state="translated">Имя "{0}" не объявлено или не существует в текущей области.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedFunctionArgumentNarrowing3">
<source>Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">Возвращаемый тип вложенной функции соответствующего параметра "{0}" сужается с "{1}" к "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonTypeFieldXMLNameInference">
<source>Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">Имя члена анонимного типа не может быть определено из идентификатора XML, который не является допустимым идентификатором языка Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonTypeFieldXMLNameInference">
<source>Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">Имя переменной диапазона не может быть определено из идентификатора XML, который не является допустимым идентификатором Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInto">
<source>'Into' expected.</source>
<target state="translated">'Требуется "Into".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnAggregation">
<source>Aggregate function name cannot be used with a type character.</source>
<target state="translated">Имя агрегатной функции не может использоваться вместе с символом типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOn">
<source>'On' expected.</source>
<target state="translated">'Требуется "On".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEquals">
<source>'Equals' expected.</source>
<target state="translated">'Требуется "Equals".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAnd">
<source>'And' expected.</source>
<target state="translated">'Требуется "And".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsTypeMismatch">
<source>'Equals' cannot compare a value of type '{0}' with a value of type '{1}'.</source>
<target state="translated">'"Equals" не может сравнить значение типа "{0}" со значением типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsOperandIsBad">
<source>You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) {0} must appear on one side of the 'Equals' operator, and range variable(s) {1} must appear on the other.</source>
<target state="translated">С обеих сторон оператора "Equals" должны присутствовать ссылки хотя бы на одну переменную диапазона. Переменные диапазона {0} должны располагаться с одной стороны оператора "Equals", а переменные диапазона {1} — с другой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotDelegate1">
<source>Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">Лямбда-выражение не может быть преобразовано в "{0}", поскольку "{0}" не является типом делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotCreatableDelegate1">
<source>Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">Лямбда-выражение не может быть преобразовано в "{0}", поскольку тип "{0}" объявлен как "MustInherit" и не может быть создан.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotInferNullableForVariable1">
<source>A nullable type cannot be inferred for variable '{0}'.</source>
<target state="translated">Тип, допускающий значение Null, не может быть определен для переменной "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableTypeInferenceNotSupported">
<source>Nullable type inference is not supported in this context.</source>
<target state="translated">Определение типа, допускающего значения NULL, не поддерживается в текущем контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedJoin">
<source>'Join' expected.</source>
<target state="translated">'Требуется "Join".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableParameterMustSpecifyType">
<source>Nullable parameters must specify a type.</source>
<target state="translated">Параметры, допускающие значения NULL, должны задавать тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal2">
<source>Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">Переменная диапазона "{0}" скрывает переменную во внешнем блоке, ранее определенную переменную диапазона или неявно объявленную переменную в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdasCannotHaveAttributes">
<source>Attributes cannot be applied to parameters of lambda expressions.</source>
<target state="translated">Атрибуты не могут быть применены к параметрам лямбда-выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaInSelectCaseExpr">
<source>Lambda expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">Лямбда-выражения являются недопустимыми в первом выражении инструкции "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfInSelectCaseExpr">
<source>'AddressOf' expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">'Выражения "AddressOf" недопустимы в первом выражении оператора "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableCharNotSupported">
<source>The '?' character cannot be used here.</source>
<target state="translated">Символ "?" нельзя употреблять здесь.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeLambda">
<source>Instance members and 'Me' cannot be used within a lambda expression in structures.</source>
<target state="translated">Члены экземпляров и "Me" не могут быть использованы внутри лямбда-выражений в структурах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamLambda1">
<source>'ByRef' parameter '{0}' cannot be used in a lambda expression.</source>
<target state="translated">'Параметр "ByRef" "{0}" нельзя использовать в лямбда-выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeLambda">
<source>Instance of restricted type '{0}' cannot be used in a lambda expression.</source>
<target state="translated">Экземпляр ограниченного типа "{0}" нельзя использовать в лямбда-выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaParamShadowLocal1">
<source>Lambda parameter '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">Лямбда-параметр "{0}" скрывает переменную во внешнем блоке, ранее определенную переменную диапазона или неявно объявленную переменную в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObjectLambda">
<source>Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.</source>
<target state="translated">Параметр "Strict On" требует, чтобы все лямбда-выражения были объявлены с использованием предложения "As" в случае, если тип не может быть определен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyParamsOnLambdaParamNoType">
<source>Array modifiers cannot be specified on lambda expression parameter name. They must be specified on its type.</source>
<target state="translated">Модификаторы массива не могут указываться в имени параметра лямбда-выражения. Они должны задаваться по его типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов, так как возможны несколько типов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, так как возможен более чем один тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов, так как возможен более чем один тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов, так как возможны несколько типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, так как возможен более чем один тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов, так как возможен более чем один тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типов не могут быть определены из этих аргументов, так как они не могут быть приведены к одному типу. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в {1}", не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">Типы данных параметров типов не могут быть определены из этих аргументов, так как они не могут быть приведены к одному типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в {1}", не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff2">
<source>Option Strict On does not allow narrowing in implicit type conversions between method '{0}' and delegate '{1}'.</source>
<target state="translated">Параметр Strict On не разрешает сужение в преобразованиях явного типа между методом '{0}' и делегатом '{1}'.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleReturnTypeOfMember2">
<source>'{0}' is not accessible in this context because the return type is not accessible.</source>
<target state="translated">"{0}" в этом контексте недоступен, так как недоступен возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifierOrGroup">
<source>'Group' or an identifier expected.</source>
<target state="translated">'Требуется "Group" или идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedGroup">
<source>'Group' not allowed in this context; identifier expected.</source>
<target state="translated">'В данном контексте "Group" не разрешено; ожидался идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff3">
<source>Option Strict On does not allow narrowing in implicit type conversions between extension method '{0}' defined in '{2}' and delegate '{1}'.</source>
<target state="translated">Параметр Strict On не разрешает сужение в преобразованиях явного типа между методом расширения "{0}", определенным в "{2}", и делегатом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible3">
<source>Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">Метод расширения "{0}", определенный в "{2}", не имеет сигнатуры, совместимой с делегатом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing2">
<source>Argument matching parameter '{0}' narrows to '{1}'.</source>
<target state="translated">Аргумент, соответствующий параметру "{0}", сужен до "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate1">
<source>
{0}</source>
<target state="translated">
{0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyInitializedInStructure">
<source>Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.</source>
<target state="translated">Автоматически реализуемые свойства, содержащиеся в Структурах не могут иметь инициализатор, кроме случаев, когда они помечены как "Общие".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsElements">
<source>XML elements cannot be selected from type '{0}'.</source>
<target state="translated">Невозможно выбрать элементы XML из типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsAttributes">
<source>XML attributes cannot be selected from type '{0}'.</source>
<target state="translated">Невозможно выбрать атрибуты XML из типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsDescendants">
<source>XML descendant elements cannot be selected from type '{0}'.</source>
<target state="translated">Невозможно выбрать элементы-потомки XML из типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric2">
<source>Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments.</source>
<target state="translated">Метод расширения "{0}", определенный в "{1}", не является универсальным (или не имеет параметров свободного типа) и поэтому не может иметь аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodCannotBeLateBound">
<source>Late-bound extension methods are not supported.</source>
<target state="translated">Методы расширения с поздним связыванием не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceArrayRankMismatch1">
<source>Cannot infer a data type for '{0}' because the array dimensions do not match.</source>
<target state="translated">Невозможно получить тип данных для "{0}", так как размеры массива не совпадают.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryStrictDisallowImplicitObject">
<source>Type of the range variable cannot be inferred, and late binding is not allowed with Option Strict on. Use an 'As' clause to specify the type.</source>
<target state="translated">Тип переменной диапазона не может быть определен, и с Option Strict On поздняя привязка не допускается. Используйте предложение "As", чтобы указать тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedInterfaceWithGeneric">
<source>Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.</source>
<target state="translated">Тип "{0}" нельзя внедрить, поскольку он имеет универсальный аргумент. Попробуйте отключить внедрение типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseGenericTypeAcrossAssemblyBoundaries">
<source>Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source>
<target state="translated">Тип "{0}" нельзя использовать за границами сборки, так как он имеет аргумент универсального типа, являющийся внедренным типом взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">"{0}" является устаревшим: "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2_Title">
<source>Type or member is obsolete</source>
<target state="translated">Тип или член устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4">
<source>{0} '{1}' shadows an overloadable member declared in the base {2} '{3}'. If you want to overload the base method, this method must be declared 'Overloads'.</source>
<target state="translated">{0} "{1}" затеняет переопределяемый член, объявленный в базе {2} "{3}". Если вы хотите перегрузить базовый метод, этот метод должен быть объявлен "Overloads".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4_Title">
<source>Member shadows an overloadable member declared in the base type</source>
<target state="translated">Член затемняет перегружаемый член, объявленный в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5">
<source>{0} '{1}' conflicts with {2} '{1}' in the base {3} '{4}' and should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" конфликтует с "{2}" в базе {1} "{3}" {4} и должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5_Title">
<source>Member conflicts with member in the base type and should be declared 'Shadows'</source>
<target state="translated">Член конфликтует с членом в базовом типе и должен быть объявлен как Shadows</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2">
<source>{0} '{1}' shadows an overridable method in the base {2} '{3}'. To override the base method, this method must be declared 'Overrides'.</source>
<target state="translated">{0} "{1}" затеняет переопределяемый метод в базе {2} "{3}". Для переопределения базового метода, этот метод должен быть объявлен "Overrides".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2_Title">
<source>Member shadows an overridable method in the base type</source>
<target state="translated">Член затемняет переопределяемый метод в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4">
<source>Default property '{0}' conflicts with the default property '{1}' in the base {2} '{3}'. '{0}' will be the default property. '{0}' should be declared 'Shadows'.</source>
<target state="translated">Свойство по умолчанию "{0}" противоречит свойству по умолчанию "{1}" в базе {2} "{3}". "{0}" будет свойством по умолчанию. "{0}" следует объявить "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4_Title">
<source>Default property conflicts with the default property in the base type</source>
<target state="translated">Свойство по умолчанию конфликтует со свойством по умолчанию в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">"{0}" является устаревшим.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1_Title">
<source>Type or member is obsolete</source>
<target state="translated">Тип или член устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0">
<source>Possible problem detected while building assembly: {0}</source>
<target state="translated">При создании сборки обнаружена потенциальная проблема: {0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">Обнаружена возможная проблема при создании сборки</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1">
<source>Possible problem detected while building assembly '{0}': {1}</source>
<target state="translated">При создании сборки обнаружена потенциальная проблема "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">Обнаружена возможная проблема при создании сборки</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class '{0}' but '{0}' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" указан для класса "{0}", но "{0}" не имеет открытых членов, которые могут быть использованы через COM; поэтому COM-интерфейсы не создаются.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class but class has no public members that can be exposed to COM</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute указан для класса, но класс не содержит открытые члены, которые можно предоставить для COM</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member in the base {3} '{4}', and so the {0} should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", что конфликтует с членом в базе {3} "{4}", поэтому {0} должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5_Title">
<source>Property or event implicitly declares type or member that conflicts with a member in the base type</source>
<target state="translated">Свойство или событие неявно объявляет тип или член, который конфликтует с членом в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in the base {4} '{5}' and should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" конфликтует с членом, который был неявно объявлен для {2} "{3}" в базе {4} "{5}" и должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6_Title">
<source>Member conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">Член конфликтует с членом, неявно объявленным для свойства или события в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member implicitly declared for {3} '{4}' in the base {5} '{6}'. {0} should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", что конфликтует с членом, который был неявно объявлен для {3} "{4}" в базе {5} "{6}". {0} должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7_Title">
<source>Property or event implicitly declares member, which conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">Свойство или событие неявно объявляет член, который конфликтует с членом, неявно объявленным для свойства или события в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело: '{2}'.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3_Title">
<source>Property accessor is obsolete</source>
<target state="translated">Метод доступа свойства устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2_Title">
<source>Property accessor is obsolete</source>
<target state="translated">Метод доступа свойства устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1">
<source>Type of member '{0}' is not CLS-compliant.</source>
<target state="translated">Тип члена "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1_Title">
<source>Type of member is not CLS-compliant</source>
<target state="translated">Тип члена несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant.</source>
<target state="translated">"{0}" несовместим с CLS, так как унаследован от "{1}", который несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because it derives from base type that is not CLS-compliant</source>
<target state="translated">Тип несовместим с CLS, так как он наследуется от базового типа, который несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1">
<source>Return type of function '{0}' is not CLS-compliant.</source>
<target state="translated">Тип возвращаемого значения "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1_Title">
<source>Return type of function is not CLS-compliant</source>
<target state="translated">Тип возвращаемого значения функции несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1">
<source>Type of parameter '{0}' is not CLS-compliant.</source>
<target state="translated">Тип параметра "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1_Title">
<source>Type of parameter is not CLS-compliant</source>
<target state="translated">Тип параметра несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant.</source>
<target state="translated">"{0}" несовместим с CLS, так как унаследованный интерфейс "{1}" несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because the interface it inherits from is not CLS-compliant</source>
<target state="translated">Тип несовместим с CLS, так как наследуемый интерфейс несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3">
<source>{0} '{1}' cannot be marked CLS-compliant because its containing type '{2}' is not CLS-compliant.</source>
<target state="translated">{0} "{1}" не может быть помечен как совместимый с CLS, так как тип, который он содержит "{2}", несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3_Title">
<source>Member cannot be marked CLS-compliant because its containing type is not CLS-compliant</source>
<target state="translated">Член невозможно пометить как совместимый с CLS, так как его содержащий тип несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1">
<source>Name '{0}' is not CLS-compliant.</source>
<target state="translated">Тип "{0}" не совместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1_Title">
<source>Name is not CLS-compliant</source>
<target state="translated">Имя несовместимо с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1">
<source>Underlying type '{0}' of Enum is not CLS-compliant.</source>
<target state="translated">Базовый тип "{0}" Enum не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1_Title">
<source>Underlying type of Enum is not CLS-compliant</source>
<target state="translated">Базовый тип перечисления несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1">
<source>Non CLS-compliant '{0}' is not allowed in a CLS-compliant interface.</source>
<target state="translated">Не допускается "{0}", несовместимый с CLS, для интерфейса, совместимого с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1_Title">
<source>Non CLS-compliant member is not allowed in a CLS-compliant interface</source>
<target state="translated">Член, несовместимый с CLS, запрещено использовать в интерфейсе, совместимом с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type '{0}'.</source>
<target state="translated">В типе "{0}", совместимом с CLS, запрещено использовать член MustOverride, несовместимый с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1_Title">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type</source>
<target state="translated">Член MustOverride, несовместимый с CLS, запрещено использовать в типе, совместимом с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2">
<source>'{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types.</source>
<target state="translated">"{0}" несовместим с CLS, так как перегружает "{1}", который отличается от него только массивом типов параметра массива или рангом типов параметра массива.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2_Title">
<source>Method is not CLS-compliant because it overloads method which differs from it only by array of array parameter types or by the rank of the array parameter types</source>
<target state="translated">Метод несовместим с CLS, так как он перегружает метод, который отличается от него только массивом типов параметров массива или рангом типов параметров массива</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1">
<source>Root namespace '{0}' is not CLS-compliant.</source>
<target state="translated">Корневое пространство имен "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1_Title">
<source>Root namespace is not CLS-compliant</source>
<target state="translated">Корневое пространство имен несовместимо с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2">
<source>Name '{0}' in the root namespace '{1}' is not CLS-compliant.</source>
<target state="translated">Имя "{0}" в корневом пространстве имен "{1}" не совместимо с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2_Title">
<source>Part of the root namespace is not CLS-compliant</source>
<target state="translated">Часть корневого пространства имен несовместима с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1">
<source>Generic parameter constraint type '{0}' is not CLS-compliant.</source>
<target state="translated">Универсальный тип параметра ограничения "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1_Title">
<source>Generic parameter constraint type is not CLS-compliant</source>
<target state="translated">Тип ограничения общего параметра несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1">
<source>Type '{0}' is not CLS-compliant.</source>
<target state="translated">Тип "{0}" не совместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1_Title">
<source>Type is not CLS-compliant</source>
<target state="translated">Тип несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1">
<source>Type of optional value for optional parameter '{0}' is not CLS-compliant.</source>
<target state="translated">Тип необязательного значения для необязательного параметра "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1_Title">
<source>Type of optional value for optional parameter is not CLS-compliant</source>
<target state="translated">Тип дополнительного значения для дополнительного параметра несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.</source>
<target state="translated">Атрибут System.CLSCompliantAttribute нельзя применять к свойствам "Get" или "Set".</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet_Title">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'</source>
<target state="translated">Атрибут System.CLSCompliantAttribute невозможно применить к свойствам Get или Set</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6">
<source>{0} '{1}' and partial {2} '{3}' conflict in {4} '{5}', but are being merged because one of them is declared partial.</source>
<target state="translated">{0} "{1}" и частичный {2} "{3}" конфликтуют в {4} "{5}", но объединены, так как один из них объявлен разделяемым.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6_Title">
<source>Type and partial type conflict, but are being merged because one of them is declared partial</source>
<target state="translated">Тип и разделяемый тип конфликтуют, но выполняется их объединение, так как один из них объявлен разделяемым</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1">
<source>Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.</source>
<target state="translated">Параметр типа "{0}" имеет то же имя в качестве параметра типа вмещающего типа. Параметр типа вмещающего типа будет затенен.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1_Title">
<source>Type parameter has the same name as a type parameter of an enclosing type</source>
<target state="translated">Параметр типа имеет то же имя, что и параметр типа, в который он входит</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1">
<source>Could not find standard library '{0}'.</source>
<target state="translated">Не удалось найти стандартную библиотеку "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1_Title">
<source>Could not find standard library</source>
<target state="translated">Не удалось найти стандартную библиотеку</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2">
<source>Delegate type '{0}' of event '{1}' is not CLS-compliant.</source>
<target state="translated">Тип делегата "{0}" события "{1}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2_Title">
<source>Delegate type of event is not CLS-compliant</source>
<target state="translated">Тип делегата события несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate.</source>
<target state="translated">Атрибут System.Diagnostics.DebuggerHiddenAttribute не влияет на методы "Get" или "Set", когда применяется к определению свойства. Применяйте атрибут непосредственно к соответствующим методам "Get" и "Set".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties_Title">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition</source>
<target state="translated">Атрибут System.Diagnostics.DebuggerHiddenAttribute не влияет на Get или Set при применении к определению свойств</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange">
<source>Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound.</source>
<target state="translated">Указан недопустимый диапазон для оператора "Case". Убедитесь, что нижняя граница меньше или равна верхней границе.</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange_Title">
<source>Range specified for 'Case' statement is not valid</source>
<target state="translated">Диапазон, указанный для оператора Case, недопустим</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3">
<source>'{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant.</source>
<target state="translated">"{0}" метод для события "{1}" не может быть помечен как совместимый с CLS, потому что тип, который он содержит, "{2}" несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3_Title">
<source>AddHandler or RemoveHandler method for event cannot be marked CLS compliant because its containing type is not CLS compliant</source>
<target state="translated">Метод AddHandler или RemoveHandler для события невозможно пометить как совместимый с CLS, так как его содержащий тип несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2">
<source>'{0}' in designer-generated type '{1}' should call InitializeComponent method.</source>
<target state="translated">"{0}" в типе, созданном конструктором "{1}", должен вызывать метод InitializeComponent.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2_Title">
<source>Constructor in designer-generated type should call InitializeComponent method</source>
<target state="translated">Конструктор в типе, созданном конструктором, должен вызывать метод InitializeComponent</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3">
<source>Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'.</source>
<target state="translated">Регистр пространства имен "{0}" не соответствует регистру имени пространства имен "{1}" в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3_Title">
<source>Casing of namespace name does not match</source>
<target state="translated">Регистр имен для пространств имен не соответствует требованиям</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1">
<source>Namespace or type specified in the Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">Пространство имен или тип, указанный в Imports "{0}", не содержит открытый член или не может быть найден. Убедитесь, что пространство имен или тип заданы и содержат хотя бы один открытый член. Убедитесь, что импортируемое имя элемента не использует псевдонимы.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1_Title">
<source>Namespace or type specified in Imports statement doesn't contain any public member or cannot be found</source>
<target state="translated">Пространство имен или тип, указанный в операторе Imports, не содержит открытый член, или невозможно найти пространство имен или тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1">
<source>Namespace or type specified in the project-level Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">Пространство имен или тип, указанные в операторе Imports "{0}" проекта, не содержат открытые члены или не могут быть найдены. Убедитесь, что пространство имен или тип определены и содержат хотя бы один открытый член. Убедитесь, что имя импортируемого элемента не имеет псевдонимов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1_Title">
<source>Namespace or type imported at project level doesn't contain any public member or cannot be found</source>
<target state="translated">Пространство имен или тип, импортированный на уровне проекта, не содержит открытый член, или невозможно найти пространство имен или тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2">
<source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly from assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source>
<target state="translated">Была создана ссылка на внедренную сборку взаимодействия "{0}", так как существует косвенная ссылка на эту сборку, созданная сборкой "{1}". Рассмотрите возможность изменения свойства "Внедрять типы взаимодействия" в любой сборке.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2_Title">
<source>A reference was created to embedded interop assembly because of an indirect reference to that assembly</source>
<target state="translated">Была создана ссылка на внедренную сборку взаимодействия из-за непрямой ссылки на эту сборку</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">Класс должен объявлять Sub New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший: "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">Класс должен объявлять Sub New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">Первый оператор Sub New должен быть явным вызовом в MyBase.New или MyClass.New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший: "{3}"</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">Первый оператор Sub New должен быть явным вызовом в MyBase.New или MyClass.New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator">
<source>Operator without an 'As' clause; type of Object assumed.</source>
<target state="translated">Оператор без предложения "As"; предполагаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator_Title">
<source>Operator without an 'As' clause</source>
<target state="translated">Оператор без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2">
<source>Type arguments inferred for method '{0}' result in the following warnings :{1}</source>
<target state="translated">Тип аргументов, выведенных для метода "{0}", выдает следующие предупреждения: {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2_Title">
<source>Type arguments inferred for method result in warnings</source>
<target state="translated">Аргументы типов, определяемые для результата метода в предупреждениях</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations.</source>
<target state="translated">Атрибут "Conditional" допустим только в объявлениях "Sub".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction_Title">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations</source>
<target state="translated">Атрибут Conditional допустим только в объявлениях Sub</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute">
<source>Use command-line option '{0}' or appropriate project settings instead of '{1}'.</source>
<target state="translated">Используйте параметр командной строки "{0}" или подходящие параметры проекта вместо "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute_Title">
<source>Use command-line option /keyfile, /keycontainer, or /delaysign instead of AssemblyKeyFileAttribute, AssemblyKeyNameAttribute, or AssemblyDelaySignAttribute</source>
<target state="translated">Используйте параметр командной строки /keyfile, /keycontainer или /delaysign вместо AssemblyKeyFileAttribute, AssemblyKeyNameAttribute или AssemblyDelaySignAttribute</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall">
<source>Statement recursively calls the containing '{0}' for event '{1}'.</source>
<target state="translated">Выражение рекурсивно вызывает содержащийся "{0}" для события "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall_Title">
<source>Statement recursively calls the event's containing AddHandler</source>
<target state="translated">Оператор рекурсивно вызывает содержащий его AddHandler события</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack">
<source>Implicit conversion from '{1}' to '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">Неявное преобразование "{1}" в "{2}" при копировании значения параметра "ByRef" "{0}" обратно в соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack_Title">
<source>Implicit conversion in copying the value of 'ByRef' parameter back to the matching argument</source>
<target state="translated">Неявное преобразование при выполнении обратного копирования значения параметра ByRef в соответствующий аргумент</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2">
<source>{0} '{1}' conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" конфликтует с другими членами с тем же именем в иерархии наследования и должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2_Title">
<source>Method conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'</source>
<target state="translated">Метод конфликтует с другими членами того же имени в иерархии наследования, поэтому должен быть объявлен как Shadows</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall">
<source>Expression recursively calls the containing Operator '{0}'.</source>
<target state="translated">Выражение рекурсивно вызывает содержащийся оператор "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall_Title">
<source>Expression recursively calls the containing Operator</source>
<target state="translated">Выражение рекурсивно вызывает содержащий его оператор</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2">
<source>Implicit conversion from '{0}' to '{1}'.</source>
<target state="translated">Неявное преобразование "{0}" в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2_Title">
<source>Implicit conversion</source>
<target state="translated">Неявное преобразование</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing">
<source>Local variable '{0}' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">Локальная переменная "{0}" доступна только для чтения и ее тип является структурой. Вызов членов или передача ByRef не меняет ее содержания и может привести к непредвиденным результатам. Попробуйте объявить переменную за пределами блока "Using".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type is a structure</source>
<target state="translated">Локальная переменная, объявленная оператором Using, доступна только для чтения и имеет тип структуры</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing">
<source>Local variable '{0}' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">Локальная переменная "{0}" доступна только для чтения. Если ее тип является структурой, вызов членов или передача ByRef не меняет ее содержания и может привести к непредвиденным результатам. Попробуйте объявить переменную за пределами блока "Using".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type may be a structure</source>
<target state="translated">Локальная переменная, объявленная оператором Using, доступна только для чтения и может иметь тип структуры</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1_Title">
<source>Implicit conversion</source>
<target state="translated">Неявное преобразование</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution">
<source>Late bound resolution; runtime errors could occur.</source>
<target state="translated">Позднее разрешение перегруженных объектов; возможна ошибка времени выполнения.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution_Title">
<source>Late bound resolution</source>
<target state="translated">Динамическое разрешение границ</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1">
<source>Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity.</source>
<target state="translated">Операнды типа Object, используемые для оператора "{0}"; используется оператор "Is", чтобы проверить идентификатор объекта.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">В операторе используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2">
<source>Operands of type Object used for operator '{0}'; runtime errors could occur.</source>
<target state="translated">Операнды типа Object, используемые для оператора "{0}"; возможна ошибка выполнения.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">В операторе используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">Объявление переменной без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1_Title">
<source>Function without an 'As' clause</source>
<target state="translated">Функция без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1_Title">
<source>Property without an 'As' clause</source>
<target state="translated">Свойство без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl">
<source>Variable declaration without an 'As' clause; type of Object assumed.</source>
<target state="translated">Переменная объявлена без предложения "As"; предполагаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">Объявление переменной без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction">
<source>Function without an 'As' clause; return type of Object assumed.</source>
<target state="translated">Функция без предложения "As"; предполагаемый возвращаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction_Title">
<source>Function without an 'As' clause</source>
<target state="translated">Функция без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty">
<source>Property without an 'As' clause; type of Object assumed.</source>
<target state="translated">Свойство без предложения "As"; предполагаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty_Title">
<source>Property without an 'As' clause</source>
<target state="translated">Свойство без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal">
<source>Unused local variable: '{0}'.</source>
<target state="translated">Неиспользованная локальная переменная: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal_Title">
<source>Unused local variable</source>
<target state="translated">Неиспользуемая локальная переменная</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance">
<source>Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.</source>
<target state="translated">Доступ к общему члену, члену-константе, члену-перечислению или вложенному типу через экземпляр; заданное выражение не будет вычислено.</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance_Title">
<source>Access of shared member, constant member, enum member or nested type through an instance</source>
<target state="translated">Доступ общего члена, члена константы, члена перечисления или вложенного типа с помощью экземпляра</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall">
<source>Expression recursively calls the containing property '{0}'.</source>
<target state="translated">Выражение рекурсивно вызывает содержащееся свойство "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall_Title">
<source>Expression recursively calls the containing property</source>
<target state="translated">Выражение рекурсивно вызывает содержащее его свойство</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch">
<source>'Catch' block never reached, because '{0}' inherits from '{1}'.</source>
<target state="translated">'Невозможно достичь блока Catch, поскольку "{0}" наследуется от "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch_Title">
<source>'Catch' block never reached; exception type's base type handled above in the same Try statement</source>
<target state="translated">'Блок Catch недоступен; базовый тип типа исключения обрабатывается выше в том же операторе Try</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef">
<source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">Переменная "{0}" передается по ссылке, прежде чем ей присваивается значение. Во время выполнения может появиться пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">Переменная передана ссылкой до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch">
<source>'Catch' block never reached; '{0}' handled above in the same Try statement.</source>
<target state="translated">'Невозможно достичь блок "Catch"; "{0}" обрабатывается выше в том же операторе Try.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch_Title">
<source>'Catch' block never reached; exception type handled above in the same Try statement</source>
<target state="translated">'Блок Catch недоступен; обработанный выше тип исключения находится в том же операторе Try</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not">
<source>Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity.</source>
<target state="translated">Операнды типа Object, используемые для оператора "{0}"; используется оператор "IsNot", чтобы проверить идентификатор объекта.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not_Title">
<source>Operands of type Object used for operator <></source>
<target state="translated">В операторе <> используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum">
<source>Bad checksum value, non hex digits or odd number of hex digits.</source>
<target state="translated">Некорректное значение контрольной суммы: не шестнадцатеричный формат или нечетное количество шестнадцатеричных цифр.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum_Title">
<source>Bad checksum value, non hex digits or odd number of hex digits</source>
<target state="translated">Некорректное значение контрольной суммы: не шестнадцатеричный формат или нечетное количество шестнадцатеричных цифр</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum">
<source>File name already declared with a different GUID and checksum value.</source>
<target state="translated">Имя файла уже объявлено с другим GUID и контрольной суммой.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum_Title">
<source>File name already declared with a different GUID and checksum value</source>
<target state="translated">Имя файла уже объявлено с другим GUID и контрольной суммой</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum">
<source>Bad GUID format.</source>
<target state="translated">Недействительный формат GUID.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum_Title">
<source>Bad GUID format</source>
<target state="translated">Недействительный формат GUID</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur.</source>
<target state="translated">В выражениях для операторов "Select", "Case" используются операнды типа Object; возможна ошибка времени выполнения.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase_Title">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements</source>
<target state="translated">В выражениях для операторов Select и Case используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.</source>
<target state="translated">Это выражение всегда будет иметь результат "Nothing" (из-за распространения значения Null от оператора равенства). Для проверки на значение NULL рекомендуется использовать "Is Nothing".</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">Вычисление этого выражения всегда будет иметь значение Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'.</source>
<target state="translated">Это выражение всегда будет иметь результат "Nothing" (из-за распространения значения Null от оператора равенства). Для проверки на значение NULL рекомендуется использовать "IsNot Nothing".</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">Вычисление этого выражения всегда будет иметь значение Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst">
<source>Unused local constant: '{0}'.</source>
<target state="translated">Неиспользованная локальная константа: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst_Title">
<source>Unused local constant</source>
<target state="translated">Неиспользуемая локальная константа</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class '{0}' implicitly declares {1} '{2}', which conflicts with a member of the same name in {3} '{4}'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base {4}.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" для класса "{0}" неявно объявляет {1} "{2}", что конфликтует с членом, имеющим то же имя в {3} "{4}". Используйте "Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)", если вы хотите скрыть имя в базе{4}.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class implicitly declares member, which conflicts with a member of the same name</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute в классе неявно объявляет член, который конфликтует с членом, обладающим тем же именем</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1">
<source>'{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.</source>
<target state="translated">'Для "{0}" невозможно использование через COM как свойство "Let". Вы не сможете присвоить значения, не являющиеся объектом (например, числа или строки), с помощью оператора "Let" для этого свойства с версии Visual Basic 6.0.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1_Title">
<source>Property cannot be exposed to COM as a property 'Let'</source>
<target state="translated">Невозможно предоставить свойство для COM как свойство Let</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef">
<source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">Используется переменная "{0}", прежде чем ей было присвоено значение. Во время выполнения может появиться пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">Переменная используется до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1">
<source>Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">Функция "{0}" не возвращает значение для всех путей к коду. Во время выполнения при использовании результата может возникнуть пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">Функция не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1">
<source>Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">Оператор "{0}" не возвращает значение для всех путей к коду. Во время выполнения при использовании результата может возникнуть пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">Оператор не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1">
<source>Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">Свойство "{0}" не возвращает значение для всех путей к коду. Во время выполнения при использовании результата может возникнуть пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">Свойство не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr">
<source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source>
<target state="translated">Переменная "{0}" передается по ссылке, прежде чем ей присваивается значение. Во время выполнения может появиться пустая ссылка на исключение. Убедитесь, что перед использованием инициализирована структура или все ссылочные члены</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">Переменная передана ссылкой до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr">
<source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source>
<target state="translated">Используется переменная "{0}", прежде чем ей было присвоено значение. Во время выполнения может появиться пустая ссылка на исключение. Убедитесь, что перед использованием инициализирована структура или все ссылочные члены</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">Переменная используется до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference">
<source>Static variable declared without an 'As' clause; type of Object assumed.</source>
<target state="translated">Статическая переменная объявлена без предложения "As"; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference_Title">
<source>Static variable declared without an 'As' clause</source>
<target state="translated">Статическая переменная, объявленная без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName">
<source>Assembly reference '{0}' is invalid and cannot be resolved.</source>
<target state="translated">Ссылка сборки "{0}" является недопустимой и не может быть разрешена.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName_Title">
<source>Assembly reference is invalid and cannot be resolved</source>
<target state="translated">Ссылка на сборку недопустима и не может быть разрешена</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine">
<source>XML comment block must immediately precede the language element to which it applies. XML comment will be ignored.</source>
<target state="translated">Непосредственно перед блоком комментариев XML должен находиться элемент языка, к которому он применяется. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine_Title">
<source>XML comment block must immediately precede the language element to which it applies</source>
<target state="translated">Блок комментариев XML должен находиться непосредственно перед элементом языка, к которому он применяется</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock">
<source>Only one XML comment block is allowed per language element.</source>
<target state="translated">Только один блок комментариев XML допускается для каждого элемента языка.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock_Title">
<source>Only one XML comment block is allowed per language element</source>
<target state="translated">Только один блок комментариев XML допускается для каждого элемента языка</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine">
<source>XML comment must be the first statement on a line. XML comment will be ignored.</source>
<target state="translated">Комментарий XML должен быть первым оператором строки. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine_Title">
<source>XML comment must be the first statement on a line</source>
<target state="translated">Комментарий XML должен быть первым оператором в строке</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod">
<source>XML comment cannot appear within a method or a property. XML comment will be ignored.</source>
<target state="translated">Комментарий XML не может находиться внутри метода или свойства. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod_Title">
<source>XML comment cannot appear within a method or a property</source>
<target state="translated">Комментарий XML не должен содержаться в методе или свойстве</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1">
<source>XML documentation parse error: {0} XML comment will be ignored.</source>
<target state="translated">Ошибка синтаксического анализа документации XML: Комментарий XML {0} будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1_Title">
<source>XML documentation parse error</source>
<target state="translated">Ошибка анализа документации XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1">
<source>XML comment tag '{0}' appears with identical attributes more than once in the same XML comment block.</source>
<target state="translated">Тег "{0}" комментария XML с одинаковыми атрибутами более одного раза появляется в том же блоке комментариев XML.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1_Title">
<source>XML comment tag appears with identical attributes more than once in the same XML comment block</source>
<target state="translated">Тег комментария XML с идентичными атрибутами встречается больше одного раза в одном блоке комментариев XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2">
<source>XML comment tag '{0}' is not permitted on a '{1}' language element.</source>
<target state="translated">Тег комментария XML "{0}" недопустим для элемента языка "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2_Title">
<source>XML comment tag is not permitted on language element</source>
<target state="translated">Тег комментария XML запрещен в элементе языка</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2">
<source>XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement.</source>
<target state="translated">Параметр комментария XML "{0}" не соответствует параметру соответствующего оператора "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2_Title">
<source>XML comment parameter does not match a parameter on the corresponding declaration statement</source>
<target state="translated">Параметр комментария XML не совпадает с параметром в соответствующем операторе объявления</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName">
<source>XML comment parameter must have a 'name' attribute.</source>
<target state="translated">Параметр комментария XML должен содержать атрибут "name".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName_Title">
<source>XML comment parameter must have a 'name' attribute</source>
<target state="translated">Параметр комментария XML должен содержать атрибут name</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1">
<source>XML comment has a tag with a 'cref' attribute '{0}' that could not be resolved.</source>
<target state="translated">Комментарий XML содержит тег с атрибутом "cref" "{0}", который не удается разрешить.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1_Title">
<source>XML comment has a tag with a 'cref' attribute that could not be resolved</source>
<target state="translated">Комментарий XML содержит тег с атрибутом cref, который не удалось разрешить</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1">
<source>XML comment tag 'include' must have a '{0}' attribute. XML comment will be ignored.</source>
<target state="translated">Тег комментария XML "include" должен содержать атрибут "{0}". Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1_Title">
<source>XML comment tag 'include' must have 'file' and 'path' attributes</source>
<target state="translated">Тег комментария XML "include" должен иметь атрибуты file и path</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2">
<source>Unable to create XML documentation file '{0}': {1}</source>
<target state="translated">Не удается создать файл XML-документации "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2_Title">
<source>Unable to create XML documentation file</source>
<target state="translated">Не удалось создать XML-файл документации</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement">
<source>XML documentation comments must precede member or type declarations.</source>
<target state="translated">Комментарии XML-документации должны предшествовать объявлениям членов или типов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement_Title">
<source>XML documentation comments must precede member or type declarations</source>
<target state="translated">Комментарии XML-документации должны предшествовать объявлениям членов или типов</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.</source>
<target state="translated">Тег комментария XML "returns" недопустим для свойства "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty_Title">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property</source>
<target state="translated">Тег комментария XML "returns" недопустим для свойства WriteOnly</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType">
<source>XML comment cannot be applied more than once on a partial {0}. XML comments for this {0} will be ignored.</source>
<target state="translated">Комментарий XML не может быть применен более одного раза для частичного значения {0}. Комментарий XML для {0} будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType_Title">
<source>XML comment cannot be applied more than once on a partial type</source>
<target state="translated">Комментарий XML не может применяться больше одного раза в разделенном типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element.</source>
<target state="translated">Тег комментария XML "returns" недопустим для элемента языка "declare sub".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub_Title">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element</source>
<target state="translated">Тег комментария XML "returns" недопустим для элемента языка declare sub</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag">
<source>XML documentation parse error: Start tag '{0}' doesn't have a matching end tag. XML comment will be ignored.</source>
<target state="translated">Ошибка синтаксического анализа документации XML: Начальный тег "{0}" не имеет соответствующего конечного тега. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag_Title">
<source>XML documentation parse error: Start tag doesn't have a matching end tag</source>
<target state="translated">Ошибка анализа документации XML: открывающий тег не имеет соответствущего закрывающего тега</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2">
<source>XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement.</source>
<target state="translated">Параметр типа комментария XML "{0}" не соответствует параметру соответствующего оператора "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2_Title">
<source>XML comment type parameter does not match a type parameter on the corresponding declaration statement</source>
<target state="translated">Параметр типа комментария XML не совпадает с параметром типа в соответствующем операторе объявления</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName">
<source>XML comment type parameter must have a 'name' attribute.</source>
<target state="translated">Параметр типа комментария XML должен содержать атрибут "name".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName_Title">
<source>XML comment type parameter must have a 'name' attribute</source>
<target state="translated">Параметр типа комментария XML должен содержать атрибут name</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef">
<source>XML comment exception must have a 'cref' attribute.</source>
<target state="translated">Исключение для комментария XML должно содержать атрибут "cref".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef_Title">
<source>XML comment exception must have a 'cref' attribute</source>
<target state="translated">Исключение для комментария XML должно содержать атрибут cref</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment">
<source>Unable to include XML fragment '{0}' of file '{1}'.</source>
<target state="translated">Не удалось включить фрагмент XML "{0}" файла "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment_Title">
<source>Unable to include XML fragment</source>
<target state="translated">Не удалось включить фрагмент XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML">
<source>Unable to include XML fragment '{1}' of file '{0}'. {2}</source>
<target state="translated">Не удалось включить фрагмент XML "{1}" файла "{0}". {2}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML_Title">
<source>Unable to include XML fragment</source>
<target state="translated">Не удалось включить фрагмент XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2">
<source>Runtime errors might occur when converting '{0}' to '{1}'.</source>
<target state="translated">Ошибки выполнения могут произойти при преобразовании "{0}" в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2_Title">
<source>Runtime errors might occur when converting to or from interface type</source>
<target state="translated">Ошибки среды выполнения могут происходить при преобразовании в тип или из типа интерфейса</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda">
<source>Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">Использование переменной цикла в лямбда-выражении может привести к непредвиденным результатам. Вместо этого можно создать локальную переменную внутри цикла и присвоить ей значение переменной цикла.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda_Title">
<source>Using the iteration variable in a lambda expression may have unexpected results</source>
<target state="translated">Использование переменной итерации в лямбда-выражении может привести к непредусмотренным результатам</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler">
<source>Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.</source>
<target state="translated">Лямбда-выражение не будет удалено из обработчика этого события. Присвойте переменной лямбда-выражение и используйте переменную, чтобы добавить или удалить событие.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler_Title">
<source>Lambda expression will not be removed from this event handler</source>
<target state="translated">Лямбда-выражение не будет удалено из этого обработчика событий</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery">
<source>Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">Использование переменной цикла в выражении запроса может привести к непредвиденным результатам. Вместо этого можно создать локальную переменную внутри цикла и присвоить ей значение переменной цикла.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery_Title">
<source>Using the iteration variable in a query expression may have unexpected results</source>
<target state="translated">Использование переменной итерации в выражении запроса может привести к непредусмотренным результатам</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler.</source>
<target state="translated">Выражение "AddressOf" не работает в этом контексте, так как аргумент метода "AddressOf" требует преобразование в тип делегата события. Можно присвоить выражение "AddressOf" переменной и использовать ее для добавления и удаления события.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler_Title">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event</source>
<target state="translated">Выражение AddressOf не оказывает влияния в этом контексте, так как аргумент метода для AddressOf требует неявного преобразования в тип делегата события</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl">
<source>Range variable is assumed to be of type Object because its type cannot be inferred. Use an 'As' clause to specify a different type.</source>
<target state="translated">Предполагается, что переменная диапазона является типом Object, так как этот тип не может быть определен. Используйте предложение "As", чтобы указать другой тип.</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl_Title">
<source>Range variable is assumed to be of type Object because its type cannot be inferred</source>
<target state="translated">Предполагается, что переменная диапазона имеет тип Object, так как ее тип невозможно определить</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingFunction">
<source>Multiline lambda expression is missing 'End Function'.</source>
<target state="translated">В многострочном лямбда-выражении отсутствует "End Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingSub">
<source>Multiline lambda expression is missing 'End Sub'.</source>
<target state="translated">В многострочном лямбда-выражении отсутствует "End Sub".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOnLambdaReturnType">
<source>Attributes cannot be applied to return types of lambda expressions.</source>
<target state="translated">Не удается применить атрибуты к возвращаемым типам лямбда-выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubDisallowsStatement">
<source>Statement is not valid inside a single-line statement lambda.</source>
<target state="translated">Недопустимый оператор в лямбде однострочного оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesBang">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>)!key</source>
<target state="translated">Эту лямбду однострочного оператора необходимо заключить в круглые скобки. Например: (Sub() <оператор>)!key</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesDot">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>).Invoke()</source>
<target state="translated">Эту лямбду однострочного оператора необходимо заключить в круглые скобки. Например: (Sub() <оператор>).Invoke()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesLParen">
<source>This single-line statement lambda must be enclosed in parentheses. For example: Call (Sub() <statement>) ()</source>
<target state="translated">Эту лямбду однострочного оператора необходимо заключить в круглые скобки. Например: Call (Sub() <оператор>) ()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresSingleStatement">
<source>Single-line statement lambdas must include exactly one statement.</source>
<target state="translated">В лямбдах однострочного оператора может содержаться только один оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StaticInLambda">
<source>Static local variables cannot be declared inside lambda expressions.</source>
<target state="translated">Статические локальные переменные нельзя задавать в лямбда-выражениях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializedExpandedProperty">
<source>Expanded Properties cannot be initialized.</source>
<target state="translated">Невозможно инициировать расширенные свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantHaveParams">
<source>Auto-implemented properties cannot have parameters.</source>
<target state="translated">Автоматически реализованные свойства не могут иметь параметры.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantBeWriteOnly">
<source>Auto-implemented properties cannot be WriteOnly.</source>
<target state="translated">Автоматически реализуемые свойства не могут иметь значение WriteOnly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFCount">
<source>'If' operator requires either two or three operands.</source>
<target state="translated">'Оператор "If" должен содержать два или три операнда.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotACollection1">
<source>Cannot initialize the type '{0}' with a collection initializer because it is not a collection type.</source>
<target state="translated">Невозможно инициализировать тип "{0}" с инициализатором набора, так как он не является типом коллекции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAddMethod1">
<source>Cannot initialize the type '{0}' with a collection initializer because it does not have an accessible 'Add' method.</source>
<target state="translated">Невозможно инициализировать тип "{0}" с инициализатором набора, так как он не имеет доступного метода "Add".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCombineInitializers">
<source>An Object Initializer and a Collection Initializer cannot be combined in the same initialization.</source>
<target state="translated">Инициализатор объектов и инициализатор коллекций не могут объединяться в одной инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmptyAggregateInitializer">
<source>An aggregate collection initializer entry must contain at least one element.</source>
<target state="translated">Запись агрегатного инициализатора коллекции должна содержать по меньшей мере один элемент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndElementNoMatchingStart">
<source>XML end element must be preceded by a matching start element.</source>
<target state="translated">Перед конечным XML-элементом должен идти соответствующий начальный элемент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdasCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside a lambda expression.</source>
<target state="translated">'Сообщения "On Error" и "Resume" не могут находиться в лямбда-выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceDisallowedHere">
<source>Keywords 'Out' and 'In' can only be used in interface and delegate declarations.</source>
<target state="translated">Ключевые слова "Out" и "In" могут использоваться только в объявлениях интерфейсов и делегатов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndCDataNotAllowedInContent">
<source>The literal string ']]>' is not allowed in element content.</source>
<target state="translated">Использование строки литерала "]]>" в содержимом элемента не допускается.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadsModifierInModule">
<source>Inappropriate use of '{0}' keyword in a module.</source>
<target state="translated">Неправильное использование ключевого слова "{0}" в модуле.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedTypeOrNamespace1">
<source>Type or namespace '{0}' is not defined.</source>
<target state="translated">Тип или пространство имен "{0}" не определено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentityDirectCastForFloat">
<source>Using DirectCast operator to cast a floating-point value to the same type is not supported.</source>
<target state="translated">Использование оператора DirectCast для приведения значения с плавающей точкой к тому же типу не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete.</source>
<target state="translated">Использование оператора DirectCast для приведения типа значения к тому же типу больше не нужно.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType_Title">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete</source>
<target state="translated">Использование оператора DirectCast для приведения типа значения к тому же типу больше не нужно</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode">
<source>Unreachable code detected.</source>
<target state="translated">Обнаружен недостижимый код.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode_Title">
<source>Unreachable code detected</source>
<target state="translated">Обнаружен недостижимый код</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1">
<source>Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Функция "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">Функция не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1">
<source>Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Оператор "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">Оператор не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1">
<source>Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Свойство "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">Свойство не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedGlobalNamespace">
<source>Global namespace may not be nested in another namespace.</source>
<target state="translated">Глобальные пространства имен нельзя вкладывать в другие пространства имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatch6">
<source>'{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'.</source>
<target state="translated">"{0}" не может представлять тип "{1}" в {2} "{3}" посредством {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMetaDataReference1">
<source>'{0}' cannot be referenced because it is not a valid assembly.</source>
<target state="translated">'"Задание ссылок на "{0}" не предусмотрено, поскольку это недопустимая сборка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementAllAccessors">
<source>'{0}' cannot be implemented by a {1} property.</source>
<target state="translated">"{0}" невозможно реализовать с помощью свойства {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMustOverride">
<source>
{0}: {1}</source>
<target state="translated">
{0}: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfTooManyTypesObjectDisallowed">
<source>Cannot infer a common type because more than one type is possible.</source>
<target state="translated">Не удается получить общий тип, так как возможно больше одного типа.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed">
<source>Cannot infer a common type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">Не удается получить общий тип, так как возможно больше одного типа: предполагается "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed_Title">
<source>Cannot infer a common type because more than one type is possible</source>
<target state="translated">Не удается получить общий тип, так как возможно больше одного типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoTypeObjectDisallowed">
<source>Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.</source>
<target state="translated">Не удается получить общий тип, так как параметр Strict On не разрешает предположение "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed">
<source>Cannot infer a common type; 'Object' assumed.</source>
<target state="translated">Не удается определить общий тип; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed_Title">
<source>Cannot infer a common type</source>
<target state="translated">Невозможно получить общий тип</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoType">
<source>Cannot infer a common type.</source>
<target state="translated">Не удалось определить общий тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyFileFailure">
<source>Error extracting public key from file '{0}': {1}</source>
<target state="translated">Ошибка извлечения открытого ключа из файла "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyContainerFailure">
<source>Error extracting public key from container '{0}': {1}</source>
<target state="translated">Ошибка извлечения открытого ключа из контейнера "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefNotEqualToThis">
<source>Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</source>
<target state="translated">Дружественный доступ предоставлен "{0}", однако открытый ключ выходной сборки не соответствует ключу, определенному атрибутом предоставляющей сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefSigningMismatch">
<source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source>
<target state="translated">Дружественный доступ предоставлен "{0}", однако состояние подписи строгого имени выходной сборки не соответствует состоянию предоставляющей сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNoKey">
<source>Public sign was specified and requires a public key, but no public key was specified</source>
<target state="translated">Указана общедоступная подпись, и требуется открытый ключ, но открытый ключ не указан.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNetModule">
<source>Public signing is not supported for netmodules.</source>
<target state="translated">Общедоступные подписи не поддерживаются для netmodule.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning">
<source>Attribute '{0}' is ignored when public signing is specified.</source>
<target state="translated">Атрибут "{0}" пропускается при указании общедоступного подписывания.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title">
<source>Attribute is ignored when public signing is specified.</source>
<target state="translated">Атрибут пропускается при указании общедоступного подписывания.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey">
<source>Delay signing was specified and requires a public key, but no public key was specified.</source>
<target state="translated">Была указана отложенная подпись, для которой требуется открытый ключ. Открытый ключ не был указан.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey_Title">
<source>Delay signing was specified and requires a public key, but no public key was specified</source>
<target state="translated">Была указана отложенная подпись, для которой требуется открытый ключ, но открытый ключ не был указан</target>
<note />
</trans-unit>
<trans-unit id="ERR_SignButNoPrivateKey">
<source>Key file '{0}' is missing the private key needed for signing.</source>
<target state="translated">Файл ключа "{0}" не содержит закрытого ключа, необходимого для подписания.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FailureSigningAssembly">
<source>Error signing assembly '{0}': {1}</source>
<target state="translated">Ошибка при подписи сборки "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat">
<source>The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]]</source>
<target state="translated">Указанная строка версии не соответствует требуемому формату: основной номер[.дополнительный номер[.сборка|*[.редакция|*]]]</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">Указанная строка версии не соответствует рекомендованному формату — основной номер.дополнительный номер.сборка.редакция</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat_Title">
<source>The specified version string does not conform to the recommended format</source>
<target state="translated">Указанная строка версии не соответствует рекомендуемому формату</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat2">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">Указанная строка версии не соответствует рекомендованному формату — основной номер.дополнительный номер.сборка.редакция</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCultureForExe">
<source>Executables cannot be satellite assemblies; culture should always be empty</source>
<target state="translated">Исполняемые файлы не могут быть вспомогательными сборками; язык и региональные параметры должны быть пустыми.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored">
<source>The entry point of the program is global script code; ignoring '{0}' entry point.</source>
<target state="translated">Точкой входа программы является глобальный код скрипта; игнорируйте точку входа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored_Title">
<source>The entry point of the program is global script code; ignoring entry point</source>
<target state="translated">Точка входа в программе является глобальным кодом скрипта; выполняется пропуск точки входа</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName">
<source>The xmlns attribute has special meaning and should not be written with a prefix.</source>
<target state="translated">Атрибут xmlns имеет особое значение и не должен быть написан с префиксом.</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName_Title">
<source>The xmlns attribute has special meaning and should not be written with a prefix</source>
<target state="translated">Атрибут xmlns имеет особое значение и не должен быть записан с префиксом</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName">
<source>It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:{0}' to define a prefix named '{0}'?</source>
<target state="translated">Не рекомендуется иметь атрибуты с именем xmlns. Имелось в виду написание "xmlns:{0}" для определения префикса с именем "{0}"?</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName_Title">
<source>It is not recommended to have attributes named xmlns</source>
<target state="translated">Атрибуты не рекомендуется называть "xmlns"</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSingleScript">
<source>Expected a single script (.vbx file)</source>
<target state="translated">Ожидался отдельный скрипт (VBX-файл)</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedAssemblyName">
<source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source>
<target state="translated">Имя сборки "{0}" зарезервировано и не может использоваться как ссылка в интерактивном сеансе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts">
<source>#R is only allowed in scripts</source>
<target state="translated">#R допускается только в скриптах</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAllowedInScript">
<source>You cannot declare Namespace in script code</source>
<target state="translated">Нельзя объявить пространство имен в коде скрипта</target>
<note />
</trans-unit>
<trans-unit id="ERR_KeywordNotAllowedInScript">
<source>You cannot use '{0}' in top-level script code</source>
<target state="translated">Нельзя использовать "{0}" в коде скрипта верхнего уровня.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoType">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">Не удалось определить возвращаемый тип. Для указания возвращаемого типа рекомендуется добавлять предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed">
<source>Cannot infer a return type; 'Object' assumed.</source>
<target state="translated">Не удается определить тип возвращаемого значения; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed_Title">
<source>Cannot infer a return type</source>
<target state="translated">Невозможно определить тип возвращаемого значения</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed">
<source>Cannot infer a return type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">Не удается получить тип возвращаемого значения, так как возможно больше одного типа; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed_Title">
<source>Cannot infer a return type because more than one type is possible</source>
<target state="translated">Невозможно определить тип возвращаемого значения, так как возможно больше одного типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoTypeObjectDisallowed">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">Не удалось определить возвращаемый тип. Для указания возвращаемого типа рекомендуется добавлять предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaTooManyTypesObjectDisallowed">
<source>Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">Не удается получить возвращаемый тип, так как возможно больше одного типа. Для указания возвращаемого типа рекомендуется добавлять предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch">
<source>The command line switch '{0}' is not yet implemented and was ignored.</source>
<target state="translated">Переключатель командной строки "{0}" еще не реализован и был пропущен.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch_Title">
<source>Command line switch is not yet implemented</source>
<target state="translated">Переключатель командной строки еще не реализован</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoTypeObjectDisallowed">
<source>Cannot infer an element type, and Option Strict On does not allow 'Object' to be assumed. Specifying the type of the array might correct this error.</source>
<target state="translated">Не удается получить тип элемента, параметр Strict On не разрешает предположение "Object". Указание типа массива может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoType">
<source>Cannot infer an element type. Specifying the type of the array might correct this error.</source>
<target state="translated">Не удалось определить тип элемента. Указание типа массива может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitTooManyTypesObjectDisallowed">
<source>Cannot infer an element type because more than one type is possible. Specifying the type of the array might correct this error.</source>
<target state="translated">Не удается получить тип элемента, так как возможно больше одного типа. Указание типа массива может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed">
<source>Cannot infer an element type; 'Object' assumed.</source>
<target state="translated">Не удается определить тип элемента; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed_Title">
<source>Cannot infer an element type</source>
<target state="translated">Невозможно определить тип элемента</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed">
<source>Cannot infer an element type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">Не удается получить тип элемента, так как возможно больше одного типа: предполагается "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed_Title">
<source>Cannot infer an element type because more than one type is possible</source>
<target state="translated">Невозможно определить тип элемента, так как возможно больше одного типа</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3">
<source>Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed.</source>
<target state="translated">Не удалось получить тип данных "{0}" в "{1}". "{2}" предполагается.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3_Title">
<source>Data type could not be inferred</source>
<target state="translated">Не удалось определить тип данных</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousCastConversion2">
<source>Option Strict On does not allow implicit conversions from '{0}' to '{1}' because the conversion is ambiguous.</source>
<target state="translated">Параметр Strict On не допускает неявные преобразования из "{0}" в "{1}", поскольку такое преобразование неоднозначно.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2">
<source>Conversion from '{0}' to '{1}' may be ambiguous.</source>
<target state="translated">Преобразование "{0}" в "{1}" может привести к неоднозначности.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2_Title">
<source>Conversion may be ambiguous</source>
<target state="translated">Преобразование может быть неоднозначным</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3_Title">
<source>Type cannot be converted to target collection type</source>
<target state="translated">Невозможно преобразовать тип в целевой тип коллекции</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedIn6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">"{4}" нельзя преобразовать в "{5}", так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "In" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedOut6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">'{4}" нельзя преобразовать в "{5}", так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "Out" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">Неявное преобразование "{4}" в "{5}"; возможны ошибки преобразования, так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "In" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'In' generic parameter</source>
<target state="translated">Неявное преобразование; может произойти сбой этого преобразования, так как целевой тип не наследуется от типа источника, как это требуется для универсального параметра In</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">Неявное преобразование "{4}" в "{5}"; возможно ошибки преобразования, так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "Out" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'Out' generic parameter</source>
<target state="translated">Неявное преобразование; может произойти сбой этого преобразования, так как целевой тип не наследуется из типа источника, как это требуется для универсального параметра Out</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">Тип невозможно преобразовать в целевой тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">Тип невозможно преобразовать в целевой тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3">
<source>Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'.</source>
<target state="translated">Интерфейс "{0}" неоднозначен с другим реализованным интерфейсом "{1}" из-за параметров "In" и "Out" в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3_Title">
<source>Interface is ambiguous with another implemented interface due to 'In' and 'Out' parameters</source>
<target state="translated">Интерфейс неоднозначен, так как другой интерфейс реализован в соответствии с параметрами In и Out</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInterfaceNesting">
<source>Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.</source>
<target state="translated">Перечисления, классы и структуры не могут быть объявлены в интерфейсе, имеющем параметр типа "In" или "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VariancePreventsSynthesizedEvents2">
<source>Event definitions with parameters are not allowed in an interface such as '{0}' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within '{0}'. For example, 'Event {1} As Action(Of ...)'.</source>
<target state="translated">Определения событий с параметрами не допускается в интерфейсе, например "{0}", который имеет параметры "In" или "Out". Попробуйте объявить событие с помощью делегата, который не определен в "{0}". Например, "Event {1} As Action(Of ...)".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в этом контексте, так как параметры "In" и "Out" нельзя использовать для параметра ByRef и "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в "{1}" так как параметры "In" и "Out" не допускают значение Null и "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать для "{1}" в "{2}" в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в "{1}" в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать для "{2}" "{3}" в "{1}" в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа свойства в данном контексте, так как "{0}" является параметром типа "In" и свойство не помечено как WriteOnly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReadOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в качестве свойства ReadOnly, так как "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReturnDisallowed1">
<source>Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в качестве возвращаемого типа, так как "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в этом контексте, потому что тип параметров "In" и "Out" нельзя использовать для типов параметра ByRef и "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByValDisallowed1">
<source>Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в качестве типа параметра ByVal, так как "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutConstraintDisallowed1">
<source>Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа ограничения, так как "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в "{1}", так как параметры "In" и "Out" не допускают значение Null и "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться для "{1}" в "{2}" в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в "{1}" в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться для "{2}" "{3}" в "{1}" в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа свойства в данном контексте, так как "{0}" является параметром типа "Out" и свойство не помечено как ReadOnly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutWriteOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа свойства WriteOnly, так как "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowed2">
<source>Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться для "{2}" в "{3}" в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHere3">
<source>Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться для "{2}" в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHereForGeneric5">
<source>Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться для "{3}" "{4}" в "{2}" в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterNotValidForType">
<source>Parameter not valid for the specified unmanaged type.</source>
<target state="translated">Недопустимый параметр для указанного неуправляемого типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields">
<source>Unmanaged type '{0}' not valid for fields.</source>
<target state="translated">Неуправляемый тип "{0}" недопустим для полей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields">
<source>Unmanaged type '{0}' is only valid for fields.</source>
<target state="translated">Неуправляемый тип "{0}" допустим только для полей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired1">
<source>Attribute parameter '{0}' must be specified.</source>
<target state="translated">Должен быть указан параметр атрибута "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired2">
<source>Attribute parameter '{0}' or '{1}' must be specified.</source>
<target state="translated">Должен быть указан параметр атрибута "{0}" или "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberConflictWithSynth4">
<source>Conflicts with '{0}', which is implicitly declared for '{1}' in {2} '{3}'.</source>
<target state="translated">Конфликтует с "{0}", неявно объявленным для "{1}" в {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="IDS_ProjectSettingsLocationName">
<source><project settings></source>
<target state="translated"><настройки проекта></target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty">
<source>Attributes applied on a return type of a WriteOnly Property have no effect.</source>
<target state="translated">Атрибуты, применяемые к возвращаемому типу свойства WriteOnly, никак не влияют.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty_Title">
<source>Attributes applied on a return type of a WriteOnly Property have no effect</source>
<target state="translated">Атрибуты, применяемые к типу возвращаемого значения свойства WriteOnly, никак не влияют</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidTarget">
<source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source>
<target state="translated">Атрибут безопасности "{0}" не допускается для этого типа объявления. Атрибуты безопасности допустимы только в сборке, типе и объявлениях метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AbsentReferenceToPIA1">
<source>Cannot find the interop type that matches the embedded type '{0}'. Are you missing an assembly reference?</source>
<target state="translated">Не удается найти тип взаимодействия, соответствующий внедренному типу взаимодействия "{0}". Возможно, отсутствует ссылка на сборку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLinkClassWithNoPIA1">
<source>Reference to class '{0}' is not allowed when its assembly is configured to embed interop types.</source>
<target state="translated">Ссылка на класс "{0}" не разрешена, когда его сборка настроена для внедрения типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidStructMemberNoPIA1">
<source>Embedded interop structure '{0}' can contain only public instance fields.</source>
<target state="translated">Внедренная структура взаимодействия "{0}" может содержать только открытые экземпляры полей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPIAAttributeMissing2">
<source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source>
<target state="translated">Не удается внедрить тип взаимодействия "{0}", так как у него отсутствует обязательный атрибут "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoAssemblyGuid1">
<source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source>
<target state="translated">Не удается внедрить типы взаимодействия из сборки "{0}" из-за отсутствия в ней атрибута "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalTypes3">
<source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider disabling the embedding of interop types.</source>
<target state="translated">Не удается внедрить тип взаимодействия "{0}", находящийся в обеих сборках "{1}" и "{2}". Попробуйте отключить внедрение типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoTypeLibAttribute1">
<source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source>
<target state="translated">Внедрение типов взаимодействия из сборки "{0}" невозможно, так как у нее отсутствует атрибут "{1}" или атрибут "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceInterfaceMustBeInterface">
<source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source>
<target state="translated">Интерфейс "{0}" имеет недопустимый исходный интерфейс, который требуется для внедрения события "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNoPIANoBackingMember">
<source>Source interface '{0}' is missing method '{1}', which is required to embed event '{2}'.</source>
<target state="translated">В исходном интерфейсе "{0}" отсутствует метод "{1}", обязательный для внедрения события "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedInteropType">
<source>Nested type '{0}' cannot be embedded.</source>
<target state="translated">Невозможно внедрить вложенный тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalTypeNameClash2">
<source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types.</source>
<target state="translated">Внедрение типа взаимодействия "{0}" из сборки "{1}" служит причиной конфликта имен в текущей сборке. Попробуйте отключить внедрение типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InteropMethodWithBody1">
<source>Embedded interop method '{0}' contains a body.</source>
<target state="translated">Внедренный метод взаимодействия "{0}" содержит тело.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncInQuery">
<source>'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.</source>
<target state="translated">'Оператор Await можно использовать только в выражении запроса в первом выражении коллекции начального предложения From или в выражении коллекции предложения Join.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGetAwaiterMethod1">
<source>'Await' requires that the type '{0}' have a suitable GetAwaiter method.</source>
<target state="translated">'Для применения оператора "await" у типа "{0}" должен быть подходящий метод GetAwaiter.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIsCompletedOnCompletedGetResult2">
<source>'Await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.</source>
<target state="translated">'Для использования оператора "Await" необходимо, чтобы у возвращаемого типа "{0}" метода "{1}.GetAwaiter()" были соответствующие члены IsCompleted, OnCompleted и GetResult и чтобы этот тип реализовывал интерфейс INotifyCompletion или ICriticalNotifyCompletion.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoesntImplementAwaitInterface2">
<source>'{0}' does not implement '{1}'.</source>
<target state="translated">"{0}" не реализует "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNothing">
<source>Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.</source>
<target state="translated">Нельзя ожидать значение Nothing. Попробуйте вместо этого ожидать Task.Yield().</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncByRefParam">
<source>Async methods cannot have ByRef parameters.</source>
<target state="translated">Методы с модификатором Async не могут иметь параметры ByRef.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAsyncIteratorModifiers">
<source>'Async' and 'Iterator' modifiers cannot be used together.</source>
<target state="translated">'Модификаторы "Async" и "Iterator" нельзя использовать одновременно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadResumableAccessReturnVariable">
<source>The implicit return variable of an Iterator or Async method cannot be accessed.</source>
<target state="translated">Нельзя получить доступ к неявно возвращаемой переменной метода, помеченного модификатором Iterator или Async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonGenericTaskAsync">
<source>'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.</source>
<target state="translated">'Операторам "Return" данного метода Async не удается вернуть значение, поскольку для функции указан возвращаемый тип "Task". Попробуйте изменить тип возвращаемого значения на "Task(Of T)".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturnOperand1">
<source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task(Of {0})'.</source>
<target state="translated">Поскольку данный метод является асинхронным, возвращаемое выражение должно относиться к типу "{0}", а не к типу "Task(Of {0})".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturn">
<source>The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).</source>
<target state="translated">Модификатор Async можно использовать только в подпрограммах или в функциях, которые возвращают значения типа Task или Task(Of T).</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAwaitAsyncSub1">
<source>'{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function.</source>
<target state="translated">"{0}" не возвращает значения типа Task, и его нельзя ожидать. Попробуйте заменить его на функцию с модификатором Async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLambdaModifier">
<source>'Only the 'Async' or 'Iterator' modifier is valid on a lambda.</source>
<target state="translated">'В лямбда-выражениях допускаются только модификаторы "Async" или "Iterator".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of {0})'.</source>
<target state="translated">'Оператор await можно использовать только в методах с модификатором async. Попробуйте пометить этот метод модификатором "Async" и изменить его возвращаемый тип на "Task(Of {0})".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncVoidMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.</source>
<target state="translated">'Оператор await можно использовать только в методах с модификатором async. Попробуйте пометить этот метод модификатором async и изменить тип его возвращаемого значения на Task.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncLambda">
<source>'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.</source>
<target state="translated">'Оператор await можно использовать только в лямбда-выражениях с модификатором async. Попробуйте пометить это лямбда-выражение модификатором async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNotInAsyncMethodOrLambda">
<source>'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.</source>
<target state="translated">'Оператор await можно использовать, только если он содержится в методе или лямбда-выражении, помеченном модификатором async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StatementLambdaInExpressionTree">
<source>Statement lambdas cannot be converted to expression trees.</source>
<target state="translated">Лямбды оператора невозможно преобразовать в деревья выражений.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression">
<source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.</source>
<target state="translated">Поскольку этот вызов не ожидается, выполнение текущего метода продолжается до завершения вызова. Попробуйте применить оператор Await к результату вызова.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression_Title">
<source>Because this call is not awaited, execution of the current method continues before the call is completed</source>
<target state="translated">Так как этот вызов не ожидается, выполнение существующего метода продолжается до тех пор, пока вызов не будет завершен</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotAwait">
<source>Loop control variable cannot include an 'Await'.</source>
<target state="translated">Управляющая переменная цикла не может содержать "Await".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticInitializerInResumable">
<source>Static variables cannot appear inside Async or Iterator methods.</source>
<target state="translated">В методах Async или Iterator нельзя использовать статические переменные.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedResumableType1">
<source>'{0}' cannot be used as a parameter type for an Iterator or Async method.</source>
<target state="translated">"{0}" не может быть использовано в качестве типа параметра для метода Iterator или Async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorAsync">
<source>Constructor must not have the 'Async' modifier.</source>
<target state="translated">Конструктор не должен иметь модификатор "Async".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustNotBeAsync1">
<source>'{0}' cannot be declared 'Partial' because it has the 'Async' modifier.</source>
<target state="translated">"{0}" не может быть объявлен "Partial", так как имеет модификатор "Async".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumablesCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside async or iterator methods.</source>
<target state="translated">'В методах, помеченных модификатором "Async" или "Iterator", не могут возникать события "On Error" и "Resume".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumableLambdaInExpressionTree">
<source>Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.</source>
<target state="translated">Лямбда-выражения с модификаторами "Async" и "Iterator" нельзя преобразовать в деревья выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeResumable1">
<source>Variable of restricted type '{0}' cannot be declared in an Async or Iterator method.</source>
<target state="translated">Переменную ограниченного типа "{0}" нельзя объявить в методе, помеченном модификатором Async или Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInTryHandler">
<source>'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.</source>
<target state="translated">'Оператор Await нельзя использовать в операторах Catch, Finally и SyncLock.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits">
<source>This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.</source>
<target state="translated">В данном асинхронном методе отсутствуют операторы "Await", поэтому метод будет выполняться синхронно. Воспользуйтесь оператором "Await" для ожидания неблокирующих вызовов API или оператором "Await Task.Run(...)" для выполнения связанных с ЦП заданий в фоновом потоке.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits_Title">
<source>This async method lacks 'Await' operators and so will run synchronously</source>
<target state="translated">В асинхронном методе отсутствуют операторы Await; будет выполнен синхронный запуск</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.</source>
<target state="translated">Задача, возвращенная этой функцией Async, будет удалена, а все исключения будут игнорироваться. Попробуйте изменить ее на подпрограмму Async, чтобы исключения распространялись.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate_Title">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored</source>
<target state="translated">Задача, полученная из асинхронной функции, будет удалена, а все исключения в ней — пропущены</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsyncInClassOrStruct">
<source>Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source>
<target state="translated">Методы Async и Iterator недопустимо использовать в [Класс|Структура|Интерфейс|Модуль] с атрибутом "SecurityCritical" или "SecuritySafeCritical".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsync">
<source>Security attribute '{0}' cannot be applied to an Async or Iterator method.</source>
<target state="translated">Атрибут безопасности "{0}" нельзя применить к методу Async или Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnResumableMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методам Async или Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynchronizedAsyncMethod">
<source>'MethodImplOptions.Synchronized' cannot be applied to an Async method.</source>
<target state="translated">'Невозможно применить "MethodImplOptions.Synchronized" к асинхронному методу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsyncSubMain">
<source>The 'Main' method cannot be marked 'Async'.</source>
<target state="translated">Метод Main нельзя пометить модификатором Async.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction">
<source>Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.</source>
<target state="translated">Некоторые используемые здесь перегрузки принимают функцию Async, а не подпрограмму Async. Воспользуйтесь функцией Async или выполните явное приведение данной подпрограммы Async к требуемому типу.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction_Title">
<source>Some overloads here take an Async Function rather than an Async Sub</source>
<target state="translated">Некоторые используемые здесь перегрузки принимают функцию с модификатором Async, а не подпрограмму с модификатором Async</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyGroupCollectionAttributeCycle">
<source>MyGroupCollectionAttribute cannot be applied to itself.</source>
<target state="translated">Атрибут MyGroupCollectionAttribute нельзя применить к самому себе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LiteralExpected">
<source>Literal expected.</source>
<target state="translated">Требуется литерал.</target>
<note />
</trans-unit>
<trans-unit id="ERR_WinRTEventWithoutDelegate">
<source>Event declarations that target WinMD must specify a delegate type. Add an As clause to the event declaration.</source>
<target state="translated">В объявления событий, предназначенных для WinMD, должен указываться тип делегатов. Добавьте в объявление событий предложение As.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MixingWinRTAndNETEvents">
<source>Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}'</source>
<target state="translated">Событие "{0}" не может реализовать событие среды выполнения Windows "{1}" и регулярное событие .NET "{2}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplRemoveHandlerParamWrong">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because the parameters of their 'RemoveHandler' methods do not match.</source>
<target state="translated">Событию "{0}" не удается реализовать событие "{1}" в интерфейсе "{2}" из-за несовпадения параметров их методов "RemoveHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddParamWrongForWinRT">
<source>The type of the 'AddHandler' method's parameter must be the same as the type of the event.</source>
<target state="translated">Тип параметра метода AddHandler должен совпадать с типом события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RemoveParamWrongForWinRT">
<source>In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken'</source>
<target state="translated">В событии среды выполнения Windows тип параметра метода "RemoveHandler" должен иметь значение "EventRegistrationToken"</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface5">
<source>'{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed</source>
<target state="translated">"{0}.{1}" из "implements {2}" уже реализован базовым классом "{3}". Повторная реализация интерфейса среды выполнения Windows "{4}" не разрешена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface4">
<source>'{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed</source>
<target state="translated">"{0}.{1}" уже реализован базовым классом "{2}". Повторная реализация интерфейса среды выполнения Windows "{3}" не разрешена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorByRefParam">
<source>Iterator methods cannot have ByRef parameters.</source>
<target state="translated">Методы с модификатором Iterator не могут иметь параметры ByRef.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorExpressionLambda">
<source>Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.</source>
<target state="translated">Лямбда-выражения, состоящие из одной строки, не могут содержать модификатор Iterator. Используйте лямбда-выражение, состоящее из нескольких строк.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorReturn">
<source>Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.</source>
<target state="translated">Функции с модификатором Iterator должны возвращать интерфейс IEnumerable(Of T) или IEnumerator(Of T) либо неуниверсальные формы перечисления IEnumerable или IEnumerator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadReturnValueInIterator">
<source>To return a value from an Iterator function, use 'Yield' rather than 'Return'.</source>
<target state="translated">Для возвращения значения из функции с модификатором Iterator используйте оператор Yield, а не оператор Return.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInNonIteratorMethod">
<source>'Yield' can only be used in a method marked with the 'Iterator' modifier.</source>
<target state="translated">'Yield можно использовать только в методах, помеченных модификатором Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInTryHandler">
<source>'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.</source>
<target state="translated">'Yield нельзя использовать в операторе Catch или Finally.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1">
<source>The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">AddHandler для события среды выполнения Windows "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1_Title">
<source>The AddHandler for Windows Runtime event doesn't return a value on all code paths</source>
<target state="translated">Атрибут AddHandler для события среды выполнения Windows не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodDefaultParameterValueMismatch2">
<source>Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">Необязательный параметр метода "{0}" не имеет то же значение по умолчанию, что и соответствующий параметр разделяемого метода "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamArrayMismatch2">
<source>Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">Параметр метода "{0}" отличается по модификатору ParamArray из соответствующего параметра разделяемого метода "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMismatch">
<source>Module name '{0}' stored in '{1}' must match its filename.</source>
<target state="translated">Имя модуля "{0}", сохраненное в "{1}", должно соответствовать его имени файла.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleName">
<source>Invalid module name: {0}</source>
<target state="translated">Недопустимое имя модуля: {0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden">
<source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source.</source>
<target state="translated">Атрибут "{0}" из модуля "{1}" будут игнорироваться в пользу экземпляра в исходнике.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title">
<source>Attribute from module will be ignored in favor of the instance appearing in source</source>
<target state="translated">Вместо атрибута модуля будет показан экземпляр, отображающийся в источнике</target>
<note />
</trans-unit>
<trans-unit id="ERR_CmdOptionConflictsSource">
<source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source>
<target state="translated">Атрибут "{0}", заданный в исходном файле, конфликтует с параметром "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName">
<source>Referenced assembly '{0}' does not have a strong name.</source>
<target state="translated">У сборки "{0}", на которую дается ссылка, нет строгого имени.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title">
<source>Referenced assembly does not have a strong name</source>
<target state="translated">Сборка, на которую указывает ссылка, не имеет строгого имени</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSignaturePublicKey">
<source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source>
<target state="translated">В AssemblySignatureKeyAttribute определен недопустимый открытый ключ подписи.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CollisionWithPublicTypeInModule">
<source>Type '{0}' conflicts with public type defined in added module '{1}'.</source>
<target state="translated">Тип "{0}" конфликтует с общим типом, определенным в добавленном модуле "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypeConflictsWithDeclaration">
<source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">Тип "{0}", экспортированный из модуля "{1}", конфликтует с типом, объявленным в основном модуле этой сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypesConflict">
<source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">Тип "{0}", экспортированный из модуля "{1}", конфликтует с типом "{2}", экспортированным из модуля "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch">
<source>Referenced assembly '{0}' has different culture setting of '{1}'.</source>
<target state="translated">Сборка "{0}", на которую дается ссылка, использует другой параметр языка и региональных параметров "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch_Title">
<source>Referenced assembly has different culture setting</source>
<target state="translated">Сборка, на которую указывает ссылка, содержит другой параметр языка и региональных параметров</target>
<note />
</trans-unit>
<trans-unit id="ERR_AgnosticToMachineModule">
<source>Agnostic assembly cannot have a processor specific module '{0}'.</source>
<target state="translated">Безразмерная сборка не может иметь модуль для конкретного процессора "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingMachineModule">
<source>Assembly and module '{0}' cannot target different processors.</source>
<target state="translated">Сборка и модуль "{0}" не могут предназначаться для разных процессоров.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly">
<source>Referenced assembly '{0}' targets a different processor.</source>
<target state="translated">Сборка, на которую дана ссылка "{0}", направлена на другой процессор.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly_Title">
<source>Referenced assembly targets a different processor</source>
<target state="translated">Сборка, на которую указывает ссылка, предназначена для другого процессора</target>
<note />
</trans-unit>
<trans-unit id="ERR_CryptoHashFailed">
<source>Cryptographic failure while creating hashes.</source>
<target state="translated">Сбой шифрования при создании хэшей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantHaveWin32ResAndManifest">
<source>Conflicting options specified: Win32 resource file; Win32 manifest.</source>
<target state="translated">Заданы несовместимые параметры: файл ресурсов Win32; манифест Win32.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration">
<source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">Отправленный тип "{0}" конфликтует с типом, объявленным в основном модуле этой сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypesConflict">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source>
<target state="translated">Тип "{0}", отправленный в сборку "{1}", конфликтует с типом "{2}", отправленным в сборку "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongMetadataName">
<source>Name '{0}' exceeds the maximum length allowed in metadata.</source>
<target state="translated">Имя "{0}" превышает максимальную длину, допустимую в метаданных.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNetModuleReference">
<source>Reference to '{0}' netmodule missing.</source>
<target state="translated">Отсутствует ссылка на "{0}" netmodule.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMustBeUnique">
<source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source>
<target state="translated">Модуль "{0}" уже определен в этой сборке. Каждый модуль должен иметь уникальное имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithExportedType">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">Тип "{0}", отправленный в сборку "{1}", конфликтует с типом "{2}", экспортированным из модуля "{3}".</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDREFERENCE">
<source>Adding assembly reference '{0}'</source>
<target state="translated">Добавление ссылки на сборку "{0}"</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDLINKREFERENCE">
<source>Adding embedded assembly reference '{0}'</source>
<target state="translated">Добавление ссылки на встроенную сборку "{0}"</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDMODULE">
<source>Adding module reference '{0}'</source>
<target state="translated">Добавление ссылки на модуль "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestingViolatesCLS1">
<source>Type '{0}' does not inherit the generic type parameters of its container.</source>
<target state="translated">Тип "{0}" не наследует параметров универсального типа для контейнера.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PDBWritingFailed">
<source>Failure writing debug information: {0}</source>
<target state="translated">Сбой при записи информации отладки: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute">
<source>The parameter has multiple distinct default values.</source>
<target state="translated">Параметр имеет несколько различных значений по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldHasMultipleDistinctConstantValues">
<source>The field has multiple distinct constant values.</source>
<target state="translated">Поле имеет несколько различных константных значений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncNoPIAReference">
<source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source>
<target state="translated">Не удается продолжить, так как оператор edit содержит ссылку на встроенный тип: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncReferenceToAddedMember">
<source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source>
<target state="translated">Доступ к члену "{0}", добавленному в ходе текущего сеанса отладки, возможен только из его объявляющей сборки "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedModule1">
<source>'{0}' is an unsupported .NET module.</source>
<target state="translated">"{0}" не поддерживается модулем .NET.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedEvent1">
<source>'{0}' is an unsupported event.</source>
<target state="translated">"{0}" является неподдерживаемым событием.</target>
<note />
</trans-unit>
<trans-unit id="PropertiesCanNotHaveTypeArguments">
<source>Properties can not have type arguments</source>
<target state="translated">Свойства не могут иметь тип аргументов.</target>
<note />
</trans-unit>
<trans-unit id="IdentifierSyntaxNotWithinSyntaxTree">
<source>IdentifierSyntax not within syntax tree</source>
<target state="translated">IdentifierSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="AnonymousObjectCreationExpressionSyntaxNotWithinTree">
<source>AnonymousObjectCreationExpressionSyntax not within syntax tree</source>
<target state="translated">AnonymousObjectCreationExpressionSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="FieldInitializerSyntaxNotWithinSyntaxTree">
<source>FieldInitializerSyntax not within syntax tree</source>
<target state="translated">FieldInitializerSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="IDS_TheSystemCannotFindThePathSpecified">
<source>The system cannot find the path specified</source>
<target state="translated">Системе не удается найти указанный путь</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoPointerTypesInVB">
<source>There are no pointer types in VB.</source>
<target state="translated">В VB нет типов указателей.</target>
<note />
</trans-unit>
<trans-unit id="ThereIsNoDynamicTypeInVB">
<source>There is no dynamic type in VB.</source>
<target state="translated">В VB нет динамического типа.</target>
<note />
</trans-unit>
<trans-unit id="VariableSyntaxNotWithinSyntaxTree">
<source>variableSyntax not within syntax tree</source>
<target state="translated">variableSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="AggregateSyntaxNotWithinSyntaxTree">
<source>AggregateSyntax not within syntax tree</source>
<target state="translated">AggregateSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="FunctionSyntaxNotWithinSyntaxTree">
<source>FunctionSyntax not within syntax tree</source>
<target state="translated">FunctionSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="PositionIsNotWithinSyntax">
<source>Position is not within syntax tree</source>
<target state="translated">Позиция не входит в синтаксическое дерево.</target>
<note />
</trans-unit>
<trans-unit id="RangeVariableSyntaxNotWithinSyntaxTree">
<source>RangeVariableSyntax not within syntax tree</source>
<target state="translated">RangeVariableSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinSyntaxTree">
<source>DeclarationSyntax not within syntax tree</source>
<target state="translated">DeclarationSyntax вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="StatementOrExpressionIsNotAValidType">
<source>StatementOrExpression is not an ExecutableStatementSyntax or an ExpressionSyntax</source>
<target state="translated">StatementOrExpression не является ExecutableStatementSyntax или ExpressionSyntax</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinTree">
<source>DeclarationSyntax not within tree</source>
<target state="translated">DeclarationSyntax вне дерева</target>
<note />
</trans-unit>
<trans-unit id="TypeParameterNotWithinTree">
<source>TypeParameter not within tree</source>
<target state="translated">TypeParameter находится вне дерева</target>
<note />
</trans-unit>
<trans-unit id="NotWithinTree">
<source> not within tree</source>
<target state="translated"> вне дерева</target>
<note />
</trans-unit>
<trans-unit id="LocationMustBeProvided">
<source>Location must be provided in order to provide minimal type qualification.</source>
<target state="translated">Чтобы выполнить минимальную квалификацию типа, необходимо указать расположение.</target>
<note />
</trans-unit>
<trans-unit id="SemanticModelMustBeProvided">
<source>SemanticModel must be provided in order to provide minimal type qualification.</source>
<target state="translated">Для обеспечения минимального типа квалификации требуется SemanticModel.</target>
<note />
</trans-unit>
<trans-unit id="NumberOfTypeParametersAndArgumentsMustMatch">
<source>the number of type parameters and arguments should be the same</source>
<target state="translated">Число типа параметров и аргументов должно быть одинаковым.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResourceInModule">
<source>Cannot link resource files when building a module</source>
<target state="translated">Не удается связать файлы ресурсов при сборке модуля.</target>
<note />
</trans-unit>
<trans-unit id="NotAVbSymbol">
<source>Not a VB symbol.</source>
<target state="translated">Не символ VB.</target>
<note />
</trans-unit>
<trans-unit id="ElementsCannotBeNull">
<source>Elements cannot be null.</source>
<target state="translated">Элементы не могут иметь значение Null.</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause">
<source>Unused import clause.</source>
<target state="translated">Неиспользуемое предложение import.</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement">
<source>Unused import statement.</source>
<target state="translated">Неиспользуемый оператор import.</target>
<note />
</trans-unit>
<trans-unit id="WrongSemanticModelType">
<source>Expected a {0} SemanticModel.</source>
<target state="translated">Требуется {0} SemanticModel.</target>
<note />
</trans-unit>
<trans-unit id="PositionNotWithinTree">
<source>Position must be within span of the syntax tree.</source>
<target state="translated">Позиция должна находиться в диапазоне синтаксического дерева.</target>
<note />
</trans-unit>
<trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation">
<source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source>
<target state="translated">Предполагаемый синтаксический узел не может принадлежать синтаксическому дереву из текущей компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ChainingSpeculativeModelIsNotSupported">
<source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source>
<target state="translated">Построение цепочки наблюдающей семантической модели не поддерживается. Необходимо создать наблюдающую модель из ненаблюдающей ParentModel.</target>
<note />
</trans-unit>
<trans-unit id="IDS_ToolName">
<source>Microsoft (R) Visual Basic Compiler</source>
<target state="translated">Компилятор Microsoft (R) Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine1">
<source>{0} version {1}</source>
<target state="translated">{0} версии {1}</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine2">
<source>Copyright (C) Microsoft Corporation. All rights reserved.</source>
<target state="translated">© Корпорация Майкрософт (Microsoft Corporation). Все права защищены.</target>
<note />
</trans-unit>
<trans-unit id="IDS_LangVersions">
<source>Supported language versions:</source>
<target state="translated">Поддерживаемые языковые версии:</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong">
<source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">Слишком длинное локальное имя "{0}" для PDB. Попробуйте сократить или компилировать без /debug.</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong_Title">
<source>Local name is too long for PDB</source>
<target state="translated">Локальное имя слишком длинное для PDB-файла</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong">
<source>Import string '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">Импорт строки "{0}" имеет слишком много знаков для PDB. Попробуйте сократить или компилировать без /debug.</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong_Title">
<source>Import string is too long for PDB</source>
<target state="translated">Строка импорта слишком длинная для PDB</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter">
<source>XML comment has a tag with a 'cref' attribute '{0}' that bound to a type parameter. Use the <typeparamref> tag instead.</source>
<target state="translated">Комментарий XML содержит тег с атрибутом "cref" "{0}", который привязан к типу параметра. Вместо этого следует использовать тег <typeparamref>.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter_Title">
<source>XML comment has a tag with a 'cref' attribute that bound to a type parameter</source>
<target state="translated">Комментарий XML содержит тег с атрибутом cref, который привязан к параметру типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage">
<source>Linked netmodule metadata must provide a full PE image: '{0}'.</source>
<target state="translated">Связанные метаданные netmodule должны обеспечивать полный образ PE: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated">
<source>An instance of analyzer {0} cannot be created from {1} : {2}.</source>
<target state="translated">Экземпляр анализатора {0} невозможно создать из {1} : {2}"</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated_Title">
<source>Instance of analyzer cannot be created</source>
<target state="translated">Невозможно создать экземпляр анализатора</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly">
<source>The assembly {0} does not contain any analyzers.</source>
<target state="translated">Сборка {0} не содержит анализаторов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly_Title">
<source>Assembly does not contain any analyzers</source>
<target state="translated">Сборка не содержит анализаторов</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer">
<source>Unable to load analyzer assembly {0} : {1}.</source>
<target state="translated">Не удается загрузить анализатор сборки{0}: {1}.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer_Title">
<source>Unable to load analyzer assembly</source>
<target state="translated">Не удалось загрузить сборку анализатора</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer">
<source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source>
<target state="translated">Пропуск некоторых типов в сборке анализатора {0} из-за исключения ReflectionTypeLoadException: {1}.</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title">
<source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source>
<target state="translated">Пропуск загрузки типов в сборке анализатора, завершившихся сбоем из-за ReflectionTypeLoadException</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReadRulesetFile">
<source>Error reading ruleset file {0} - {1}</source>
<target state="translated">Ошибка при чтении файла с набором правил {0} — {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PlatformDoesntSupport">
<source>{0} is not supported in current project type.</source>
<target state="translated">{0} не поддерживается в текущем типе проекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantUseRequiredAttribute">
<source>The RequiredAttribute attribute is not permitted on Visual Basic types.</source>
<target state="translated">Атрибут RequiredAttribute не разрешен для типов Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncodinglessSyntaxTree">
<source>Cannot emit debug information for a source text without encoding.</source>
<target state="translated">Не удается выдать отладочную информацию для исходного текста без кодировки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatSpecifier">
<source>'{0}' is not a valid format specifier</source>
<target state="translated">"{0}" не является допустимым описателем формата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPreprocessorConstantType">
<source>Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed.</source>
<target state="translated">Константа препроцессора "{0}" типа "{1}" не поддерживается, допускаются только примитивные типы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedWarningKeyword">
<source>'Warning' expected.</source>
<target state="translated">'Требуется "Warning".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotBeMadeNullable1">
<source>'{0}' cannot be made nullable.</source>
<target state="translated">"{0}" не может быть стать параметром, допускающим NULL.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConditionalWithRef">
<source>Leading '?' can only appear inside a 'With' statement, but not inside an object member initializer.</source>
<target state="translated">Символ "?" в начале может находиться только внутри оператора "With", но не внутри инициализатора участников объекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullPropagatingOpInExpressionTree">
<source>A null propagating operator cannot be converted into an expression tree.</source>
<target state="translated">Распространяющий NULL оператор невозможно преобразовать в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongOrComplexExpression">
<source>An expression is too long or complex to compile</source>
<target state="translated">Выражение слишком длинное или сложное для компиляции</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionDoesntHaveName">
<source>This expression does not have a name.</source>
<target state="translated">Выражение не имеет имени.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNameOfSubExpression">
<source>This sub-expression cannot be used inside NameOf argument.</source>
<target state="translated">Невозможно использовать подвыражение в аргументе NameOf.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodTypeArgsUnexpected">
<source>Method type arguments unexpected.</source>
<target state="translated">Неожиданные аргументы типа метода.</target>
<note />
</trans-unit>
<trans-unit id="NoNoneSearchCriteria">
<source>SearchCriteria is expected.</source>
<target state="translated">Ожидается SearchCriteria.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCulture">
<source>Assembly culture strings may not contain embedded NUL characters.</source>
<target state="translated">Строки языка и региональных параметров сборки могут не содержать встроенных символов NULL.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InReferencedAssembly">
<source>There is an error in a referenced assembly '{0}'.</source>
<target state="translated">Ошибка в связанной сборке "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationFormatWhitespace">
<source>Format specifier may not contain trailing whitespace.</source>
<target state="translated">Указатель формата может не содержать пробел в конце.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationAlignmentOutOfRange">
<source>Alignment value is outside of the supported range.</source>
<target state="translated">Значение выравнивания находится вне диапазона поддерживаемых значений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolatedStringFactoryError">
<source>There were one or more errors emitting a call to {0}.{1}. Method or its return type may be missing or malformed.</source>
<target state="translated">Возникла одна или несколько ошибок при создании вызова к {0}.{1}. Метод или его тип возвращаемых данных может быть не задан или неправильно сформирован.</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause_Title">
<source>Unused import clause</source>
<target state="translated">Неиспользуемое предложение import</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement_Title">
<source>Unused import statement</source>
<target state="translated">Неиспользуемый оператор import</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantStringTooLong">
<source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source>
<target state="translated">Длина строковой константы, полученной в результате объединения, превышает значение System.Int32.MaxValue. Попробуйте разделить строку на несколько констант.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LanguageVersion">
<source>Visual Basic {0} does not support {1}.</source>
<target state="translated">Visual Basic {0} не поддерживает {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPdbData">
<source>Error reading debug information for '{0}'</source>
<target state="translated">Ошибка чтения отладочной информации для "{0}"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ArrayLiterals">
<source>array literal expressions</source>
<target state="translated">литеральные выражения массива</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AsyncExpressions">
<source>async methods or lambdas</source>
<target state="translated">Асинхронные методы или лямбда-выражения</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AutoProperties">
<source>auto-implemented properties</source>
<target state="translated">автоматически внедренные свойства</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ReadonlyAutoProperties">
<source>readonly auto-implemented properties</source>
<target state="translated">автоматически реализуемые свойства только для чтения</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CoContraVariance">
<source>variance</source>
<target state="translated">расхождение</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CollectionInitializers">
<source>collection initializers</source>
<target state="translated">инициализаторы коллекции</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_GlobalNamespace">
<source>declaring a Global namespace</source>
<target state="translated">объявление глобального пространства имен</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Iterators">
<source>iterators</source>
<target state="translated">итераторы</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuation">
<source>implicit line continuation</source>
<target state="translated">неявное продолжение строки</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_StatementLambdas">
<source>multi-line lambda expressions</source>
<target state="translated">многострочные лямбда-выражения</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_SubLambdas">
<source>'Sub' lambda expressions</source>
<target state="translated">'Лямбда-выражения "Sub"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NullPropagatingOperator">
<source>null conditional operations</source>
<target state="translated">условные операции со значением "null"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NameOfExpressions">
<source>'nameof' expressions</source>
<target state="translated">'выражения "nameof"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_RegionsEverywhere">
<source>region directives within method bodies or regions crossing boundaries of declaration blocks</source>
<target state="translated">директивы region в телах методов или регионах, пересекающих границы блоков объявлений</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_MultilineStringLiterals">
<source>multiline string literals</source>
<target state="translated">строковые литералы из нескольких строк</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CObjInAttributeArguments">
<source>CObj in attribute arguments</source>
<target state="translated">CObj в аргументах атрибута</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuationComments">
<source>line continuation comments</source>
<target state="translated">комментарии продолжения строки</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_TypeOfIsNot">
<source>TypeOf IsNot expression</source>
<target state="translated">Выражение IsNot TypeOf</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_YearFirstDateLiterals">
<source>year-first date literals</source>
<target state="translated">литералы даты с годом на первом месте</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_WarningDirectives">
<source>warning directives</source>
<target state="translated">директивы warning</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialModules">
<source>partial modules</source>
<target state="translated">частичные модули</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialInterfaces">
<source>partial interfaces</source>
<target state="translated">частичные интерфейсы</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite">
<source>implementing read-only or write-only property with read-write property</source>
<target state="translated">реализация свойства только для чтения или только для записи с помощью свойства для чтения и записи</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_DigitSeparators">
<source>digit separators</source>
<target state="translated">цифровые разделители</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_BinaryLiterals">
<source>binary literals</source>
<target state="translated">двоичные литералы</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Tuples">
<source>tuples</source>
<target state="translated">кортежи</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PrivateProtected">
<source>Private Protected</source>
<target state="translated">Частный защищенный</target>
<note />
</trans-unit>
<trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition">
<source>Debug entry point must be a definition of a method declared in the current compilation.</source>
<target state="translated">Точкой входа отладки должно быть определение метода, объявленное в текущей компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPathMap">
<source>The pathmap option was incorrectly formatted.</source>
<target state="translated">Неправильный формат параметра pathmap.</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeIsNotASubmission">
<source>Syntax tree should be created from a submission.</source>
<target state="translated">Дерево синтаксиса должно быть создано из отправки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyUserStrings">
<source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string or XML literals.</source>
<target state="translated">Объединенная длина пользовательских строк, используемых программой, превышает допустимый предел. Попробуйте сократить использование строковых литералов или XML-литералов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PeWritingFailure">
<source>An error occurred while writing the output file: {0}</source>
<target state="translated">Произошла ошибка при записи выходного файла: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionMustBeAbsolutePath">
<source>Option '{0}' must be an absolute path.</source>
<target state="translated">Параметр "{0}" должен быть абсолютным путем.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceLinkRequiresPdb">
<source>/sourcelink switch is only supported when emitting PDB.</source>
<target state="translated">Параметр /sourcelink поддерживается только при создании данных формата PDB.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleDuplicateElementName">
<source>Tuple element names must be unique.</source>
<target state="translated">Имена элементов кортежа должны быть уникальными.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch">
<source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source>
<target state="translated">Имя элемента кортежа "{0}" игнорируется, так как целевым типом "{1}" задано другое имя либо имя не задано.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch_Title">
<source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source>
<target state="translated">Имя элемента кортежа игнорируется, так как целевым объектом назначения задано другое имя либо имя не задано.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementName">
<source>Tuple element name '{0}' is only allowed at position {1}.</source>
<target state="translated">Имя элемента кортежа "{0}" допускается только в позиции {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementNameAnyPosition">
<source>Tuple element name '{0}' is disallowed at any position.</source>
<target state="translated">Имя элемента кортежа "{0}" не допускается ни в одной позиции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleTooFewElements">
<source>Tuple must contain at least two elements.</source>
<target state="translated">Кортеж должен содержать по меньшей мере два элемента.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleElementNamesAttributeMissing">
<source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source>
<target state="translated">Невозможно определить класс или элемент, использующий кортежи, так как не удалось найти необходимый тип компилятора ({0}). Отсутствует ссылка?</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExplicitTupleElementNamesAttribute">
<source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source>
<target state="translated">Невозможно явным образом добавить ссылку на "System.Runtime.CompilerServices.TupleElementNamesAttribute". Используйте синтаксис кортежа для определения имен кортежа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefReturningCallInExpressionTree">
<source>An expression tree may not contain a call to a method or property that returns by reference.</source>
<target state="translated">Дерево выражений не может содержать вызов метода или свойства, которые возвращают данные по ссылке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedWithoutPdb">
<source>/embed switch is only supported when emitting a PDB.</source>
<target state="translated">Параметр /embed поддерживается только при создании PDB-файла.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInstrumentationKind">
<source>Invalid instrumentation kind: {0}</source>
<target state="translated">Недопустимый тип инструментирования: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DocFileGen">
<source>Error writing to XML documentation file: {0}</source>
<target state="translated">Ошибка при записи в XML-файл документации: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAssemblyName">
<source>Invalid assembly name: {0}</source>
<target state="translated">Недопустимое имя сборки: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeForwardedToMultipleAssemblies">
<source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source>
<target state="translated">Модуль "{0}" в сборке "{1}" перенаправляет тип "{2}" в несколько сборок: "{3}" и "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_Merge_conflict_marker_encountered">
<source>Merge conflict marker encountered</source>
<target state="translated">Встретилась отметка о конфликте слияния</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoRefOutWhenRefOnly">
<source>Do not use refout when using refonly.</source>
<target state="translated">Не используйте refout при использовании refonly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly">
<source>Cannot compile net modules when using /refout or /refonly.</source>
<target state="translated">Не удается скомпилировать сетевые модули при использовании /refout или /refonly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNonTrailingNamedArgument">
<source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source>
<target state="translated">Именованный аргумент "{0}" используется не на своем месте, но за ним следует неименованный аргумент</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDocumentationMode">
<source>Provided documentation mode is unsupported or invalid: '{0}'.</source>
<target state="translated">Указанный режим документации не поддерживается или недопустим: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLanguageVersion">
<source>Provided language version is unsupported or invalid: '{0}'.</source>
<target state="translated">Указанная версия языка не поддерживается или недопустима: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSourceCodeKind">
<source>Provided source code kind is unsupported or invalid: '{0}'</source>
<target state="translated">Указанный тип исходного кода не поддерживается или недопустим: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleInferredNamesNotAvailable">
<source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source>
<target state="translated">Имя элемента кортежа "{0}" является выведенным. Для обращения к элементу по выведенному имени используйте версию языка {1} или более позднюю.</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental">
<source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">"{0}" предназначен только для оценки и может быть изменен или удален в будущих обновлениях.</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental_Title">
<source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">Тип предназначен только для оценки и может быть изменен или удален в будущих обновлениях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInfo">
<source>Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}'</source>
<target state="translated">Не удается считать сведения об отладке метода "{0}" (маркер 0x{1}) из сборки "{2}".</target>
<note />
</trans-unit>
<trans-unit id="IConversionExpressionIsNotVisualBasicConversion">
<source>{0} is not a valid Visual Basic conversion expression</source>
<target state="translated">{0} не является допустимым выражением преобразования Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="IArgumentIsNotVisualBasicArgument">
<source>{0} is not a valid Visual Basic argument</source>
<target state="translated">{0} не является допустимым аргументом Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LeadingDigitSeparator">
<source>leading digit separator</source>
<target state="translated">разделитель начальных цифр</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleResolutionAmbiguous3">
<source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source>
<target state="translated">Предопределенный тип "{0}" объявлен в нескольких сборках, на которые имеются ссылки: "{1}" и "{2}"</target>
<note />
</trans-unit>
<trans-unit id="ICompoundAssignmentOperationIsNotVisualBasicCompoundAssignment">
<source>{0} is not a valid Visual Basic compound assignment operation</source>
<target state="translated">{0} не является допустимой операцией составного назначения Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHashAlgorithmName">
<source>Invalid hash algorithm name: '{0}'</source>
<target state="translated">Недопустимое имя хэш-алгоритма: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InterpolatedStrings">
<source>interpolated strings</source>
<target state="translated">интерполированные строки</target>
<note />
</trans-unit>
<trans-unit id="FTL_InvalidInputFileName">
<source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source>
<target state="translated">Имя файла "{0}" пустое, содержит недопустимые символы, имеет имя диска без абсолютного пути или слишком длинное.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB">
<source>'{0}' is not supported in VB.</source>
<target state="translated">"{0}" не поддерживается в VB.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB_Title">
<source>Attribute is not supported in VB</source>
<target state="translated">Атрибут не поддерживается в VB</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="ru" original="../VBResources.resx">
<body>
<trans-unit id="ERR_AssignmentInitOnly">
<source>Init-only property '{0}' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor.</source>
<target state="translated">Свойство "{0}", доступное только для инициализации, можно назначать только c помощью инициализатора элемента объекта или для "Me", "MyClass" или "MyBase" в конструкторе экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSwitchValue">
<source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source>
<target state="translated">Ошибка в синтаксисе командной строки: "{0}" не является допустимым значением для параметра "{1}". Значение должно иметь форму "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CommentsAfterLineContinuationNotAvailable1">
<source>Please use language version {0} or greater to use comments after line continuation character.</source>
<target state="translated">Используйте версию языка {0} или более позднюю, чтобы использовать комментарии после символа продолжения строки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">Не удается внедрить тип "{0}", так как он имеет неабстрактный член. Попробуйте задать для свойства "Внедрить типы взаимодействия" значение false.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir">
<source>Multiple analyzer config files cannot be in the same directory ('{0}').</source>
<target state="translated">В одном каталоге ("{0}") не может находиться несколько файлов конфигурации анализатора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingInitOnlyProperty">
<source>'{0}' cannot override init-only '{1}'.</source>
<target state="translated">"{0}" не может переопределить свойство "{1}", предназначенное только для инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementInitOnly">
<source>Init-only '{0}' cannot be implemented.</source>
<target state="translated">Невозможно реализовать свойство "{0}", предназначенное только для инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReAbstractionInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">Невозможно внедрить тип "{0}", так как он переопределяет абстракцию элемента базового интерфейса. Попробуйте задать для свойства "Внедрить типы взаимодействия" значение false (ложь).</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation">
<source>Target runtime doesn't support default interface implementation.</source>
<target state="translated">Целевая среда выполнения не поддерживает реализацию интерфейса по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember">
<source>Target runtime doesn't support 'Protected', 'Protected Friend', or 'Private Protected' accessibility for a member of an interface.</source>
<target state="translated">Целевая среда выполнения не поддерживает доступ "Protected", "Protected Friend" или "Private Protected" для элемента интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsHandlerInTheSameType">
<source>Events of shared WithEvents variables cannot be handled by methods in a different type.</source>
<target state="translated">События общих переменных WithEvents не могут обрабатывать методы другого типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnmanagedCallersOnlyNotSupported">
<source>'UnmanagedCallersOnly' attribute is not supported.</source>
<target state="translated">Атрибут "UnmanagedCallersOnly" не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CallerArgumentExpression">
<source>caller argument expression</source>
<target state="new">caller argument expression</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CommentsAfterLineContinuation">
<source>comments after line continuation</source>
<target state="translated">комментарии после продолжения строки</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InitOnlySettersUsage">
<source>assigning to or passing 'ByRef' properties with init-only setters</source>
<target state="translated">назначение свойств "ByRef" или их передача с помощью методов задания, предназначенных только для инициализации</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_UnconstrainedTypeParameterInConditional">
<source>unconstrained type parameters in binary conditional expressions</source>
<target state="translated">параметры неограниченного типа в двоичных условных выражениях</target>
<note />
</trans-unit>
<trans-unit id="IDS_VBCHelp">
<source> Visual Basic Compiler Options
- OUTPUT FILE -
-out:<file> Specifies the output file name.
-target:exe Create a console application (default).
(Short form: -t)
-target:winexe Create a Windows application.
-target:library Create a library assembly.
-target:module Create a module that can be added to an
assembly.
-target:appcontainerexe Create a Windows application that runs in
AppContainer.
-target:winmdobj Create a Windows Metadata intermediate file
-doc[+|-] Generates XML documentation file.
-doc:<file> Generates XML documentation file to <file>.
-refout:<file> Reference assembly output to generate
- INPUT FILES -
-addmodule:<file_list> Reference metadata from the specified modules
-link:<file_list> Embed metadata from the specified interop
assembly. (Short form: -l)
-recurse:<wildcard> Include all files in the current directory
and subdirectories according to the
wildcard specifications.
-reference:<file_list> Reference metadata from the specified
assembly. (Short form: -r)
-analyzer:<file_list> Run the analyzers from this assembly
(Short form: -a)
-additionalfile:<file list> Additional files that don't directly affect code
generation but may be used by analyzers for producing
errors or warnings.
- RESOURCES -
-linkresource:<resinfo> Links the specified file as an external
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -linkres)
-nowin32manifest The default manifest should not be embedded
in the manifest section of the output PE.
-resource:<resinfo> Adds the specified file as an embedded
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -res)
-win32icon:<file> Specifies a Win32 icon file (.ico) for the
default Win32 resources.
-win32manifest:<file> The provided file is embedded in the manifest
section of the output PE.
-win32resource:<file> Specifies a Win32 resource file (.res).
- CODE GENERATION -
-optimize[+|-] Enable optimizations.
-removeintchecks[+|-] Remove integer checks. Default off.
-debug[+|-] Emit debugging information.
-debug:full Emit full debugging information (default).
-debug:pdbonly Emit full debugging information.
-debug:portable Emit cross-platform debugging information.
-debug:embedded Emit cross-platform debugging information into
the target .dll or .exe.
-deterministic Produce a deterministic assembly
(including module version GUID and timestamp)
-refonly Produce a reference assembly in place of the main output
-instrument:TestCoverage Produce an assembly instrumented to collect
coverage information
-sourcelink:<file> Source link info to embed into PDB.
- ERRORS AND WARNINGS -
-nowarn Disable all warnings.
-nowarn:<number_list> Disable a list of individual warnings.
-warnaserror[+|-] Treat all warnings as errors.
-warnaserror[+|-]:<number_list> Treat a list of warnings as errors.
-ruleset:<file> Specify a ruleset file that disables specific
diagnostics.
-errorlog:<file>[,version=<sarif_version>]
Specify a file to log all compiler and analyzer
diagnostics in SARIF format.
sarif_version:{1|2|2.1} Default is 1. 2 and 2.1
both mean SARIF version 2.1.0.
-reportanalyzer Report additional analyzer information, such as
execution time.
-skipanalyzers[+|-] Skip execution of diagnostic analyzers.
- LANGUAGE -
-define:<symbol_list> Declare global conditional compilation
symbol(s). symbol_list:name=value,...
(Short form: -d)
-imports:<import_list> Declare global Imports for namespaces in
referenced metadata files.
import_list:namespace,...
-langversion:? Display the allowed values for language version
-langversion:<string> Specify language version such as
`default` (latest major version), or
`latest` (latest version, including minor versions),
or specific versions like `14` or `15.3`
-optionexplicit[+|-] Require explicit declaration of variables.
-optioninfer[+|-] Allow type inference of variables.
-rootnamespace:<string> Specifies the root Namespace for all type
declarations.
-optionstrict[+|-] Enforce strict language semantics.
-optionstrict:custom Warn when strict language semantics are not
respected.
-optioncompare:binary Specifies binary-style string comparisons.
This is the default.
-optioncompare:text Specifies text-style string comparisons.
- MISCELLANEOUS -
-help Display this usage message. (Short form: -?)
-noconfig Do not auto-include VBC.RSP file.
-nologo Do not display compiler copyright banner.
-quiet Quiet output mode.
-verbose Display verbose messages.
-parallel[+|-] Concurrent build.
-version Display the compiler version number and exit.
- ADVANCED -
-baseaddress:<number> The base address for a library or module
(hex).
-checksumalgorithm:<alg> Specify algorithm for calculating source file
checksum stored in PDB. Supported values are:
SHA1 or SHA256 (default).
-codepage:<number> Specifies the codepage to use when opening
source files.
-delaysign[+|-] Delay-sign the assembly using only the public
portion of the strong name key.
-publicsign[+|-] Public-sign the assembly using only the public
portion of the strong name key.
-errorreport:<string> Specifies how to handle internal compiler
errors; must be prompt, send, none, or queue
(default).
-filealign:<number> Specify the alignment used for output file
sections.
-highentropyva[+|-] Enable high-entropy ASLR.
-keycontainer:<string> Specifies a strong name key container.
-keyfile:<file> Specifies a strong name key file.
-libpath:<path_list> List of directories to search for metadata
references. (Semi-colon delimited.)
-main:<class> Specifies the Class or Module that contains
Sub Main. It can also be a Class that
inherits from System.Windows.Forms.Form.
(Short form: -m)
-moduleassemblyname:<string> Name of the assembly which this module will
be a part of.
-netcf Target the .NET Compact Framework.
-nostdlib Do not reference standard libraries
(system.dll and VBC.RSP file).
-pathmap:<K1>=<V1>,<K2>=<V2>,...
Specify a mapping for source path names output by
the compiler.
-platform:<string> Limit which platforms this code can run on;
must be x86, x64, Itanium, arm, arm64
AnyCPU32BitPreferred or anycpu (default).
-preferreduilang Specify the preferred output language name.
-nosdkpath Disable searching the default SDK path for standard library assemblies.
-sdkpath:<path> Location of the .NET Framework SDK directory
(mscorlib.dll).
-subsystemversion:<version> Specify subsystem version of the output PE.
version:<number>[.<number>]
-utf8output[+|-] Emit compiler output in UTF8 character
encoding.
@<file> Insert command-line settings from a text file
-vbruntime[+|-|*] Compile with/without the default Visual Basic
runtime.
-vbruntime:<file> Compile with the alternate Visual Basic
runtime in <file>.
</source>
<target state="translated"> Параметры компилятора Visual Basic
- Выходной файл -
-out:<file> Задает имя выходного файла.
-target:exe Создать консольное приложение (по умолчанию).
(Краткая форма: -t)
-target:winexe Создать Windows-приложение.
-target:library Создать библиотечную сборку.
-target:module Создать модуль, который может быть добавлен в
сборку.
-target:appcontainerexe Создать Windows-приложение, выполняемое в контейнере
AppContainer.
-target:winmdobj Создать промежуточный файл метаданных Windows
-doc[+|-] Создает XML-файл документации.
-doc:<file> Создает XML-файл документации <file>.
-refout:<file> Выходные данные создаваемой базовой сборки
- Входные файлы -
-addmodule:<file_list> Ссылка на метаданные из заданных модулей
-link:<file_list> Внедрить метаданные из указанной сборки
взаимодействия. (Краткая форма: -l)
-recurse:<wildcard> Включить все файлы в текущем каталоге
и подкаталогах в соответствии с
заданным шаблоном.
-reference:<file_list> Ссылка на метаданные из заданной
сборки. (Краткая форма: -r)
-analyzer:<file_list> Запускать анализаторы из этой сборки
(Краткая форма: -a)
-additionalfile:<file list> Дополнительные файлы, которые не оказывают прямого влияния на создание
кода, но могут использоваться анализаторами для вывода
ошибок или предупреждений.
- Ресурсы -
-linkresource:<resinfo> Привязывает указанный файл в качестве внешнего
ресурса сборки.
Данные о ресурсе:<file>[,<name>[,public|private]]
(Краткая форма: -linkres)
-nowin32manifest Манифест по умолчанию не должен внедряться
в раздел манифеста выходного PE-файла.
-resource:<resinfo> Добавляет указанный файл в качестве внедренного
ресурса сборки.
Данные о ресурсе:<file>[,<name>[,public|private]]
(Краткая форма: -res)
-win32icon:<file> Задает файл значка Win32 (ICO-файл) для
ресурсов Win32 по умолчанию.
-win32manifest:<file> Предоставленный файл внедряется в раздел
манифеста выходного PE-файла.
-win32resource:<file> Задает файл ресурсов Win32 (RES-файл).
- Создание кода -
-optimize[+|-] Включить оптимизацию.
-removeintchecks[+|-] Удалить целочисленные проверки. По умолчанию отключены.
-debug[+|-] Выдать отладочные данные.
-debug:full Выдать полные отладочные данные (по умолчанию).
-debug:pdbonly Выдать полные отладочные данные.
-debug:portable Выдать кроссплатформенные отладочные данные.
-debug:embedded Выдать кроссплатформенные отладочные данные в
целевой DLL-файл или EXE-файл.
-deterministic Создать детерминированную сборку
(включая GUID версии модуля и метку времени)
-refonly Создавать базовую сборку вместо основных выходных данных
-instrument:TestCoverage Создавать сборку, инструментированную для сбора
данных об объеме протестированного кода
-sourcelink:<file> Данные о ссылке на исходные файлы для внедрения в PDB.
- Ошибки и предупреждения -
-nowarn Отключить все предупреждения.
-nowarn:<number_list> Отключить отдельные предупреждения по списку.
-warnaserror[+|-] Обрабатывать все предупреждения как ошибки.
-warnaserror[+|-]:<number_list> Обрабатывать список предупреждений как ошибки.
-ruleset:<file> Указать файл набора правил, отключающий определенные
диагностические операции.
-errorlog:<file>[,version=<sarif_version>]
Указать файл для записи всех диагностических данных
компилятора и анализатора в формате SARIF.
sarif_version:{1|2|2.1} По умолчанию используются значения 1. 2 и 2.1,
обозначающие версию SARIF 2.1.0.
-reportanalyzer Сообщить дополнительные сведения об анализаторе, например
время выполнения.
-skipanalyzers[+|-] Пропустить выполнение анализаторов диагностики.
- Язык -
-define:<symbol_list> Объявить глобальные символы условной
компиляции. symbol_list:имя=значение,...
(Краткая форма: -d)
-imports:<import_list> Объявить глобальные импорты для пространств имен в
указанных файлах метаданных.
import_list:пространство_имен,...
-langversion:? Отображать допустимые значения версии языка
-langversion:<string> Указать версию языка, например
"default" (последний основной номер версии) или
"latest" (последняя версия, включая дополнительные номера),
или конкретные версии, например 14 или 15.3
-optionexplicit[+|-] Требовать явное объявление переменных.
-optioninfer[+|-] Разрешить вывод для типов переменных.
-rootnamespace:<string> Задает корневое пространство имен для всех объявлений
типов.
-optionstrict[+|-] Требовать строгую семантику языка.
-optionstrict:custom Предупреждать, когда не соблюдается строгая семантика
языка.
-optioncompare:binary Задает сравнение строк как двоичных данных.
Задано по умолчанию.
-optioncompare:text Задает сравнение строк как текста.
- Прочее -
-help Отображать это сообщение об использовании. (Краткая форма: -?)
-noconfig Не включать файл VBC.RSP в состав автоматически.
-nologo Не отображать заставку компилятора с информацией об авторских правах.
-quiet Режим вывода без сообщений.
-verbose Отображать подробные сообщения.
-parallel[+|-] Параллельная сборка.
-version Отобразить номер версии компилятора и выйти.
- Дополнительно -
-baseaddress:<number> Базовый адрес библиотеки или модуля
(шестнадцатеричный).
-checksumalgorithm:<alg> Задать алгоритм расчета контрольной суммы
исходного файла, хранимой в PDB. Поддерживаемые значения:
SHA1 или SHA256 (по умолчанию).
-codepage:<number> Указывает кодовую страницу, используемую при открытии
исходных файлов.
-delaysign[+|-] Использовать отложенную подпись для сборки, применяя только
открытую часть ключа строгого имени.
-publicsign[+|-] Выполнить общедоступную подпись сборки, используя только открытую
часть ключа строгого имени.
-errorreport:<string> Указывает способ обработки внутренних ошибок
компилятора; принимает prompt, send, none или queue
(по умолчанию).
-filealign:<number> Задать выравнивание для разделов выходных
файлов.
-highentropyva[+|-] Включить ASLR с высокой энтропией.
-keycontainer:<string> Задает контейнер ключа строгого имени.
-keyfile:<file> Задает файл ключа строгого имени.
-libpath:<path_list> Список каталогов для поиска ссылок на
метаданные. (Разделитель — точка с запятой.)
-main:<class> Задает класс или модуль, содержащий
Sub Main. Он может являться производным
классом от System.Windows.Forms.Form.
(Краткая форма: -m)
-moduleassemblyname:<string> Имя сборки, частью которой будет
данный модуль.
-netcf Целевая версия .NET Compact Framework.
-nostdlib Не обращаться к стандартным библиотекам
(файл system.dll и VBC.RSP).
-pathmap:<K1>=<V1>,<K2>=<V2>,...
Указать сопоставление для выходных данных имен исходного пути по
компилятору.
-platform:<string> Ограничить платформы, на которых может выполняться этот код:
x86, x64, Itanium, arm, arm64
AnyCPU32BitPreferred или anycpu (по умолчанию).
-preferreduilang Указать имя предпочтительного языка вывода.
-nosdkpath Отключить поиск пути пакета SDK по умолчанию для сборок стандартных библиотек.
-sdkpath:<path> Расположение каталога пакета SDK .NET Framework
(mscorlib.dll).
-subsystemversion:<version> Указать версию подсистемы выходного PE-файла.
version:<number>[.<number>]
-utf8output[+|-] Выдавать выходные данные компилятора в кодировке
UTF8.
@<file> Вставить параметры командной строки из текстового файла
-vbruntime[+|-|*] Скомпилировать с помощью или без использования стандартной среды выполнения
Visual Basic.
-vbruntime:<file> Скомпилировать с помощью альтернативной среды выполнения
Visual Basic в <file>.
</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoFunctionPointerTypesInVB">
<source>There are no function pointer types in VB.</source>
<target state="translated">В VB отсутствуют типы указателей на функции.</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoNativeIntegerTypesInVB">
<source>There are no native integer types in VB.</source>
<target state="translated">В VB нет собственных целочисленных типов.</target>
<note />
</trans-unit>
<trans-unit id="Trees0">
<source>trees({0})</source>
<target state="translated">деревья({0})</target>
<note />
</trans-unit>
<trans-unit id="TreesMustHaveRootNode">
<source>trees({0}) must have root node with SyntaxKind.CompilationUnit.</source>
<target state="translated">Деревья({0}) должны иметь корневой узел SyntaxKind.CompilationUnit.</target>
<note />
</trans-unit>
<trans-unit id="CannotAddCompilerSpecialTree">
<source>Cannot add compiler special tree</source>
<target state="translated">Не удается добавить особое дерево компилятора</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeAlreadyPresent">
<source>Syntax tree already present</source>
<target state="translated">Синтаксическое дерево уже имеется</target>
<note />
</trans-unit>
<trans-unit id="SubmissionCanHaveAtMostOneSyntaxTree">
<source>Submission can have at most one syntax tree.</source>
<target state="translated">Отправка может иметь максимум одно синтаксическое дерево.</target>
<note />
</trans-unit>
<trans-unit id="CannotRemoveCompilerSpecialTree">
<source>Cannot remove compiler special tree</source>
<target state="translated">Не удается удалить особое дерево компилятора</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeNotFoundToRemove">
<source>SyntaxTree '{0}' not found to remove</source>
<target state="translated">SyntaxTree "{0}" не найдено и не будет удалено.</target>
<note />
</trans-unit>
<trans-unit id="TreeMustHaveARootNodeWithCompilationUnit">
<source>Tree must have a root node with SyntaxKind.CompilationUnit</source>
<target state="translated">Деревья должны иметь корневой узел SyntaxKind.CompilationUnit.</target>
<note />
</trans-unit>
<trans-unit id="CompilationVisualBasic">
<source>Compilation (Visual Basic): </source>
<target state="translated">Компиляция (Visual Basic):</target>
<note />
</trans-unit>
<trans-unit id="NodeIsNotWithinSyntaxTree">
<source>Node is not within syntax tree</source>
<target state="translated">Узел не входит в синтаксическое дерево.</target>
<note />
</trans-unit>
<trans-unit id="CantReferenceCompilationFromTypes">
<source>Can't reference compilation of type '{0}' from {1} compilation.</source>
<target state="translated">Не удается создать ссылку на компиляцию типа "{0}" из компиляции {1}.</target>
<note />
</trans-unit>
<trans-unit id="PositionOfTypeParameterTooLarge">
<source>position of type parameter too large</source>
<target state="translated">Позиция типа параметра является слишком большой.</target>
<note />
</trans-unit>
<trans-unit id="AssociatedTypeDoesNotHaveTypeParameters">
<source>Associated type does not have type parameters</source>
<target state="translated">У связанного типа отсутствуют параметры типа.</target>
<note />
</trans-unit>
<trans-unit id="IDS_FunctionReturnType">
<source>function return type</source>
<target state="translated">тип возвращаемого функцией значения</target>
<note />
</trans-unit>
<trans-unit id="TypeArgumentCannotBeNothing">
<source>Type argument cannot be Nothing</source>
<target state="translated">Аргумент типа не может иметь значение Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework">
<source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source>
<target state="translated">Сборка "{0}", содержащая тип "{1}", ссылается на платформу .NET Framework, которая не поддерживается.</target>
<note>{1} is the type that was loaded, {0} is the containing assembly.</note>
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework_Title">
<source>The loaded assembly references .NET Framework, which is not supported.</source>
<target state="translated">Загруженная сборка ссылается на платформу .NET Framework, которая не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration">
<source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">Генератору "{0}" не удалось создать источник. Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}"</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">Генератор создал следующее исключение:
"{0}".</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Title">
<source>Generator failed to generate source.</source>
<target state="translated">Генератору не удалось создать источник.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization">
<source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">Не удалось инициализировать генератор "{0}". Это не повлияет на выходные данные и ошибки компиляции, которые могут возникнуть в результате. Тип возникшего исключения: "{1}", сообщение: "{2}"</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">Генератор создал следующее исключение:
"{0}".</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Title">
<source>Generator failed to initialize.</source>
<target state="translated">Не удалось инициализировать генератор.</target>
<note />
</trans-unit>
<trans-unit id="WrongNumberOfTypeArguments">
<source>Wrong number of type arguments</source>
<target state="translated">Неверное число аргументов типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileNotFound">
<source>file '{0}' could not be found</source>
<target state="translated">Не удалось найти файл "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoResponseFile">
<source>unable to open response file '{0}'</source>
<target state="translated">Не удается открыть файл ответов "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentRequired">
<source>option '{0}' requires '{1}'</source>
<target state="translated">параметр "{0}" требует "{1}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_SwitchNeedsBool">
<source>option '{0}' can be followed only by '+' or '-'</source>
<target state="translated">за параметром "{0}" может следовать только "+" или "-"</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSwitchValue">
<source>the value '{1}' is invalid for option '{0}'</source>
<target state="translated">значение "{1}" недопустимо для параметра "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_MutuallyExclusiveOptions">
<source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source>
<target state="translated">Параметры компиляции "{0}" и "{1}" невозможно использовать одновременно.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang">
<source>The language name '{0}' is invalid.</source>
<target state="translated">Недопустимое имя языка "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang_Title">
<source>The language name for /preferreduilang is invalid</source>
<target state="translated">Название языка для /preferreduilang недопустимо</target>
<note />
</trans-unit>
<trans-unit id="ERR_VBCoreNetModuleConflict">
<source>The options /vbruntime* and /target:module cannot be combined.</source>
<target state="translated">Невозможно объединить параметры /vbruntime* и /target:module.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatForGuidForOption">
<source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source>
<target state="translated">Ошибка в синтаксисе командной строки: Недопустимый формат Guid "{0}" для параметра "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingGuidForOption">
<source>Command-line syntax error: Missing Guid for option '{1}'</source>
<target state="translated">Ошибка в синтаксисе командной строки: Отсутствует Guid для параметра "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadChecksumAlgorithm">
<source>Algorithm '{0}' is not supported</source>
<target state="translated">Алгоритм "{0}" не поддерживается</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch">
<source>unrecognized option '{0}'; ignored</source>
<target state="translated">нераспознанный параметр "{0}"; проигнорирован</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch_Title">
<source>Unrecognized command-line option</source>
<target state="translated">Нераспознанный параметр командной строки</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSources">
<source>no input sources specified</source>
<target state="translated">не задано входящих источников</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded">
<source>source file '{0}' specified multiple times</source>
<target state="translated">Исходный файл "{0}" задан несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded_Title">
<source>Source file specified multiple times</source>
<target state="translated">Исходный файл указан несколько раз</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOpenFileWrite">
<source>can't open '{0}' for writing: {1}</source>
<target state="translated">не удается открыть "{0}" для записи: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCodepage">
<source>code page '{0}' is invalid or not installed</source>
<target state="translated">Кодовая страница "{0}" является недопустимой или не установлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryFile">
<source>the file '{0}' is not a text file</source>
<target state="translated">файл "{0}" не является текстовым</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibNotFound">
<source>could not find library '{0}'</source>
<target state="translated">Не удалось найти библиотеку "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataReferencesNotSupported">
<source>Metadata references not supported.</source>
<target state="translated">Ссылки на метаданные не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IconFileAndWin32ResFile">
<source>cannot specify both /win32icon and /win32resource</source>
<target state="translated">Не удается определить /win32icon и /win32resource</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile">
<source>ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">Параметр /noconfig проигнорирован, потому что он задан в файле ответов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile_Title">
<source>Ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">Параметр /noconfig пропущен, т. к. он задан в файле ответов</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId">
<source>warning number '{0}' for the option '{1}' is either not configurable or not valid</source>
<target state="translated">Номер предупреждения "{0}" для параметра "{1}" не настраивается или недопустим</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId_Title">
<source>Warning number is either not configurable or not valid</source>
<target state="translated">Номер предупреждения недоступен для настройки или недопустим</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSourcesOut">
<source>cannot infer an output file name from resource only input files; provide the '/out' option</source>
<target state="translated">Не удалось определить имя выходного файла из ресурса только входных файлов; укажите параметр "/out"</target>
<note />
</trans-unit>
<trans-unit id="ERR_NeedModule">
<source>the /moduleassemblyname option may only be specified when building a target of type 'module'</source>
<target state="translated">Параметр /moduleassemblyname может использоваться только при создании типа "module"</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyName">
<source>'{0}' is not a valid value for /moduleassemblyname</source>
<target state="translated">"{0}" не является допустимым значением для /moduleassemblyname</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingManifestSwitches">
<source>Error embedding Win32 manifest: Option /win32manifest conflicts with /nowin32manifest.</source>
<target state="translated">Ошибка при внедрении манифеста Win32: Параметр /win32manifest конфликтует с /nowin32manifest.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest">
<source>Option /win32manifest ignored. It can be specified only when the target is an assembly.</source>
<target state="translated">Параметр / win32manifest игнорируется. Он может быть задан, только если целевым объектом является сборка.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest_Title">
<source>Option /win32manifest ignored</source>
<target state="translated">Параметр /win32manifest пропускается</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInNamespace">
<source>Statement is not valid in a namespace.</source>
<target state="translated">Не допускается применение операторов в пространствах имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedType1">
<source>Type '{0}' is not defined.</source>
<target state="translated">Тип "{0}" не определен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNext">
<source>'Next' expected.</source>
<target state="translated">'Требуется "Next".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCharConstant">
<source>Character constant must contain exactly one character.</source>
<target state="translated">Символьная константа должна содержать ровно один символ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssemblyEvent3">
<source>Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется сборка, содержащая определение события "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModuleEvent3">
<source>Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется ссылка, содержащая определение события "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbExpectedEndIf">
<source>'#If' block must end with a matching '#End If'.</source>
<target state="translated">'Блок "#If" должен завершаться соответствующим блоком "#End If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbNoMatchingIf">
<source>'#ElseIf', '#Else', or '#End If' must be preceded by a matching '#If'.</source>
<target state="translated">'Блоку "#ElseIf", "#Else" или "#End If" должен предшествовать соответствующий оператор "#If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbBadElseif">
<source>'#ElseIf' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'Блоку "#ElseIf" должен предшествовать соответствующий блок "#If" или "#ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromRestrictedType1">
<source>Inheriting from '{0}' is not valid.</source>
<target state="translated">Наследование от "{0}" недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvOutsideProc">
<source>Labels are not valid outside methods.</source>
<target state="translated">Метки за пределами методов недействительны.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantImplement">
<source>Delegates cannot implement interface methods.</source>
<target state="translated">Делегаты не могут реализовывать методы интерфейсов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantHandleEvents">
<source>Delegates cannot handle events.</source>
<target state="translated">Делегаты не могут обрабатывать события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorRequiresReferenceTypes1">
<source>'Is' operator does not accept operands of type '{0}'. Operands must be reference or nullable types.</source>
<target state="translated">'Оператор "Is" не принимает операнды типа "{0}". Операнды должны быть ссылочными типами или типами, допускающими значения Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfRequiresReferenceType1">
<source>'TypeOf ... Is' requires its left operand to have a reference type, but this operand has the value type '{0}'.</source>
<target state="translated">'"TypeOf ... Is" требует, чтобы левый операнд имел ссылочный тип, но этот операнд имеет тип значения "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasSet">
<source>Properties declared 'ReadOnly' cannot have a 'Set'.</source>
<target state="translated">Свойства, объявленные как доступные только для чтения (ReadOnly), не могут иметь метод "Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasGet">
<source>Properties declared 'WriteOnly' cannot have a 'Get'.</source>
<target state="translated">Свойства, объявленные как доступные только для записи (WriteOnly), не могут иметь метод Get.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideProc">
<source>Statement is not valid inside a method.</source>
<target state="translated">Недопустимый оператор в методе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideBlock">
<source>Statement is not valid inside '{0}' block.</source>
<target state="translated">Недопустимый оператор в блоке "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedExpressionStatement">
<source>Expression statement is only allowed at the end of an interactive submission.</source>
<target state="translated">Выражение оператора допускается только в конце интерактивной отправки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndProp">
<source>Property missing 'End Property'.</source>
<target state="translated">В свойстве отсутствует "End Property".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSubExpected">
<source>'End Sub' expected.</source>
<target state="translated">'Требуется "End Sub".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndFunctionExpected">
<source>'End Function' expected.</source>
<target state="translated">'Требуется "End Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseNoMatchingIf">
<source>'#Else' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'Блоку "#Else" должен предшествовать соответствующий блок "#If" или "#ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantRaiseBaseEvent">
<source>Derived classes cannot raise base class events.</source>
<target state="translated">Производные классы не могут генерировать события базовых классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryWithoutCatchOrFinally">
<source>Try must have at least one 'Catch' or a 'Finally'.</source>
<target state="translated">Оператор "Try" должен содержать хотя бы один блок "Catch" или "Finally".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventsCantBeFunctions">
<source>Events cannot have a return type.</source>
<target state="translated">Событиям невозможно задать возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndBrack">
<source>Bracketed identifier is missing closing ']'.</source>
<target state="translated">У идентификатора в квадратных скобках отсутствует закрывающая скобка "]".</target>
<note />
</trans-unit>
<trans-unit id="ERR_Syntax">
<source>Syntax error.</source>
<target state="translated">Синтаксическая ошибка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_Overflow">
<source>Overflow.</source>
<target state="translated">Переполнение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalChar">
<source>Character is not valid.</source>
<target state="translated">Недопустимый символ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected">
<source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source>
<target state="translated">Указан аргумент stdin "-", но входные данные не были перенаправлены из стандартного входного потока.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectOperand1">
<source>Option Strict On prohibits operands of type Object for operator '{0}'.</source>
<target state="translated">Option Strict On запрещает операнды типа Object для оператора "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotBeProperty">
<source>Loop control variable cannot be a property or a late-bound indexed array.</source>
<target state="translated">Переменной цикла не может являться свойство или проиндексированный массив с поздним связыванием.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodBodyNotAtLineStart">
<source>First statement of a method body cannot be on the same line as the method declaration.</source>
<target state="translated">Первый оператор тела метода не может находиться на одной строке с объявлением этого метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MaximumNumberOfErrors">
<source>Maximum number of errors has been exceeded.</source>
<target state="translated">Превышено допустимое число ошибок.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordNotInInstanceMethod1">
<source>'{0}' is valid only within an instance method.</source>
<target state="translated">"{0}" допускается только в методе экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromStructure1">
<source>'{0}' is not valid within a structure.</source>
<target state="translated">"{0}" не является допустимым в структуре.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor1">
<source>Attribute constructor has a parameter of type '{0}', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types.</source>
<target state="translated">Конструктор атрибута имеет параметр типа "{0}", который не является ни целым числом или числом с плавающей запятой, ни перечислением, ни параметром одного из следующих типов: Object, Char, String, Boolean или System.Type, ни одномерным массивом этих типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWithOptArgs">
<source>Method cannot have both a ParamArray and Optional parameters.</source>
<target state="translated">Метод не может одновременно иметь параметры ParamArray и Optional.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedArray1">
<source>'{0}' statement requires an array.</source>
<target state="translated">'Оператор "{0}" требует массив.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayNotArray">
<source>ParamArray parameter must be an array.</source>
<target state="translated">Параметр ParamArray должен быть массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayRank">
<source>ParamArray parameter must be a one-dimensional array.</source>
<target state="translated">Параметр ParamArray должен быть одномерным массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayRankLimit">
<source>Array exceeds the limit of 32 dimensions.</source>
<target state="translated">Число измерений массива превышает максимально допустимое значение 32.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsNewArray">
<source>Arrays cannot be declared with 'New'.</source>
<target state="translated">Массивы не могут объявляться с помощью ключевого слова "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs1">
<source>Too many arguments to '{0}'.</source>
<target state="translated">Слишком много аргументов для "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedCase">
<source>Statements and labels are not valid between 'Select Case' and first 'Case'.</source>
<target state="translated">Операторы и метки между "Select Case" и первым блоком "Case" недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstExpr">
<source>Constant expression is required.</source>
<target state="translated">Требуется константное выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression.</source>
<target state="translated">Преобразование "{0}" в "{1}" не может происходить в константном выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMe">
<source>'Me' cannot be the target of an assignment.</source>
<target state="translated">'"Me" не может присваиваться значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyAssignment">
<source>'ReadOnly' variable cannot be the target of an assignment.</source>
<target state="translated">'Доступной только для чтения (ReadOnly) переменной нельзя присвоить значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSubOfFunc">
<source>'Exit Sub' is not valid in a Function or Property.</source>
<target state="translated">'Использование оператора "Exit Sub" в функциях и свойствах недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitPropNot">
<source>'Exit Property' is not valid in a Function or Sub.</source>
<target state="translated">'Использование оператора "Exit Property" в функциях и подпрограммах недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitFuncOfSub">
<source>'Exit Function' is not valid in a Sub or Property.</source>
<target state="translated">'Использование оператора "Exit Function" в подпрограммах и свойствах недопустимо.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LValueRequired">
<source>Expression is a value and therefore cannot be the target of an assignment.</source>
<target state="translated">Выражение является значением, поэтому ему нельзя ничего присваивать.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForIndexInUse1">
<source>For loop control variable '{0}' already in use by an enclosing For loop.</source>
<target state="translated">Управляющая переменная цикла For "{0}" уже используется вложенным циклом For.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextForMismatch1">
<source>Next control variable does not match For loop control variable '{0}'.</source>
<target state="translated">Следующая переменная элемента управления не соответствует переменной "{0}" цикла For.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseElseNoSelect">
<source>'Case Else' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'"Case Else" может использоваться только в теле оператора "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseNoSelect">
<source>'Case' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'"Case" может использоваться только в теле оператора "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAssignToConst">
<source>Constant cannot be the target of an assignment.</source>
<target state="translated">Константе нельзя ничего присваивать.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedSubscript">
<source>Named arguments are not valid as array subscripts.</source>
<target state="translated">Недопустимо использовать именованные аргументы как индексы массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndIf">
<source>'If' must end with a matching 'End If'.</source>
<target state="translated">'Блок "If" должен заканчиваться соответствующим оператором "End If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWhile">
<source>'While' must end with a matching 'End While'.</source>
<target state="translated">'Блок "While" должен заканчиваться соответствующим оператором "End While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLoop">
<source>'Do' must end with a matching 'Loop'.</source>
<target state="translated">'Блок "Do" должен заканчиваться соответствующим оператором "Loop".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNext">
<source>'For' must end with a matching 'Next'.</source>
<target state="translated">'Блок "For" должен заканчиваться соответствующим оператором "Next".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWith">
<source>'With' must end with a matching 'End With'.</source>
<target state="translated">'Блок "With" должен заканчиваться соответствующим оператором "End With".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseNoMatchingIf">
<source>'Else' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'Оператору "ElseIf" должен предшествовать соответствующий "If" или "ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndIfNoMatchingIf">
<source>'End If' must be preceded by a matching 'If'.</source>
<target state="translated">'Оператору "End If" должен предшествовать соответствующий оператор "If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSelectNoSelect">
<source>'End Select' must be preceded by a matching 'Select Case'.</source>
<target state="translated">'Оператору "End Select" должен предшествовать соответствующий оператор "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitDoNotWithinDo">
<source>'Exit Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'"Exit Do" может использоваться только в теле оператора "Do".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWhileNoWhile">
<source>'End While' must be preceded by a matching 'While'.</source>
<target state="translated">'Оператору "End While" должен предшествовать соответствующий оператор "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopNoMatchingDo">
<source>'Loop' must be preceded by a matching 'Do'.</source>
<target state="translated">'Оператору "Loop" должен предшествовать соответствующий оператор "Do".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextNoMatchingFor">
<source>'Next' must be preceded by a matching 'For'.</source>
<target state="translated">'Оператору "Next" должен предшествовать соответствующий оператор "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWithWithoutWith">
<source>'End With' must be preceded by a matching 'With'.</source>
<target state="translated">'Оператору "End With" должен предшествовать соответствующий оператор "With".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefined1">
<source>Label '{0}' is already defined in the current method.</source>
<target state="translated">Метка "{0}" уже определена в текущем методе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSelect">
<source>'Select Case' must end with a matching 'End Select'.</source>
<target state="translated">'Блок "Select Case" должен заканчиваться соответствующим оператором "End Select".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitForNotWithinFor">
<source>'Exit For' can only appear inside a 'For' statement.</source>
<target state="translated">'"Exit For" может использоваться только в теле оператора "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitWhileNotWithinWhile">
<source>'Exit While' can only appear inside a 'While' statement.</source>
<target state="translated">'"Exit While" может использоваться только в теле оператора "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyProperty1">
<source>'ReadOnly' property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Свойство "ReadOnly" "{0}" не может быть целевым объектом назначения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSelectNotWithinSelect">
<source>'Exit Select' can only appear inside a 'Select' statement.</source>
<target state="translated">'"Exit Select" может использоваться только в теле оператора "Select".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BranchOutOfFinally">
<source>Branching out of a 'Finally' is not valid.</source>
<target state="translated">Переход из блока "Finally" является недопустимым.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualNotObjectRecord1">
<source>'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'.</source>
<target state="translated">'!' требует, чтобы левый операнд имел параметр типа, класс или тип интерфейса, но этот операнд имеет тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewIndices">
<source>Number of indices is less than the number of dimensions of the indexed array.</source>
<target state="translated">Число индексов меньше числа измерений индексированного массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyIndices">
<source>Number of indices exceeds the number of dimensions of the indexed array.</source>
<target state="translated">Число индексов больше числа измерений индексированного массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EnumNotExpression1">
<source>'{0}' is an Enum type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом Enum и не может использоваться как выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeNotExpression1">
<source>'{0}' is a type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом и не может использоваться в качестве выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassNotExpression1">
<source>'{0}' is a class type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом класса и не может использоваться как выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNotExpression1">
<source>'{0}' is a structure type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом структуры и не может использоваться в качестве выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotExpression1">
<source>'{0}' is an interface type and cannot be used as an expression.</source>
<target state="translated">"{0}" является типом интерфейса и не может использоваться как выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotExpression1">
<source>'{0}' is a namespace and cannot be used as an expression.</source>
<target state="translated">"{0}" является пространством имени и не может использоваться в качестве выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNamespaceName1">
<source>'{0}' is not a valid name and cannot be used as the root namespace name.</source>
<target state="translated">"{0}" является недопустимым именем и не может использоваться как имя корневого пространства имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlPrefixNotExpression">
<source>'{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object.</source>
<target state="translated">"{0}" является префиксом XML и не может использоваться в качестве выражения. Используйте оператор GetXmlNamespace для создания объекта пространства имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleExtends">
<source>'Inherits' can appear only once within a 'Class' statement and can only specify one class.</source>
<target state="translated">'В операторе "Class" ключевое слово "Inherits" может использоваться только один раз и задавать только один класс.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropMustHaveGetSet">
<source>Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.</source>
<target state="translated">Свойство без спецификаторов "ReadOnly" или "WriteOnly" должно содержать методы "Get" и "Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasNoWrite">
<source>'WriteOnly' property must provide a 'Set'.</source>
<target state="translated">'Свойство со спецификатором WriteOnly должно иметь метод Set.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasNoGet">
<source>'ReadOnly' property must provide a 'Get'.</source>
<target state="translated">'Свойство со спецификатором "ReadOnly" должно иметь метод "Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttribute1">
<source>Attribute '{0}' is not valid: Incorrect argument value.</source>
<target state="translated">Недопустимый атрибут "{0}": Неверное значение аргумента.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LabelNotDefined1">
<source>Label '{0}' is not defined.</source>
<target state="translated">Метка "{0}" не определена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ErrorCreatingWin32ResourceFile">
<source>Error creating Win32 resources: {0}</source>
<target state="translated">Ошибка при создании ресурсов Win32: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToCreateTempFile">
<source>Cannot create temporary file: {0}</source>
<target state="translated">Не удается создать временный файл: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCall2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" из "{1}" не имеет доступный "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMember3">
<source>{0} '{1}' must implement '{2}' for interface '{3}'.</source>
<target state="translated">{0} "{1}" должна реализовать "{2}" для интерфейса "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithRef">
<source>Leading '.' or '!' can only appear inside a 'With' statement.</source>
<target state="translated">"." или "!" в начале строки может использоваться только в теле оператора With.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAccessCategoryUsed">
<source>Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.</source>
<target state="translated">Можно указать только один из модификаторов: "Public", "Private", "Protected", "Friend", "Protected Friend" или "Private Protected".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateModifierCategoryUsed">
<source>Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.</source>
<target state="translated">Можно указать только одно из значений: "NotOverridable", "MustOverride" или "Overridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateSpecifier">
<source>Specifier is duplicated.</source>
<target state="translated">Повторяющийся спецификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeConflict6">
<source>{0} '{1}' and {2} '{3}' conflict in {4} '{5}'.</source>
<target state="translated">{0} "{1}" и {2} "{3}" конфликтуют в {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeKeyword">
<source>Keyword does not name a type.</source>
<target state="translated">Ключевое слово не задает имя типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraSpecifiers">
<source>Specifiers valid only at the beginning of a declaration.</source>
<target state="translated">Спецификаторы допустимы только в начале объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedType">
<source>Type expected.</source>
<target state="translated">Требуется тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfKeyword">
<source>Keyword is not valid as an identifier.</source>
<target state="translated">Ключевое слово не может использоваться как идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEnum">
<source>'End Enum' must be preceded by a matching 'Enum'.</source>
<target state="translated">'Оператору "End Enum" должен предшествовать соответствующий оператор "Enum".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEnum">
<source>'Enum' must end with a matching 'End Enum'.</source>
<target state="translated">'Блок "Enum" должен заканчиваться соответствующим блоком "End Enum".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDeclaration">
<source>Declaration expected.</source>
<target state="translated">Ожидалось объявление.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeLast">
<source>End of parameter list expected. Cannot define parameters after a paramarray parameter.</source>
<target state="translated">Требуется завершение списка параметров. Невозможно определить параметры, расположенные после параметра ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvalidOnInheritsImplOpt">
<source>Specifiers and attributes are not valid on this statement.</source>
<target state="translated">Для этого оператора спецификаторы и атрибуты являются недопустимыми.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSpecifier">
<source>Expected one of 'Dim', 'Const', 'Public', 'Private', 'Protected', 'Friend', 'Shadows', 'ReadOnly' or 'Shared'.</source>
<target state="translated">Требуется один из этих операторов: "Dim", "Const", "Public", "Private", "Protected", "Friend", "Shadows", "ReadOnly" или "Shared".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedComma">
<source>Comma expected.</source>
<target state="translated">Требуется запятая.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAs">
<source>'As' expected.</source>
<target state="translated">'Требуется "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRparen">
<source>')' expected.</source>
<target state="translated">'Требуется ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLparen">
<source>'(' expected.</source>
<target state="translated">'Требуется "(".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNewInType">
<source>'New' is not valid in this context.</source>
<target state="translated">'В этом контексте "New" является недействительным.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExpression">
<source>Expression expected.</source>
<target state="translated">Требуется выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptional">
<source>'Optional' expected.</source>
<target state="translated">'Требуется "Optional".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifier">
<source>Identifier expected.</source>
<target state="translated">Требуется идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIntLiteral">
<source>Integer constant expected.</source>
<target state="translated">Требуется целочисленная константа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEOS">
<source>End of statement expected.</source>
<target state="translated">Требуется завершение оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedForOptionStmt">
<source>'Option' must be followed by 'Compare', 'Explicit', 'Infer', or 'Strict'.</source>
<target state="translated">'После "Option" должно следовать "Compare", "Explicit", "Infer" или "Strict".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionCompare">
<source>'Option Compare' must be followed by 'Text' or 'Binary'.</source>
<target state="translated">'За оператором "Option Compare" должны следовать "Text" или "Binary".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptionCompare">
<source>'Compare' expected.</source>
<target state="translated">'Требуется Compare.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObject">
<source>Option Strict On requires all variable declarations to have an 'As' clause.</source>
<target state="translated">При использовании параметра "Strict On" все объявления переменных должны иметь предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitProc">
<source>Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.</source>
<target state="translated">При использовании параметра "Strict On" объявления функций, свойств и операторов должны иметь предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitArgs">
<source>Option Strict On requires that all method parameters have an 'As' clause.</source>
<target state="translated">Оператор "Option Strict On" требует, чтобы все параметры метода имели предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidParameterSyntax">
<source>Comma or ')' expected.</source>
<target state="translated">Требуется запятая или ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubFunction">
<source>'Sub' or 'Function' expected.</source>
<target state="translated">'Требуется "Sub" или "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedStringLiteral">
<source>String constant expected.</source>
<target state="translated">Ожидалась строковая константа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingLibInDeclare">
<source>'Lib' expected.</source>
<target state="translated">'Требуется "Lib".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateNoInvoke1">
<source>Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call.</source>
<target state="translated">Класс делегата "{0}" не содержит метода Invoke, поэтому выражение этого типа не может быть результатом вызова метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingIsInTypeOf">
<source>'Is' expected.</source>
<target state="translated">'Требуется "Is".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateOption1">
<source>'Option {0}' statement can only appear once per file.</source>
<target state="translated">'Оператор "Option {0}" можно использовать в файле только один раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantInherit">
<source>'Inherits' not valid in Modules.</source>
<target state="translated">'Оператор "Inherits" недопустим в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantImplement">
<source>'Implements' not valid in Modules.</source>
<target state="translated">'Оператор "Implements" недопустим в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadImplementsType">
<source>Implemented type must be an interface.</source>
<target state="translated">Реализованный тип должен представлять интерфейс.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstFlags1">
<source>'{0}' is not valid on a constant declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении константы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithEventsFlags1">
<source>'{0}' is not valid on a WithEvents declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении WithEvents.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDimFlags1">
<source>'{0}' is not valid on a member variable declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении переменной-члена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParamName1">
<source>Parameter already declared with name '{0}'.</source>
<target state="translated">Параметр уже объявлен с именем "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopDoubleCondition">
<source>'Loop' cannot have a condition if matching 'Do' has one.</source>
<target state="translated">'Оператор "Loop" не может содержать условие, если соответствующий оператор "Do" содержит условие.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRelational">
<source>Relational operator expected.</source>
<target state="translated">Требуется оператор отношения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExitKind">
<source>'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'.</source>
<target state="translated">'За оператором "Exit" должно следовать слово "Sub", "Function", "Property", "Do", "For", "While", "Select" или "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgumentInAttributeList">
<source>Named argument expected.</source>
<target state="translated">Ожидается именованный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation">
<source>Named argument specifications must appear after all fixed arguments have been specified in a late bound invocation.</source>
<target state="translated">Спецификации именованных аргументов должны создаваться после всех указанных фиксированных аргументов в вызове с поздним связыванием.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgument">
<source>Named argument expected. Please use language version {0} or greater to use non-trailing named arguments.</source>
<target state="translated">Ожидается именованный аргумент. Используйте версию языка {0} или более позднюю, чтобы использовать неконечные аргументы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMethodFlags1">
<source>'{0}' is not valid on a method declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEventFlags1">
<source>'{0}' is not valid on an event declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDeclareFlags1">
<source>'{0}' is not valid on a Declare.</source>
<target state="translated">"{0}" является недопустимым для Declare.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalConstFlags1">
<source>'{0}' is not valid on a local constant declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении локальной константы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalDimFlags1">
<source>'{0}' is not valid on a local variable declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении локальной переменной.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedConditionalDirective">
<source>'If', 'ElseIf', 'Else', 'Const', 'Region', 'ExternalSource', 'ExternalChecksum', 'Enable', 'Disable', 'End' or 'R' expected.</source>
<target state="translated">'Ожидались операторы If, ElseIf, Else, Const, Region, ExternalSource, ExternalChecksum, Enable, Disable, End или R.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEQ">
<source>'=' expected.</source>
<target state="translated">'Требуется "=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorNotFound1">
<source>Type '{0}' has no constructors.</source>
<target state="translated">Тип "{0}" не имеет конструкторов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndInterface">
<source>'End Interface' must be preceded by a matching 'Interface'.</source>
<target state="translated">'Оператору "End Interface" должен предшествовать соответствующий оператор "Interface".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndInterface">
<source>'Interface' must end with a matching 'End Interface'.</source>
<target state="translated">'Блок "Interface" должен заканчиваться соответствующим оператором "End Interface".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFrom2">
<source>
'{0}' inherits from '{1}'.</source>
<target state="translated">
"{0}" наследует от "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNestedIn2">
<source>
'{0}' is nested in '{1}'.</source>
<target state="translated">
"{0}" вложено в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycle1">
<source>Class '{0}' cannot inherit from itself: {1}</source>
<target state="translated">Класс "{0}" не может наследовать от себя самого: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonClass">
<source>Classes can inherit only from other classes.</source>
<target state="translated">Классы могут наследовать только от других классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedType3">
<source>'{0}' is already declared as '{1}' in this {2}.</source>
<target state="translated">"{0}" уже объявлено как "{1}" в {2}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverrideAccess2">
<source>'{0}' cannot override '{1}' because they have different access levels.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку у них разные уровни доступа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideNotOverridable2">
<source>'{0}' cannot override '{1}' because it is declared 'NotOverridable'.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку он объявлен как "NotOverridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDef1">
<source>'{0}' has multiple definitions with identical signatures.</source>
<target state="translated">"{0}" имеет несколько определений с одинаковыми сигнатурами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDefWithDifferentTupleNames2">
<source>'{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'.</source>
<target state="translated">"{0}" имеет несколько определений с одинаковыми подписями, но разными именами элементов кортежа, в том числе "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceMethodFlags1">
<source>'{0}' is not valid on an interface method declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением метода интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound2">
<source>'{0}' is not a parameter of '{1}'.</source>
<target state="translated">"{0}" не является параметром "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfacePropertyFlags1">
<source>'{0}' is not valid on an interface property declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением свойства интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice2">
<source>Parameter '{0}' of '{1}' already has a matching argument.</source>
<target state="translated">Параметр "{0}" "{1}" уже имеет соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCantUseEventSpecifier1">
<source>'{0}' is not valid on an interface event declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением события интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNoMatch2">
<source>Type character '{0}' does not match declared data type '{1}'.</source>
<target state="translated">Тип символа "{0}" не соответствует объявленному типу данных "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubOrFunction">
<source>'Sub' or 'Function' expected after 'Delegate'.</source>
<target state="translated">'После "Delegate" требуется "Sub" или "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEmptyEnum1">
<source>Enum '{0}' must contain at least one member.</source>
<target state="translated">Перечисление "{0}" должно содержать хотя бы один член.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidConstructorCall">
<source>Constructor call is valid only as the first statement in an instance constructor.</source>
<target state="translated">Вызов конструктора допустим только как первый оператор в конструкторе экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideConstructor">
<source>'Sub New' cannot be declared 'Overrides'.</source>
<target state="translated">'"Sub New" не может объявляться как "Overrides".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorCannotBeDeclaredPartial">
<source>'Sub New' cannot be declared 'Partial'.</source>
<target state="translated">'"Sub New" нельзя объявить как "Partial".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleEmitFailure">
<source>Failed to emit module '{0}': {1}</source>
<target state="translated">Не удалось выдать модуль "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncUpdateFailedMissingAttribute">
<source>Cannot update '{0}'; attribute '{1}' is missing.</source>
<target state="translated">Невозможно обновить "{0}"; нет атрибута "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideNotNeeded3">
<source>{0} '{1}' cannot be declared 'Overrides' because it does not override a {0} in a base class.</source>
<target state="translated">{0} "{1}" не может быть объявлен как "Overrides", так как он не переопределяет {0} в базовом классе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDot">
<source>'.' expected.</source>
<target state="translated">'Требуется ".".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocals1">
<source>Local variable '{0}' is already declared in the current block.</source>
<target state="translated">Локальная переменная "{0}" уже объявлена в текущем блоке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProc">
<source>Statement cannot appear within a method body. End of method assumed.</source>
<target state="translated">Оператор не может присутствовать в теле метода. Предполагается, что метод закончен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalSameAsFunc">
<source>Local variable cannot have the same name as the function containing it.</source>
<target state="translated">Имя локальной переменной не может совпадать с именем содержащей ее функции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordEmbeds2">
<source>
'{0}' contains '{1}' (variable '{2}').</source>
<target state="translated">
"{0}" содержит "{1}" (переменная "{2}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordCycle2">
<source>Structure '{0}' cannot contain an instance of itself: {1}</source>
<target state="translated">Структура "{0}" не может содержать экземпляр самой себя: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCycle1">
<source>Interface '{0}' cannot inherit from itself: {1}</source>
<target state="translated">Интерфейс "{0}" не может наследовать от себя самого: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle2">
<source>
'{0}' calls '{1}'.</source>
<target state="translated">
"{0}" вызывает "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle1">
<source>Constructor '{0}' cannot call itself: {1}</source>
<target state="translated">Конструктор "{0}" не может вызывать сам себя: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromCantInherit3">
<source>'{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'.</source>
<target state="translated">"{0}" не может наследовать от {2} "{1}", поскольку "{1}" объявлен как "NotInheritable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithOptional2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by optional parameters.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по необязательным параметрам.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithReturnType2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by return types.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по возвращаемым типам.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharWithType1">
<source>Type character '{0}' cannot be used in a declaration with an explicit type.</source>
<target state="translated">Тип символа "{0}" не может быть использован в объявлении с явным типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnSub">
<source>Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.</source>
<target state="translated">Символ типа не может использоваться в объявлении "Sub", так как "Sub" не возвращает значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithDefault2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по значениям по умолчанию необязательных параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingSubscript">
<source>Array subscript expression missing.</source>
<target state="translated">Отсутствует выражение для индексов массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithDefault2">
<source>'{0}' cannot override '{1}' because they differ by the default values of optional parameters.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по значениям по умолчанию необязательных параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptional2">
<source>'{0}' cannot override '{1}' because they differ by optional parameters.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по необязательным параметрам.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldOfValueFieldOfMarshalByRef3">
<source>Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class.</source>
<target state="translated">Невозможно обратиться к "{0}", так как он является членом поля типа значения "{1}" класса "{2}", базовым классом которого является "System.MarshalByRefObject".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}'.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseAfterCaseElse">
<source>'Case' cannot follow a 'Case Else' in the same 'Select' statement.</source>
<target state="translated">'В операторе "Select" блок "Case" не может задаваться после "Case Else".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayMismatch4">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}", поскольку "{2}" не является производным от "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertObjectArrayMismatch3">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}", поскольку "{2}" не является ссылочным типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopType1">
<source>'For' loop control variable cannot be of type '{0}' because the type does not support the required operators.</source>
<target state="translated">'Управляющая переменная цикла "For" не может быть типа "{0}", так как этот тип не поддерживают требуемые операторы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithByref2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ByRef" или "ByVal".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonInterface">
<source>Interface can inherit only from another interface.</source>
<target state="translated">Интерфейс может наследовать только от другого интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceOrderOnInherits">
<source>'Inherits' statements must precede all declarations in an interface.</source>
<target state="translated">'Операторы "Inherits" должны предшествовать всем объявлениям в интерфейсе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateDefaultProps1">
<source>'Default' can be applied to only one property name in a {0}.</source>
<target state="translated">'"Default" может указываться только для одного имени свойства в {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMissingFromProperty2">
<source>'{0}' and '{1}' cannot overload each other because only one is declared 'Default'.</source>
<target state="translated">"{0}" и "{1}" не могут перегружать друг друга, т. к. только один из них объявлен как "Default".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingPropertyKind2">
<source>'{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по типу "ReadOnly" или "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInInterface">
<source>'Sub New' cannot be declared in an interface.</source>
<target state="translated">'"Sub New" нельзя объявлять в интерфейсе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNew1">
<source>'Sub New' cannot be declared '{0}'.</source>
<target state="translated">'"Sub New" нельзя объявить как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadingPropertyKind2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по "ReadOnly" или "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDefaultNotExtend1">
<source>Class '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">Класс "{0}" не может быть индексирован, так как не имеет свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithArrayVsParamArray2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'.</source>
<target state="translated">"{0}" и "{1}" не могут переопределить друг друга, так как они отличаются только по параметрам, объявленным "ParamArray".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInstanceMemberAccess">
<source>Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.</source>
<target state="translated">Невозможно обратиться к члену экземпляра класса из общего метода или общего инициализатора члена без явного указания экземпляра этого класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRbrace">
<source>'}' expected.</source>
<target state="translated">'Требуется "}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleAsType1">
<source>Module '{0}' cannot be used as a type.</source>
<target state="translated">Модуль "{0}" не может использоваться как тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnNonClass">
<source>'New' cannot be used on an interface.</source>
<target state="translated">'"New" не может использоваться для интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchAfterFinally">
<source>'Catch' cannot appear after 'Finally' within a 'Try' statement.</source>
<target state="translated">'В операторе "Try" ключевое слово "Catch" не может указываться после "Finally".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNoMatchingTry">
<source>'Catch' cannot appear outside a 'Try' statement.</source>
<target state="translated">'"Catch" не может использоваться вне оператора "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyAfterFinally">
<source>'Finally' can only appear once in a 'Try' statement.</source>
<target state="translated">'"Finally" в операторе "Try" может использоваться только один раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyNoMatchingTry">
<source>'Finally' cannot appear outside a 'Try' statement.</source>
<target state="translated">'"Finally" не может находиться за пределами оператора "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndTryNoTry">
<source>'End Try' must be preceded by a matching 'Try'.</source>
<target state="translated">'Оператору "End Try" должен предшествовать соответствующий оператор "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndTry">
<source>'Try' must end with a matching 'End Try'.</source>
<target state="translated">'Блок "Try" должен заканчиваться соответствующим "End Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDelegateFlags1">
<source>'{0}' is not valid on a Delegate declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как его базовый класс "{1}" не имеет доступного "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleSymbol2">
<source>'{0}' is not accessible in this context because it is '{1}'.</source>
<target state="translated">"{0}" в этом контексте недоступен, так как он является "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleMember3">
<source>'{0}.{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">"{0}.{1}" в этом контексте недоступен, так как он является "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNotException1">
<source>'Catch' cannot catch type '{0}' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.</source>
<target state="translated">'"Catch" не может перехватить тип "{0}", так как не является "System.Exception" или классом, наследующим от "System.Exception".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitTryNotWithinTry">
<source>'Exit Try' can only appear inside a 'Try' statement.</source>
<target state="translated">'"Exit Try" может использоваться только в теле оператора "Try".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRecordFlags1">
<source>'{0}' is not valid on a Structure declaration.</source>
<target state="translated">"{0}" недопустимо использовать в объявлении Structure.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEnumFlags1">
<source>'{0}' is not valid on an Enum declaration.</source>
<target state="translated">"{0}" недопустимо использовать при объявлении перечисления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceFlags1">
<source>'{0}' is not valid on an Interface declaration.</source>
<target state="translated">"{0}" является недопустимым объявлением интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithByref2">
<source>'{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по параметру, который помечен как ByRef" относительно "ByVal".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyBaseAbstractCall1">
<source>'MyBase' cannot be used with method '{0}' because it is declared 'MustOverride'.</source>
<target state="translated">'"MyBase" не может использоваться с методом "{0}", объявленным как "MustOverride".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentNotMemberOfInterface4">
<source>'{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'.</source>
<target state="translated">"{0}" не может реализовать "{1}", поскольку нет соответствующего {2} в интерфейсе "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementingInterfaceWithDifferentTupleNames5">
<source>'{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'.</source>
<target state="translated">"{0}" не может реализовать {1} "{2}" в интерфейсе "{3}", так как имена элементов кортежа в "{4}" не соответствуют именам в "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsRequiresClass">
<source>'WithEvents' variables must have an 'As' clause.</source>
<target state="translated">'Объявления переменных с модификатором "WithEvents" должны иметь предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsAsStruct">
<source>'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.</source>
<target state="translated">'Типы переменных с модификатором "WithEvents" могут быть только классами, интерфейсами или параметрами типов с ограничениями классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayRankMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}' because the array types have different numbers of dimensions.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}", так как в типах массивов указано различное количество измерений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimRankMismatch">
<source>'ReDim' cannot change the number of dimensions of an array.</source>
<target state="translated">'"ReDim" не может изменять число измерений массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartupCodeNotFound1">
<source>'Sub Main' was not found in '{0}'.</source>
<target state="translated">'Не удалось найти "Sub Main" в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstAsNonConstant">
<source>Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.</source>
<target state="translated">Константы должны быть значениями встроенного типа или типа перечисления, а не классом, структурой, параметром-типом или массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSub">
<source>'End Sub' must be preceded by a matching 'Sub'.</source>
<target state="translated">'Оператору "End Sub" должен предшествовать соответствующий оператор "Sub".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndFunction">
<source>'End Function' must be preceded by a matching 'Function'.</source>
<target state="translated">'Оператору "End Function" должен предшествовать соответствующий оператор "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndProperty">
<source>'End Property' must be preceded by a matching 'Property'.</source>
<target state="translated">'Оператору "End Property" должен предшествовать соответствующий оператор "Property".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseMethodSpecifier1">
<source>Methods in a Module cannot be declared '{0}'.</source>
<target state="translated">Методы в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseEventSpecifier1">
<source>Events in a Module cannot be declared '{0}'.</source>
<target state="translated">События в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseVarSpecifier1">
<source>Members in a Structure cannot be declared '{0}'.</source>
<target state="translated">Члены в структуре не могут быть объявлены как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOverrideDueToReturn2">
<source>'{0}' cannot override '{1}' because they differ by their return types.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как их возвращаемые типы различны.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2">
<source>'{0}' cannot override '{1}' because they differ by their tuple element names.</source>
<target state="translated">"{0}" не может переопределять "{1}", так как они отличаются именами элементов кортежа.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2_Title">
<source>Member cannot override because it differs by its tuple element names.</source>
<target state="translated">Переопределение с помощью члена невозможно, так как его имена элементов кортежа отличаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantWithNoValue">
<source>Constants must have a value.</source>
<target state="translated">Константы должны иметь значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionOverflow1">
<source>Constant expression not representable in type '{0}'.</source>
<target state="translated">Константное выражение не может быть представлено как имеющее тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertyGet">
<source>'Get' is already declared.</source>
<target state="translated">'Процедура "Get" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertySet">
<source>'Set' is already declared.</source>
<target state="translated">'Процедура "Set" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotDeclared1">
<source>'{0}' is not declared. It may be inaccessible due to its protection level.</source>
<target state="translated">"{0}" не объявлена. Возможно, она недоступна из-за своего уровня защиты.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperands3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'.</source>
<target state="translated">Оператор "{0}" не определен для типов "{1}" и "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedProcedure">
<source>Expression is not a method.</source>
<target state="translated">Выражение не является методом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument2">
<source>Argument not specified for parameter '{0}' of '{1}'.</source>
<target state="translated">Аргумент, не указанный для параметра "{0}" метода "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMember2">
<source>'{0}' is not a member of '{1}'.</source>
<target state="translated">"{0}" не является членом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndClassNoClass">
<source>'End Class' must be preceded by a matching 'Class'.</source>
<target state="translated">'Оператору "End Class" должен предшествовать соответствующий оператор "Class".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadClassFlags1">
<source>Classes cannot be declared '{0}'.</source>
<target state="translated">Классы не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportsMustBeFirst">
<source>'Imports' statements must precede any declarations.</source>
<target state="translated">'Операторы "Imports" должны указываться до любых объявлений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonNamespaceOrClassOnImport2">
<source>'{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module.</source>
<target state="translated">"{1}" для Imports "{0}" не ссылается на Namespace, Class, Structure, Enum или Module.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNotallowed">
<source>Type declaration characters are not valid in this context.</source>
<target state="translated">Символы объявления типа недопустимы в этом контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectReferenceNotSupplied">
<source>Reference to a non-shared member requires an object reference.</source>
<target state="translated">Для ссылки на член, не используемый совместно, требуется ссылка на объект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassNotInClass">
<source>'MyClass' cannot be used outside of a class.</source>
<target state="translated">'"MyClass" не может использоваться вне класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndexedNotArrayOrProc">
<source>Expression is not an array or a method, and cannot have an argument list.</source>
<target state="translated">Выражение не является массивом или методом и не может иметь список аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventSourceIsArray">
<source>'WithEvents' variables cannot be typed as arrays.</source>
<target state="translated">'Переменные с модификатором "WithEvents" не могут являться массивами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorWithParams">
<source>Shared 'Sub New' cannot have any parameters.</source>
<target state="translated">Общий конструктор "Sub New" не может иметь параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorIllegalSpec1">
<source>Shared 'Sub New' cannot be declared '{0}'.</source>
<target state="translated">Невозможно объявить общий "Sub New" как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndClass">
<source>'Class' statement must end with a matching 'End Class'.</source>
<target state="translated">'Блок Class должен заканчиваться соответствующим оператором End Class.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryOperand2">
<source>Operator '{0}' is not defined for type '{1}'.</source>
<target state="translated">Оператор "{0}" не определен для типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsWithDefault1">
<source>'Default' cannot be combined with '{0}'.</source>
<target state="translated">'"Default" не может использоваться вместе с "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidValue">
<source>Expression does not produce a value.</source>
<target state="translated">Выражение не порождает значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorFunction">
<source>Constructor must be declared as a Sub, not as a Function.</source>
<target state="translated">Конструктор должен объявляться как подпрограмма (Sub), а не как функция (Function).</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLiteralExponent">
<source>Exponent is not valid.</source>
<target state="translated">Показатель степени является недопустимым.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewCannotHandleEvents">
<source>'Sub New' cannot handle events.</source>
<target state="translated">'Конструктор "Sub New" не может обрабатывать события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularEvaluation1">
<source>Constant '{0}' cannot depend on its own value.</source>
<target state="translated">Константа "{0}" не может зависеть от своего собственного значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedMeth1">
<source>'Shared' cannot be combined with '{0}' on a method declaration.</source>
<target state="translated">'"Shared" не может использоваться вместе с "{0}" в объявлении метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedProperty1">
<source>'Shared' cannot be combined with '{0}' on a property declaration.</source>
<target state="translated">'"Shared" не может использоваться вместе с "{0}" в объявлении свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnStdModuleProperty1">
<source>Properties in a Module cannot be declared '{0}'.</source>
<target state="translated">Свойства в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedOnProcThatImpl">
<source>Methods or events that implement interface members cannot be declared 'Shared'.</source>
<target state="translated">Методы или события, которые реализуют члены интерфейса, не могут объявляться как "Shared".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoWithEventsVarOnHandlesList">
<source>Handles clause requires a WithEvents variable defined in the containing type or one of its base types.</source>
<target state="translated">Для предложения Handles требуется переменная с модификатором WithEvents, определенная во вмещающем типе или в одном из его базовых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatch5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} до {3} "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionDisallowed2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'.</source>
<target state="translated">Option Strict On не разрешает неявные преобразования "{0}" к "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoArgumentCountOverloadCandidates1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of arguments.</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступного "{0}", который принимает такое число аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoViableOverloadCandidates1">
<source>Overload resolution failed because no '{0}' is accessible.</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступа к "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoCallableOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called with these arguments:{1}</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как отсутствует доступный "{0}", который можно вызвать с этими аргументами: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called:{1}</source>
<target state="translated">Сбой при разрешении перегрузки, поскольку ни один из доступных "{0}" не может быть вызван:{1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonNarrowingOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called without a narrowing conversion:{1}</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступных "{0}", которые можно вызвать без сужающего преобразования:{1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing3">
<source>Argument matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">Аргумент, соответствующий параметру "{0}", сужен с "{1}" до "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoMostSpecificOverload2">
<source>Overload resolution failed because no accessible '{0}' is most specific for these arguments:{1}</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как нет доступного "{0}", который бы являлся наиболее конкретным для этих аргументов: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotMostSpecificOverload">
<source>Not most specific.</source>
<target state="translated">Не является наиболее подходящим.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate2">
<source>
'{0}': {1}</source>
<target state="translated">
"{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGetProperty1">
<source>Property '{0}' is 'WriteOnly'.</source>
<target state="translated">Свойство "{0}" помечено как "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSetProperty1">
<source>Property '{0}' is 'ReadOnly'.</source>
<target state="translated">Свойство "{0}" помечено как "ReadOnly".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamTypingInconsistency">
<source>All parameters must be explicitly typed if any of them are explicitly typed.</source>
<target state="translated">Типы всех параметров должны быть указаны явно, если хотя бы один тип указан явно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamNameFunctionNameCollision">
<source>Parameter cannot have the same name as its defining function.</source>
<target state="translated">Параметр не может иметь имя, совпадающее с именем определяющей его функции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DateToDoubleConversion">
<source>Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method.</source>
<target state="translated">Для преобразования из типа Date в Double требуется вызов метода Date.ToOADate.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoubleToDateConversion">
<source>Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method.</source>
<target state="translated">Для преобразования из типа Date в Double требуется вызов метода Date.FromOADate.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ZeroDivide">
<source>Division by zero occurred while evaluating this expression.</source>
<target state="translated">При вычислении этого выражения произошло деление на нуль.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryAndOnErrorDoNotMix">
<source>Method cannot contain both a 'Try' statement and an 'On Error' or 'Resume' statement.</source>
<target state="translated">Метод не может одновременно содержать оператор "Try" и оператор "On Error" или "Resume".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyAccessIgnored">
<source>Property access must assign to the property or use its value.</source>
<target state="translated">Доступ к свойству должен выполняться для присваивания или считывания его значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNoDefault1">
<source>'{0}' cannot be indexed because it has no default property.</source>
<target state="translated">"{0}" невозможно индексировать, поскольку он не содержит свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyAttribute1">
<source>Attribute '{0}' cannot be applied to an assembly.</source>
<target state="translated">Атрибут "{0}" невозможно применить к сборке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidModuleAttribute1">
<source>Attribute '{0}' cannot be applied to a module.</source>
<target state="translated">Атрибут "{0}" невозможно применить к модулю.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInUnnamedNamespace1">
<source>'{0}' is ambiguous.</source>
<target state="translated">"{0}" неоднозначен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMemberNotProperty1">
<source>Default member of '{0}' is not a property.</source>
<target state="translated">Член по умолчанию "{0}" не является свойством.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespace2">
<source>'{0}' is ambiguous in the namespace '{1}'.</source>
<target state="translated">"{0}" неоднозначен в пространстве имен "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInImports2">
<source>'{0}' is ambiguous, imported from the namespaces or types '{1}'.</source>
<target state="translated">"{0}", импортированный из пространств имен или типов "{1}", является неоднозначным.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInModules2">
<source>'{0}' is ambiguous between declarations in Modules '{1}'.</source>
<target state="translated">"{0}" неоднозначен для объявлений в модулях "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespaces2">
<source>'{0}' is ambiguous between declarations in namespaces '{1}'.</source>
<target state="translated">"{0}" неоднозначен для объявлений в пространствах имен "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooFewDimensions">
<source>Array initializer has too few dimensions.</source>
<target state="translated">Недостаточное число измерений инициализатора массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooManyDimensions">
<source>Array initializer has too many dimensions.</source>
<target state="translated">Чрезмерное число измерений инициализатора массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooFewElements1">
<source>Array initializer is missing {0} elements.</source>
<target state="translated">Количество отсутствующих элементов в инициализаторе массива: {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooManyElements1">
<source>Array initializer has {0} too many elements.</source>
<target state="translated">В инициализаторе массива слишком много элементов {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewOnAbstractClass">
<source>'New' cannot be used on a class that is declared 'MustInherit'.</source>
<target state="translated">'"New" не может использоваться для класса, объявленного как "MustInherit".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateNamedImportAlias1">
<source>Alias '{0}' is already declared.</source>
<target state="translated">Псевдоним "{0}" уже объявлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePrefix">
<source>XML namespace prefix '{0}' is already declared.</source>
<target state="translated">Префикс пространства имен XML "{0}" уже объявлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsLateBinding">
<source>Option Strict On disallows late binding.</source>
<target state="translated">Оператор "Option Strict On" не разрешает позднее связывание.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfOperandNotMethod">
<source>'AddressOf' operand must be the name of a method (without parentheses).</source>
<target state="translated">'Операндом "AddressOf" должно быть имя метода; круглые скобки не требуются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndExternalSource">
<source>'#End ExternalSource' must be preceded by a matching '#ExternalSource'.</source>
<target state="translated">'Оператору "#End ExternalSource" должен предшествовать соответствующий оператор "#ExternalSource".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndExternalSource">
<source>'#ExternalSource' statement must end with a matching '#End ExternalSource'.</source>
<target state="translated">'Оператор "#ExternalSource" должен заканчиваться соответствующим оператором "#End ExternalSource".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedExternalSource">
<source>'#ExternalSource' directives cannot be nested.</source>
<target state="translated">'Директивы "#ExternalSource" не могут быть вложенными.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">'Выражение "AddressOf" нельзя преобразовать в "{0}", поскольку "{0}" не является типом делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyncLockRequiresReferenceType1">
<source>'SyncLock' operand cannot be of type '{0}' because '{0}' is not a reference type.</source>
<target state="translated">'Операнд "SyncLock" не может быть типа "{0}", так как "{0}" не является ссылочным типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodAlreadyImplemented2">
<source>'{0}.{1}' cannot be implemented more than once.</source>
<target state="translated">"{0}.{1}" невозможно реализовать более одного раза.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateInInherits1">
<source>'{0}' cannot be inherited more than once.</source>
<target state="translated">"{0}" не может наследоваться несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamArrayArgument">
<source>Named argument cannot match a ParamArray parameter.</source>
<target state="translated">Именованный аргумент не должен соответствовать параметру ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedParamArrayArgument">
<source>Omitted argument cannot match a ParamArray parameter.</source>
<target state="translated">Пропущенный аргумент не может соответствовать параметру ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayArgumentMismatch">
<source>Argument cannot match a ParamArray parameter.</source>
<target state="translated">Аргумент не может соответствовать параметру ParamArray.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNotFound1">
<source>Event '{0}' cannot be found.</source>
<target state="translated">Не удается найти событие "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseVariableSpecifier1">
<source>Variables in Modules cannot be declared '{0}'.</source>
<target state="translated">Переменные в модулях не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsSharedHandler">
<source>Events of shared WithEvents variables cannot be handled by non-shared methods.</source>
<target state="translated">События из общих переменных "WithEvents" не могут обрабатываться методами, не являющимися общими.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedMinus">
<source>'-' expected.</source>
<target state="translated">'Требуется "-".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceMemberSyntax">
<source>Interface members must be methods, properties, events, or type definitions.</source>
<target state="translated">Членами интерфейса могут быть только методы, свойства, события и определения типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideInterface">
<source>Statement cannot appear within an interface body.</source>
<target state="translated">Оператор не может присутствовать в теле интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsInterface">
<source>Statement cannot appear within an interface body. End of interface assumed.</source>
<target state="translated">Оператор не может присутствовать в теле интерфейса. Предполагается конец интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsInNotInheritableClass1">
<source>'NotInheritable' classes cannot have members declared '{0}'.</source>
<target state="translated">'Классы "NotInheritable" не могут содержать членов, объявленных как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseOnlyClassesMustBeExplicit2">
<source>Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}.</source>
<target state="translated">Класс "{0}" должен либо быть объявлен как "MustInherit", либо переопределять следующие члены, помеченные как "MustOverride": {1}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritEventNotOverridden">
<source>'{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit.</source>
<target state="translated">"{0}" является событием MustOverride в базовом классе "{1}". Visual Basic не поддерживает переопределение событий. Необходимо предоставить реализацию события в базовом классе или задать для класса "{2}" значение MustInherit.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NegativeArraySize">
<source>Array dimensions cannot have a negative size.</source>
<target state="translated">Размерности массива не могут иметь отрицательные значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassAbstractCall1">
<source>'MustOverride' method '{0}' cannot be called with 'MyClass'.</source>
<target state="translated">'Метод "{0}", помеченный как "MustOverride", не может вызываться с помощью "MyClass".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndDisallowedInDllProjects">
<source>'End' statement cannot be used in class library projects.</source>
<target state="translated">'Оператор "End" не может использоваться в проектах библиотек классов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BlockLocalShadowing1">
<source>Variable '{0}' hides a variable in an enclosing block.</source>
<target state="translated">Переменная "{0}" скрывает переменную во внешнем блоке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleNotAtNamespace">
<source>'Module' statements can occur only at file or namespace level.</source>
<target state="translated">'Операторы "Module" могут использоваться только на уровне файлов и пространств имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAtNamespace">
<source>'Namespace' statements can occur only at file or namespace level.</source>
<target state="translated">'Операторы "Namespace" могут использоваться только на уровне файлов и пространств имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEnum">
<source>Statement cannot appear within an Enum body.</source>
<target state="translated">Оператор не может присутствовать в теле перечисления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEnum">
<source>Statement cannot appear within an Enum body. End of Enum assumed.</source>
<target state="translated">Оператор не может присутствовать в теле перечисления. Предполагается, что перечисление завершено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrict">
<source>'Option Strict' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'За "Option Strict" может следовать только "On" или "Off".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndStructureNoStructure">
<source>'End Structure' must be preceded by a matching 'Structure'.</source>
<target state="translated">'Оператору "End Structure" должен предшествовать соответствующий оператор "Structure".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndModuleNoModule">
<source>'End Module' must be preceded by a matching 'Module'.</source>
<target state="translated">'Оператору "End Module" должен предшествовать соответствующий оператор "Module".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndNamespaceNoNamespace">
<source>'End Namespace' must be preceded by a matching 'Namespace'.</source>
<target state="translated">'Оператору "End Namespace" должен предшествовать соответствующий оператор "Namespace".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndStructure">
<source>'Structure' statement must end with a matching 'End Structure'.</source>
<target state="translated">'Оператор "Structure" должен заканчиваться соответствующим оператором "End Structure".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndModule">
<source>'Module' statement must end with a matching 'End Module'.</source>
<target state="translated">'Оператор "Module" должен заканчиваться соответствующим оператором "End Module".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndNamespace">
<source>'Namespace' statement must end with a matching 'End Namespace'.</source>
<target state="translated">'Оператор "Namespace" должен заканчиваться соответствующим оператором "End Namespace".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionStmtWrongOrder">
<source>'Option' statements must precede any declarations or 'Imports' statements.</source>
<target state="translated">'Оператор "Option" должен находиться перед любыми объявлениями или операторами "Imports".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantInherit">
<source>Structures cannot have 'Inherits' statements.</source>
<target state="translated">Структуры не могут содержать операторов "Inherits".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInStruct">
<source>Structures cannot declare a non-shared 'Sub New' with no parameters.</source>
<target state="translated">Структуры не могут объявлять неразделяемый конструктор "Sub New" при отсутствии параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndGet">
<source>'End Get' must be preceded by a matching 'Get'.</source>
<target state="translated">'Оператору "End Get" должен предшествовать соответствующий оператор "Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndGet">
<source>'Get' statement must end with a matching 'End Get'.</source>
<target state="translated">'Оператор "Get" должен заканчиваться соответствующим оператором "End Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSet">
<source>'End Set' must be preceded by a matching 'Set'.</source>
<target state="translated">'Оператору "End Set" должен предшествовать соответствующий оператор "Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndSet">
<source>'Set' statement must end with a matching 'End Set'.</source>
<target state="translated">'Оператор "Set" должен заканчиваться соответствующим оператором "End Set".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProperty">
<source>Statement cannot appear within a property body. End of property assumed.</source>
<target state="translated">Оператор не может присутствовать в теле свойства. Предполагается, что свойство завершено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateWriteabilityCategoryUsed">
<source>'ReadOnly' and 'WriteOnly' cannot be combined.</source>
<target state="translated">'"ReadOnly" и "WriteOnly" не могут использоваться вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedGreater">
<source>'>' expected.</source>
<target state="translated">'Требуется ">".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeStmtWrongOrder">
<source>Assembly or Module attribute statements must precede any declarations in a file.</source>
<target state="translated">Операторы атрибута сборки или модуля в файле должны указываться до объявлений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoExplicitArraySizes">
<source>Array bounds cannot appear in type specifiers.</source>
<target state="translated">Границы массивов не могут присутствовать в спецификаторах типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyFlags1">
<source>Properties cannot be declared '{0}'.</source>
<target state="translated">Свойства не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionExplicit">
<source>'Option Explicit' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'За "Option Explicit" может следовать только "On" или "Off".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleParameterSpecifiers">
<source>'ByVal' and 'ByRef' cannot be combined.</source>
<target state="translated">'"ByVal" и "ByRef" не могут использоваться вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleOptionalParameterSpecifiers">
<source>'Optional' and 'ParamArray' cannot be combined.</source>
<target state="translated">'"Optional" и "ParamArray" не могут использоваться вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedProperty1">
<source>Property '{0}' is of an unsupported type.</source>
<target state="translated">Свойство "{0}" относится к неподдерживаемому типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionalParameterUsage1">
<source>Attribute '{0}' cannot be applied to a method with optional parameters.</source>
<target state="translated">Атрибут "{0}" не может использоваться для метода с необязательными параметрами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonFunction">
<source>'Return' statement in a Sub or a Set cannot return a value.</source>
<target state="translated">'Оператор "Return" в "Sub" или "Set" не может возвращать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnterminatedStringLiteral">
<source>String constants must end with a double quote.</source>
<target state="translated">Строковые константы должны завершаться двойной кавычкой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedType1">
<source>'{0}' is an unsupported type.</source>
<target state="translated">"{0}" является неподдерживаемым типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEnumBase">
<source>Enums must be declared as an integral type.</source>
<target state="translated">Перечисления должны объявляться как целочисленный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefIllegal1">
<source>{0} parameters cannot be declared 'ByRef'.</source>
<target state="translated">параметры {0} не могут быть объявлены как "ByRef".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssembly3">
<source>Reference required to assembly '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется сборка, содержащая тип "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModule3">
<source>Reference required to module '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">Для модуля "{0}" требуется ссылка, содержащая тип "{1}". Добавьте одну из них в проект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnWithoutValue">
<source>'Return' statement in a Function, Get, or Operator must return a value.</source>
<target state="translated">'Оператор "Return" в Function, Get или Operator должен возвращать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedField1">
<source>Field '{0}' is of an unsupported type.</source>
<target state="translated">Поле "{0}" относится к неподдерживаемому типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedMethod1">
<source>'{0}' has a return type that is not supported or parameter types that are not supported.</source>
<target state="translated">"{0}" имеет возвращаемый тип или типы параметров, которые не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonIndexProperty1">
<source>Property '{0}' with no parameters cannot be found.</source>
<target state="translated">Не удается найти свойство "{0}" без параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributePropertyType1">
<source>Property or field '{0}' does not have a valid attribute type.</source>
<target state="translated">Свойство или поле "{0}" не имеет атрибута допустимого типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalsCannotHaveAttributes">
<source>Attributes cannot be applied to local variables.</source>
<target state="translated">Атрибуты не могут использоваться для локальных переменных.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyOrFieldNotDefined1">
<source>Field or property '{0}' is not found.</source>
<target state="translated">Не найдено поле или свойство "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsage2">
<source>Attribute '{0}' cannot be applied to '{1}' because the attribute is not valid on this declaration type.</source>
<target state="translated">Атрибут "{0}" не может использоваться для "{1}", поскольку данный атрибут не допускается для этого типа объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsageOnAccessor">
<source>Attribute '{0}' cannot be applied to '{1}' of '{2}' because the attribute is not valid on this declaration type.</source>
<target state="translated">Атрибут "{0}" не может использоваться для "{1}" из "{2}", поскольку данный атрибут не допускается для этого типа объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedTypeInInheritsClause2">
<source>Class '{0}' cannot reference its nested type '{1}' in Inherits clause.</source>
<target state="translated">Класс "{0}" не может ссылаться на вложенный тип "{1}" в предложении Inherits.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInItsInheritsClause1">
<source>Class '{0}' cannot reference itself in Inherits clause.</source>
<target state="translated">Класс "{0}" не может ссылаться на себя в предложении Inherits.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseTypeReferences2">
<source>
Base type of '{0}' needs '{1}' to be resolved.</source>
<target state="translated">
Базовому типу "{0}" требуется, чтобы "{1}" был разрешен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalBaseTypeReferences3">
<source>Inherits clause of {0} '{1}' causes cyclic dependency: {2}</source>
<target state="translated">Наследует предложение {0} "{1}", вызывающее циклическую зависимость: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsage1">
<source>Attribute '{0}' cannot be applied multiple times.</source>
<target state="translated">Атрибут "{0}" не может использоваться несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsageInNetModule2">
<source>Attribute '{0}' in '{1}' cannot be applied multiple times.</source>
<target state="translated">Атрибут "{0}" в "{1}" не может использоваться несколько раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantThrowNonException">
<source>'Throw' operand must derive from 'System.Exception'.</source>
<target state="translated">'Операнд оператора "Throw" должен быть производным от "System.Exception".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeInCatchToRethrow">
<source>'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.</source>
<target state="translated">'В операторе "Throw" запрещается пропускать операнд вне оператора "Catch" или в теле оператора "Finally".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeByVal">
<source>ParamArray parameters must be declared 'ByVal'.</source>
<target state="translated">Параметры типа ParamArray должны объявляться как "ByVal".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">"{0}" является устаревшим: "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimNoSizes">
<source>'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.</source>
<target state="translated">В операторе "ReDim" требуется задать в круглых скобках список новых границ для каждого измерения массива.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithMultipleDeclarators">
<source>Explicit initialization is not permitted with multiple variables declared with a single type specifier.</source>
<target state="translated">Для нескольких переменных, объявленных с одним спецификатором типа, явная инициализация не разрешена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithExplicitArraySizes">
<source>Explicit initialization is not permitted for arrays declared with explicit bounds.</source>
<target state="translated">Явная инициализация массивов, объявленных с границами явно, запрещена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSyncLockNoSyncLock">
<source>'End SyncLock' must be preceded by a matching 'SyncLock'.</source>
<target state="translated">'Оператору "End SyncLock" должен предшествовать соответствующий оператор "SyncLock".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSyncLock">
<source>'SyncLock' statement must end with a matching 'End SyncLock'.</source>
<target state="translated">'Оператор "SyncLock" должен заканчиваться соответствующим оператором "End SyncLock".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotEvent2">
<source>'{0}' is not an event of '{1}'.</source>
<target state="translated">"{0}" не является событием "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddOrRemoveHandlerEvent">
<source>'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.</source>
<target state="translated">'Операндом события оператора "AddHandler" или "RemoveHandler" должно быть выражение с точкой или простое имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedEnd">
<source>'End' statement not valid.</source>
<target state="translated">'Недопустимый оператор "End".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitForNonArray2">
<source>Array initializers are valid only for arrays, but the type of '{0}' is '{1}'.</source>
<target state="translated">Инициализаторы массивов допустимы только для массивов, а "{0}" имеет тип "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndRegionNoRegion">
<source>'#End Region' must be preceded by a matching '#Region'.</source>
<target state="translated">'Оператору "#End Region" должен предшествовать соответствующий оператор "#Region".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndRegion">
<source>'#Region' statement must end with a matching '#End Region'.</source>
<target state="translated">'Оператор "#Region" должен заканчиваться соответствующим оператором "#End Region".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsStmtWrongOrder">
<source>'Inherits' statement must precede all declarations in a class.</source>
<target state="translated">'Оператор "Inherits" должен предшествовать всем объявлениям в классе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousAcrossInterfaces3">
<source>'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'.</source>
<target state="translated">'"Неоднозначность: "{0}" относится к наследуемым интерфейсам "{1}" и "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyAmbiguousAcrossInterfaces4">
<source>Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'.</source>
<target state="translated">Неоднозначность при доступе к свойству по умолчанию между членами "{0}" наследуемого интерфейса "{1}" и "{2}" интерфейса "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceEventCantUse1">
<source>Events in interfaces cannot be declared '{0}'.</source>
<target state="translated">События в интерфейсах не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExecutableAsDeclaration">
<source>Statement cannot appear outside of a method body.</source>
<target state="translated">Оператор не может находиться вне тела метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNoDefault1">
<source>Structure '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">Структуру "{0}" нельзя проиндексировать, так как не имеет свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustShadow2">
<source>{0} '{1}' must be declared 'Shadows' because another member with this name is declared 'Shadows'.</source>
<target state="translated">{0} "{1}" должна быть объявлена как "Shadows", потому что другой член с таким именем объявлен как "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptionalTypes2">
<source>'{0}' cannot override '{1}' because they differ by the types of optional parameters.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по типам необязательных параметров.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndOfExpression">
<source>End of expression expected.</source>
<target state="translated">Ожидался конец выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructsCannotHandleEvents">
<source>Methods declared in structures cannot have 'Handles' clauses.</source>
<target state="translated">Методы, объявляемые в структурах, не могут содержать предложения "Handles".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridesImpliesOverridable">
<source>Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.</source>
<target state="translated">Методы, объявленные оператором "Overrides", не могут объявляться как "Overridable", поскольку возможность их переопределения подразумевается неявно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParam1">
<source>'{0}' is already declared as a parameter of this method.</source>
<target state="translated">"{0}" уже объявлена как параметр этого метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParamInLambda1">
<source>Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression.</source>
<target state="translated">Переменная "{0}" уже объявлена как параметр этого или внешнего лямбда-выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseTypeSpecifier1">
<source>Type in a Module cannot be declared '{0}'.</source>
<target state="translated">Тип в модуле не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InValidSubMainsFound1">
<source>No accessible 'Main' method with an appropriate signature was found in '{0}'.</source>
<target state="translated">В "{0}" не найдено доступного метода "Main" с подходящей сигнатурой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MoreThanOneValidMainWasFound2">
<source>'Sub Main' is declared more than once in '{0}': {1}</source>
<target state="translated">'"Sub Main" объявлен в "{0}" более одного раза: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotConvertValue2">
<source>Value '{0}' cannot be converted to '{1}'.</source>
<target state="translated">Значение "{0}" нельзя преобразовать в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInSyncLock">
<source>'On Error' statements are not valid within 'SyncLock' statements.</source>
<target state="translated">'Операторы "On Error" в теле оператора "SyncLock" недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionCollection2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type.</source>
<target state="translated">Option Strict On не разрешает неявные преобразования "{0}" к "{1}"; тип коллекции Visual Basic 6.0 несовместим с типом коллекции .NET Framework.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoTryHandler">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "Try", "Catch" или "Finally", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoSyncLock">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'SyncLock' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "SyncLock", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoWith">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'With' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "With", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoFor">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'For' or 'For Each' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора ''For" или "For Each", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicConstructor">
<source>Attribute cannot be used because it does not have a Public constructor.</source>
<target state="translated">Использование атрибута невозможно, так как для него отсутствует открытый конструктор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultEventNotFound1">
<source>Event '{0}' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.</source>
<target state="translated">Событие "{0}" с атрибутом "DefaultEvent" не является общедоступным для данного класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNonSerializedUsage">
<source>'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.</source>
<target state="translated">'Атрибут "NonSerialized" не затронет данный член, поскольку класс, содержащий его, не предоставлен как "Serializable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedContinueKind">
<source>'Continue' must be followed by 'Do', 'For' or 'While'.</source>
<target state="translated">'После "Continue" должны следовать "Do", "For" или "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueDoNotWithinDo">
<source>'Continue Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'"Continue Do" может присутствовать только в операторе "Do".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueForNotWithinFor">
<source>'Continue For' can only appear inside a 'For' statement.</source>
<target state="translated">'"Continue For" может присутствовать только в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueWhileNotWithinWhile">
<source>'Continue While' can only appear inside a 'While' statement.</source>
<target state="translated">'"Continue While" может присутствовать только в операторе "While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParameterSpecifier">
<source>Parameter specifier is duplicated.</source>
<target state="translated">Спецификатор параметра встречается второй раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a Module cannot be declared '{0}'.</source>
<target state="translated">'Операторы "Declare" в модуле не могут объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a structure cannot be declared '{0}'.</source>
<target state="translated">'Операторы "Declare" в структуре не могут быть объявлены как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfValueType1">
<source>'TryCast' operand must be reference type, but '{0}' is a value type.</source>
<target state="translated">'Операнд "TryCast" должен быть ссылочного типа, а "{0}" является типом значения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfUnconstrainedTypeParam1">
<source>'TryCast' operands must be class-constrained type parameter, but '{0}' has no class constraint.</source>
<target state="translated">'Операнды "TryCast" должны быть параметром типа с ограничением класса, а "{0}" не имеет ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousDelegateBinding2">
<source>No accessible '{0}' is most specific: {1}</source>
<target state="translated">Отсутствие доступного "{0}" является наиболее характерным: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedStructMemberCannotSpecifyNew">
<source>Non-shared members in a Structure cannot be declared 'New'.</source>
<target state="translated">Члены структуры, не являющиеся общими, не могут быть объявлены как "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericSubMainsFound1">
<source>None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types.</source>
<target state="translated">Ни один из доступных методов "Main" с подходящими подписями в "{0}" не может быть стартовым методом, поскольку они все либо универсального типа, либо вложены в универсальный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GeneralProjectImportsError3">
<source>Error in project-level import '{0}' at '{1}' : {2}</source>
<target state="translated">Ошибка импорта на уровне проекта "{0}" в "{1}": {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidTypeForAliasesImport2">
<source>'{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.</source>
<target state="translated">"{1}" псевдонима Imports для "{0}" не ссылается на Namespace, Class, Structure, Interface, Enum или Module.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedConstant2">
<source>Field '{0}.{1}' has an invalid constant value.</source>
<target state="translated">Поле "{0}.{1}" имеет недопустимое константное значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteArgumentsNeedParens">
<source>Method arguments must be enclosed in parentheses.</source>
<target state="translated">Аргументы метода должны быть заключены в круглые скобки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLineNumbersAreLabels">
<source>Labels that are numbers must be followed by colons.</source>
<target state="translated">После числовых меток следует ставить двоеточие.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteStructureNotType">
<source>'Type' statements are no longer supported; use 'Structure' statements instead.</source>
<target state="translated">'Операторы "Type" больше не поддерживаются; используйте операторы "Structure".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteObjectNotVariant">
<source>'Variant' is no longer a supported type; use the 'Object' type instead.</source>
<target state="translated">'Тип "Variant" больше не поддерживается; используйте тип "Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLetSetNotNeeded">
<source>'Let' and 'Set' assignment statements are no longer supported.</source>
<target state="translated">'Операторы назначения "Let" и "Set" больше не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoletePropertyGetLetSet">
<source>Property Get/Let/Set are no longer supported; use the new Property declaration syntax.</source>
<target state="translated">Операторы "Property Get/Let/Set" больше не поддерживаются; используйте новый синтаксис объявления свойств.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteWhileWend">
<source>'Wend' statements are no longer supported; use 'End While' statements instead.</source>
<target state="translated">'Операторы "Wend" больше не поддерживаются; используйте операторы "End While".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteRedimAs">
<source>'ReDim' statements can no longer be used to declare array variables.</source>
<target state="translated">'Операторы "ReDim" больше не используются при объявлении переменных-массивов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOptionalWithoutValue">
<source>Optional parameters must specify a default value.</source>
<target state="translated">Для необязательных параметров должны быть заданы значения по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGosub">
<source>'GoSub' statements are no longer supported.</source>
<target state="translated">'Операторы "GoSub" больше не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOnGotoGosub">
<source>'On GoTo' and 'On GoSub' statements are no longer supported.</source>
<target state="translated">'Операторы "On GoTo" и "On GoSub" больше не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteEndIf">
<source>'EndIf' statements are no longer supported; use 'End If' instead.</source>
<target state="translated">'Операторы "EndIf" больше не поддерживаются; используйте "End If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteExponent">
<source>'D' can no longer be used to indicate an exponent, use 'E' instead.</source>
<target state="translated">'"D" больше не может использоваться для обозначения показателя степени; используйте "E".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteAsAny">
<source>'As Any' is not supported in 'Declare' statements.</source>
<target state="translated">'"As Any" в операторах "Declare" не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGetStatement">
<source>'Get' statements are no longer supported. File I/O functionality is available in the 'Microsoft.VisualBasic' namespace.</source>
<target state="translated">'Операторы "Get" больше не поддерживаются. Возможности ввода/вывода файлов доступны в пространстве имен Microsoft.VisualBasic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithArrayVsParamArray2">
<source>'{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по параметрам, объявленным как "ParamArray".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularBaseDependencies4">
<source>This inheritance causes circular dependencies between {0} '{1}' and its nested or base type '{2}'.</source>
<target state="translated">Данное наследование приводит к циклической зависимости между {0} "{1}" и вложенным в него или базовым типом "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedBase2">
<source>{0} '{1}' cannot inherit from a type nested within it.</source>
<target state="translated">{0} "{1}" не может наследовать из вложенного в него типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchOutsideAssembly4">
<source>'{0}' cannot expose type '{1}' outside the project through {2} '{3}'.</source>
<target state="translated">"{0}" не может представлять тип "{1}" вне проекта посредством {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatchOutside3">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ базы {1} за пределы сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело: '{2}'.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent6">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'.</source>
<target state="translated">"{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует в {2} "{3}" посредством {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent4">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'.</source>
<target state="translated">"{0}" не может представлять базовый тип делегата "{1}" события, которое он реализует вне проекта посредством {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycleInImportedType1">
<source>Type '{0}' is not supported because it either directly or indirectly inherits from itself.</source>
<target state="translated">Тип "{0}" не поддерживается, поскольку он прямо или косвенно наследует от себя самого.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший: "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший: "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatch7">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" до {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatchOutside5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly.</source>
<target state="translated">"{0}" не может наследовать от {1} "{2}", поскольку он расширяет доступ типа "{3}" за пределы данной сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeAccessMismatch3">
<source>Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types.</source>
<target state="translated">Указанный доступ "{0}" для "{1}" не соответствует доступу "{2}", указанному для одного из других разделяемых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeBadMustInherit1">
<source>'MustInherit' cannot be specified for partial type '{0}' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.</source>
<target state="translated">'"MustInherit" не может быть указан для разделяемого типа "{0}", так как не может быть объединен с "NotInheritable", указанным для одного из других разделяемых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverOnNotInheritPartClsMem1">
<source>'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.</source>
<target state="translated">'Невозможно определить "MustOverride" для этого члена, поскольку он находится в разделяемом типе, объявленном как "NotInheritable" в другом частичном определении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseMismatchForPartialClass3">
<source>Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types.</source>
<target state="translated">Базовый класс "{0}", указанный для класса "{1}", не может отличаться от базового класса "{2}" для одного из его других разделяемых типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeTypeParamNameMismatch3">
<source>Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'.</source>
<target state="translated">Имя параметра типа "{0}" не соответствует имени "{1}" параметра соответствующего типа, определенного на одном из других разделяемых типов "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeConstraintMismatch1">
<source>Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'.</source>
<target state="translated">Ограничения для этого параметра типа не соответствуют ограничениям для соответствующего типа параметра, определенного на одном из других разделяемых типов "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LateBoundOverloadInterfaceCall1">
<source>Late bound overload resolution cannot be applied to '{0}' because the accessing instance is an interface type.</source>
<target state="translated">Разрешение перегрузки позднего связывания нельзя применить к "{0}", поскольку экземпляр, к которому осуществляется доступ, является типом интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredAttributeConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression used as an argument to an attribute.</source>
<target state="translated">Преобразование "{0}" в "{1}" не может происходить в константном выражении, используемом в качестве аргумента атрибута.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousOverrides3">
<source>Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2}</source>
<target state="translated">Член "{0}", соответствующий данной сигнатуре, не может быть переопределен, поскольку класс "{1}" содержит несколько членов с таким же именем и сигнатурой: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverriddenCandidate1">
<source>
'{0}'</source>
<target state="translated">
"{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplements3">
<source>Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature:
'{3}'
'{4}'</source>
<target state="translated">Член "{0}.{1}", соответствующий данной сигнатуре, не может быть реализован, поскольку интерфейс "{2}" содержит несколько членов с таким же именем и сигнатурой:
"{3}"
"{4}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotCreatableDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">'Выражение "AddressOf" нельзя преобразовать в "{0}", поскольку тип "{0}" объявлен как "MustInherit" и не может быть создан.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassGenericMethod">
<source>Generic methods cannot be exposed to COM.</source>
<target state="translated">Обобщенные методы не могут быть предоставлены в COM.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntaxInCastOp">
<source>Syntax error in cast operator; two arguments separated by comma are required.</source>
<target state="translated">Синтаксическая ошибка в операторе приведения; требуются два аргумента, разделенные запятой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerForNonConstDim">
<source>Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'.</source>
<target state="translated">Инициализатор массива не может быть задан для переменной размерности; используйте пустой инициализатор "{}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingFailure3">
<source>No accessible method '{0}' has a signature compatible with delegate '{1}':{2}</source>
<target state="translated">Нет доступного метода "{0}" с сигнатурой, совместимой с делегатом "{1}": {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructLayoutAttributeNotAllowed">
<source>Attribute 'StructLayout' cannot be applied to a generic type.</source>
<target state="translated">Атрибут "StructLayout" нельзя применять к универсальному типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal1">
<source>Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression.</source>
<target state="translated">Переменная диапазона "{0}" скрывает переменную во внешнем блоке или ранее определенную переменную в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionInfer">
<source>'Option Infer' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'За "Option Infer" может следовать только "On" или "Off".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularInference1">
<source>Type of '{0}' cannot be inferred from an expression containing '{0}'.</source>
<target state="translated">Не удается получить тип "{0}" из выражения, содержащего "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleOverridingMethod5">
<source>'{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible.</source>
<target state="translated">"{0}" в классе "{1}" не может переопределять "{2}" в классе "{3}", поскольку недоступен промежуточный класс "{4}", переопределяющий "{2}" в классе "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableWidestType1">
<source>Type of '{0}' cannot be inferred because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">Невозможно получить тип "{0}", так как границы цикла и выражение шага не преобразуют в тот же тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousWidestType3">
<source>Type of '{0}' is ambiguous because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">Тип "{0}" неоднозначен, так как привязки цикла и выражение шага не преобразуются в один тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperatorInInit">
<source>'=' expected (object initializer).</source>
<target state="translated">'Ожидается "=" (инициализатор объекта).</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQualifiedNameInInit">
<source>Name of field or property being initialized in an object initializer must start with '.'.</source>
<target state="translated">Имя поля или свойства, которое инициализируется с помощью инициализатора объектов, должно начинаться с ".".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLbrace">
<source>'{' expected.</source>
<target state="translated">'Требуется "{".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeOrWith">
<source>Type or 'With' expected.</source>
<target state="translated">Требуется тип или "With".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAggrMemberInit1">
<source>Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression.</source>
<target state="translated">Несколько инициализаций "{0}". Поля и свойства можно инициализировать только один раз в выражении инициализатора объекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonFieldPropertyAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is not a field or property.</source>
<target state="translated">Член "{0}" не может быть инициализирован в выражении инициализатора объекта, так как он не является полем или свойством.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedMemberAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is shared.</source>
<target state="translated">Член "{0}" не может быть инициализирован в выражении инициализатора объекта, потому что он является общим.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterizedPropertyInAggrInit1">
<source>Property '{0}' cannot be initialized in an object initializer expression because it requires arguments.</source>
<target state="translated">Свойство "{0}" нельзя инициализировать в выражении инициализатора объекта, так как оно требует использования аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoZeroCountArgumentInitCandidates1">
<source>Property '{0}' cannot be initialized in an object initializer expression because all accessible overloads require arguments.</source>
<target state="translated">Свойство "{0}" не может быть инициализировано в выражении инициализатора объекта, так как все перегрузки требуют использования аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AggrInitInvalidForObject">
<source>Object initializer syntax cannot be used to initialize an instance of 'System.Object'.</source>
<target state="translated">Синтаксис инициализатора объектов нельзя применять для инициализации экземпляра "System.Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerExpected">
<source>Initializer expected.</source>
<target state="translated">Требуется инициализатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LineContWithCommentOrNoPrecSpace">
<source>The line continuation character '_' must be preceded by at least one white space and it must be followed by a comment or the '_' must be the last character on the line.</source>
<target state="translated">Перед символом продолжения строки "_" должен стоять по меньшей мере один пробел, а после этого символа должен идти комментарий, либо "_" должен быть последним символом в строке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFile1">
<source>Unable to load module file '{0}': {1}</source>
<target state="translated">Не удалось загрузить файл модуля "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRefLib1">
<source>Unable to load referenced library '{0}': {1}</source>
<target state="translated">Не удается загрузить указанную библиотеку "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventHandlerSignatureIncompatible2">
<source>Method '{0}' cannot handle event '{1}' because they do not have a compatible signature.</source>
<target state="translated">Методу "{0}" не удается обработать событие "{1}", поскольку они не содержат совместимую сигнатуру.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionalCompilationConstantNotValid">
<source>Conditional compilation constant '{1}' is not valid: {0}</source>
<target state="translated">Константа условной компиляции "{1}" недопустима: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwice1">
<source>Interface '{0}' can be implemented only once by this type.</source>
<target state="translated">Интерфейс "{0}" может быть реализован этим типом только один раз.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">Интерфейс "{0}" может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">Интерфейс "{0}" может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{1}" (реализован через "{2}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть реализован с этим типом только один раз, но уже существует с другими именами элементов кортежа как "{2}" (реализован через "{3}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">Интерфейс "{0}" может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">Интерфейс "{0}" может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{1}" (реализован через '{2}').</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">Интерфейс "{0}" (реализован через "{1}") может быть унаследован этим интерфейсом только один раз, но уже существует с другими именами элементов кортежа как "{2}" (реализован через "{3}").</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotImplemented1">
<source>Interface '{0}' is not implemented by this class.</source>
<target state="translated">Интерфейс "{0}" в данном классе не реализован.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplementsMember3">
<source>'{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface.</source>
<target state="translated">"{0}" существует в нескольких базовых интерфейсах. Используйте имя данного интерфейса, которое объявляет "{0}" в предложении "Implements", а не имя производного интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsOnNew">
<source>'Sub New' cannot implement interface members.</source>
<target state="translated">'"Sub New" не может содержать реализации членов интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitInStruct">
<source>Arrays declared as structure members cannot be declared with an initial size.</source>
<target state="translated">Массивы, объявляемые как члены структуры, не могут объявляться с начальным размером.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventTypeNotDelegate">
<source>Events declared with an 'As' clause must have a delegate type.</source>
<target state="translated">События, объявляемые с помощью предложения "As", должны иметь тип делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ProtectedTypeOutsideClass">
<source>Protected types can only be declared inside of a class.</source>
<target state="translated">Защищенные типы могут объявляться только в теле класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyWithNoParams">
<source>Properties with no required parameters cannot be declared 'Default'.</source>
<target state="translated">Свойства без обязательных параметров не могут объявляться как "Default".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerInStruct">
<source>Initializers on structure members are valid only for 'Shared' members and constants.</source>
<target state="translated">Инициализаторы членов структур допустимы только для членов "Shared" и констант.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateImport1">
<source>Namespace or type '{0}' has already been imported.</source>
<target state="translated">Пространство имен или тип "{0}" уже импортированы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFlags1">
<source>Modules cannot be declared '{0}'.</source>
<target state="translated">Модули не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsStmtWrongOrder">
<source>'Implements' statements must follow any 'Inherits' statement and precede all declarations in a class.</source>
<target state="translated">'После каждого оператора "Inherits" до первого объявления в классе должен присутствовать оператор "Implements".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithSynth7">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member implicitly declared for {3} '{4}' in {5} '{6}'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", что конфликтует с членом, который был неявно объявлен для {3} "{4}" в {5} "{6}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithMember5">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member of the same name in {3} '{4}'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", который конфликтует с членом с тем же именем в {3} "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberClashesWithSynth6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in {4} '{5}'.</source>
<target state="translated">{0} "{1}" конфликтует с членом, неявно объявленным для {2} "{3}" в {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeClashesWithVbCoreType4">
<source>{0} '{1}' conflicts with a Visual Basic Runtime {2} '{3}'.</source>
<target state="translated">{0} "{1}" конфликтует со средой выполнения Visual Basic {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeMissingAction">
<source>First argument to a security attribute must be a valid SecurityAction.</source>
<target state="translated">Первый аргумент для атрибута безопасности должен быть допустимым атрибутом SecurityAction.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidAction">
<source>Security attribute '{0}' has an invalid SecurityAction value '{1}'.</source>
<target state="translated">Атрибут безопасности "{0}" имеет недопустимое значение SecurityAction "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionAssembly">
<source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly.</source>
<target state="translated">Значение SecurityAction "{0}" является недопустимым для атрибутов безопасности, применяемых к сборке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod">
<source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method.</source>
<target state="translated">Значение SecurityAction "{0}" является недопустимым для атрибутов безопасности, применяемых к типу или методу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrincipalPermissionInvalidAction">
<source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute.</source>
<target state="translated">значение SecurityAction "{0}" недопустимо для атрибута PrincipalPermission.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeInvalidFile">
<source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute.</source>
<target state="translated">Не удается найти путь к файлу "{0}", указанному для именованного аргумента "{1}" для атрибута PermissionSet.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeFileReadError">
<source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'.</source>
<target state="translated">Ошибка чтения файла "{0}", указанного для именованного аргумента "{1}" для атрибута PermissionSet: '{2}'.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasOnlyOneParam">
<source>'Set' method cannot have more than one parameter.</source>
<target state="translated">'Метод "Set" не может иметь более одного параметра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetValueNotPropertyType">
<source>'Set' parameter must have the same type as the containing property.</source>
<target state="translated">'Тип параметра метода "Set" должен совпадать с типом содержащего его свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasToBeByVal1">
<source>'Set' parameter cannot be declared '{0}'.</source>
<target state="translated">'Невозможно объявить параметр "Set" как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureCantUseProtected">
<source>Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.</source>
<target state="translated">Метод в структуре нельзя объявлять как "Protected", "Protected Friend" или "Private Protected".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceDelegateSpecifier1">
<source>Delegate in an interface cannot be declared '{0}'.</source>
<target state="translated">Делегат в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceEnumSpecifier1">
<source>Enum in an interface cannot be declared '{0}'.</source>
<target state="translated">Перечисление в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceClassSpecifier1">
<source>Class in an interface cannot be declared '{0}'.</source>
<target state="translated">Класс в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceStructSpecifier1">
<source>Structure in an interface cannot be declared '{0}'.</source>
<target state="translated">Структура в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceInterfaceSpecifier1">
<source>Interface in an interface cannot be declared '{0}'.</source>
<target state="translated">Интерфейс в интерфейсе не может объявляться как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">"{0}" является устаревшим.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotAssembly">
<source>'{0}' is a module and cannot be referenced as an assembly.</source>
<target state="translated">"{0}" является модулем и не может указываться в ссылках как сборка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotModule">
<source>'{0}' is an assembly and cannot be referenced as a module.</source>
<target state="translated">"{0}" является сборкой и не может указываться в ссылках как модуль.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceComparison3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types.</source>
<target state="translated">Оператор "{0}" не определен для типов "{1}" и "{2}". Используйте оператор "Is" для сравнения двух ссылочных типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchVariableNotLocal1">
<source>'{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.</source>
<target state="translated">"{0}" не является локальной переменной или параметром и поэтому не может использоваться как переменная оператора "Catch".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleMemberCantImplement">
<source>Members in a Module cannot implement interface members.</source>
<target state="translated">Методы в модуле не могут содержать реализацию членов интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventDelegatesCantBeFunctions">
<source>Events cannot be declared with a delegate type that has a return type.</source>
<target state="translated">События не могут объявляться типом делегата, обладающим возвращаемым типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDate">
<source>Date constant is not valid.</source>
<target state="translated">Константа даты является недействительной.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverride4">
<source>'{0}' cannot override '{1}' because it is not declared 'Overridable'.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку он не объявлен как "Overridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArraysOnBoth">
<source>Array modifiers cannot be specified on both a variable and its type.</source>
<target state="translated">Модификаторы массива не могут задаваться одновременно для переменной и ее типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotOverridableRequiresOverrides">
<source>'NotOverridable' cannot be specified for methods that do not override another method.</source>
<target state="translated">'"NotOverridable" не может назначаться для методов, не переопределяющих другие методы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrivateTypeOutsideType">
<source>Types declared 'Private' must be inside another type.</source>
<target state="translated">Типы, объявленные как "Private", должны находиться внутри других типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeRefResolutionError3">
<source>Import of type '{0}' from assembly or module '{1}' failed.</source>
<target state="translated">Импортирование типа "{0}" из сборки или модуля "{1}" невозможно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleTypeRefResolutionError1">
<source>Predefined type '{0}' is not defined or imported.</source>
<target state="translated">Предопределенный тип "{0}" не определен и не импортирован.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWrongType">
<source>ParamArray parameters must have an array type.</source>
<target state="translated">Параметры ParamArray должны быть массивами.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CoClassMissing2">
<source>Implementing class '{0}' for interface '{1}' cannot be found.</source>
<target state="translated">Не удается найти класс реализации "{0}" для интерфейса "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidCoClass1">
<source>Type '{0}' cannot be used as an implementing class.</source>
<target state="translated">Тип "{0}" не может использоваться как класс реализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMeReference">
<source>Reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">При вызове другого конструктора ссылки на объект, находящийся в процессе построения, недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitMeReference">
<source>Implicit reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">При вызове другого конструктора неявные ссылки на объект, находящийся в процессе построения, недопустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeMemberNotFound2">
<source>Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'.</source>
<target state="translated">Член "{0}" не может быть найден в классе "{1}". Это условие, как правило, является результатом несоответствия "Microsoft.VisualBasic.dll".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags">
<source>Property accessors cannot be declared '{0}'.</source>
<target state="translated">Методы доступа к свойствам нельзя объявить как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlagsRestrict">
<source>Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.</source>
<target state="translated">Модификатор доступа "{0}" недействителен. Модификатор доступа для "Get" и "Set" должен быть более ограничивающим, чем уровень доступа к свойству.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneAccessorForGetSet">
<source>Access modifier can only be applied to either 'Get' or 'Set', but not both.</source>
<target state="translated">Модификатор доступа может применяться либо к "Get", либо к "Set", но не к обоим методам одновременно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleSet">
<source>'Set' accessor of property '{0}' is not accessible.</source>
<target state="translated">'Метод доступа свойства "Set" "{0}" недоступен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleGet">
<source>'Get' accessor of property '{0}' is not accessible.</source>
<target state="translated">'Метод доступа свойства "Get" "{0}" недоступен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyNoAccessorFlag">
<source>'WriteOnly' properties cannot have an access modifier on 'Set'.</source>
<target state="translated">'Свойства со спецификатором WriteOnly не могут иметь модификатор доступа для Set.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyNoAccessorFlag">
<source>'ReadOnly' properties cannot have an access modifier on 'Get'.</source>
<target state="translated">'Свойства со спецификатором "ReadOnly" не могут иметь модификатор доступа для "Get".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags1">
<source>Property accessors cannot be declared '{0}' in a 'NotOverridable' property.</source>
<target state="translated">Методы доступа к свойствам нельзя объявить как "{0}" в свойстве "NotOverridable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags2">
<source>Property accessors cannot be declared '{0}' in a 'Default' property.</source>
<target state="translated">Методы доступа к свойствам нельзя объявить "{0}" в свойстве "Default".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags3">
<source>Property cannot be declared '{0}' because it contains a 'Private' accessor.</source>
<target state="translated">Свойство не может быть объявлено "{0}", поскольку оно содержит метод доступа "Private".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleCoClass3">
<source>Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">Реализация класса "{0}" для интерфейса "{1}" недоступна в этом контексте, поскольку он является "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingValuesForArraysInApplAttrs">
<source>Arrays used as attribute arguments are required to explicitly specify values for all elements.</source>
<target state="translated">Для массивов, используемых как аргументы атрибутов, требуется явное указание значений для всех элементов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitEventMemberNotInvalid">
<source>'Exit AddHandler', 'Exit RemoveHandler' and 'Exit RaiseEvent' are not valid. Use 'Return' to exit from event members.</source>
<target state="translated">'"Exit AddHandler", "Exit RemoveHandler" и "Exit RaiseEvent" недопустимы. Используйте "Return" для выхода из членов-событий.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEvent">
<source>Statement cannot appear within an event body. End of event assumed.</source>
<target state="translated">Оператор не может появляться в теле события. Подразумевается завершение события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEvent">
<source>'Custom Event' must end with a matching 'End Event'.</source>
<target state="translated">'Оператор "Custom Event" должен завершаться соответствующим оператором "End Event".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndAddHandler">
<source>'AddHandler' declaration must end with a matching 'End AddHandler'.</source>
<target state="translated">'Объявление "AddHandler" должно завершаться соответствующим оператором "End AddHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRemoveHandler">
<source>'RemoveHandler' declaration must end with a matching 'End RemoveHandler'.</source>
<target state="translated">'Объявление "RemoveHandler" должно завершаться соответствующим оператором "End RemoveHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRaiseEvent">
<source>'RaiseEvent' declaration must end with a matching 'End RaiseEvent'.</source>
<target state="translated">'Объявление "RaiseEvent" должно завершаться соответствующим оператором "End RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventInvInInterface">
<source>'Custom' modifier is not valid on events declared in interfaces.</source>
<target state="translated">'Модификатор Custom недопустим для событий, объявленных в интерфейсах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventRequiresAs">
<source>'Custom' modifier is not valid on events declared without explicit delegate types.</source>
<target state="translated">'Модификатор "Custom" недопустим для событий, объявленных без явных типов делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEvent">
<source>'End Event' must be preceded by a matching 'Custom Event'.</source>
<target state="translated">'Оператору "End Event" должен предшествовать соответствующий оператор "Custom Event".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndAddHandler">
<source>'End AddHandler' must be preceded by a matching 'AddHandler' declaration.</source>
<target state="translated">'Оператору "End AddHandler "должно предшествовать соответствующее объявление "AddHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRemoveHandler">
<source>'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.</source>
<target state="translated">'Оператору "End RemoveHandler" должно предшествовать соответствующее объявление "RemoveHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRaiseEvent">
<source>'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.</source>
<target state="translated">'Оператору "End RaiseEvent" должно предшествовать соответствующее объявление "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAddHandlerDef">
<source>'AddHandler' is already declared.</source>
<target state="translated">'"AddHandler" уже объявлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRemoveHandlerDef">
<source>'RemoveHandler' is already declared.</source>
<target state="translated">'Процедура "RemoveHandler" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRaiseEventDef">
<source>'RaiseEvent' is already declared.</source>
<target state="translated">'Процедура "RaiseEvent" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingAddHandlerDef1">
<source>'AddHandler' definition missing for event '{0}'.</source>
<target state="translated">'Отсутствует определение "AddHandler" события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRemoveHandlerDef1">
<source>'RemoveHandler' definition missing for event '{0}'.</source>
<target state="translated">'Отсутствует определение "RemoveHandler" события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRaiseEventDef1">
<source>'RaiseEvent' definition missing for event '{0}'.</source>
<target state="translated">'Отсутствует определение "RaiseEvent" события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveHasOnlyOneParam">
<source>'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.</source>
<target state="translated">'У методов "AddHandler" и "RemoveHandler" должен быть ровно один параметр.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveByrefParamIllegal">
<source>'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.</source>
<target state="translated">'Параметры методов "AddHandler" и "RemoveHandler" не могут быть объявлены как "ByRef".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvOnEventMethod">
<source>Specifiers are not valid on 'AddHandler', 'RemoveHandler' and 'RaiseEvent' methods.</source>
<target state="translated">Спецификаторы не применимы к методам "AddHandler", "RemoveHandler" и "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddRemoveParamNotEventType">
<source>'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.</source>
<target state="translated">'Параметры методов "AddHandler" и "RemoveHandler" должны иметь такой же тип делегата, как содержащее их событие.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RaiseEventShapeMismatch1">
<source>'RaiseEvent' method must have the same signature as the containing event's delegate type '{0}'.</source>
<target state="translated">'Метод "RaiseEvent" должен иметь одинаковую сигнатуру с типом делегата содержащегося события "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventMethodOptionalParamIllegal1">
<source>'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared '{0}'.</source>
<target state="translated">'Параметры методов "AddHandler", "RemoveHandler" и "RaiseEvent" не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReferToMyGroupInsideGroupType1">
<source>'{0}' cannot refer to itself through its default instance; use 'Me' instead.</source>
<target state="translated">"{0}" не может ссылаться на себя с помощью экземпляра по умолчанию; вместо этого используйте "Me".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfCustomModifier">
<source>'Custom' modifier can only be used immediately before an 'Event' declaration.</source>
<target state="translated">'Модификатор "Custom" может использоваться только непосредственно перед объявлением "Event".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrictCustom">
<source>Option Strict Custom can only be used as an option to the command-line compiler (vbc.exe).</source>
<target state="translated">Option Strict Custom может использоваться только как параметр компилятора командной строки (vbc.exe).</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteInvalidOnEventMember">
<source>'{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.</source>
<target state="translated">"{0}" не может быть применен к определениям "AddHandler", "RemoveHandler" или "RaiseEvent". При необходимости примените атрибут непосредственно к событию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible2">
<source>Method '{0}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">Метод расширения "{0}" не имеет сигнатуры, совместимой с делегатом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlName">
<source>XML name expected.</source>
<target state="translated">Ожидалось XML-имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedXmlPrefix">
<source>XML namespace prefix '{0}' is not defined.</source>
<target state="translated">Префикс пространства имен XML "{0}" не определен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateXmlAttribute">
<source>Duplicate XML attribute '{0}'.</source>
<target state="translated">Повторяющийся атрибут XML "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MismatchedXmlEndTag">
<source>End tag </{0}{1}{2}> expected.</source>
<target state="translated">Требуется конечный тег </{0}{1}{2}>.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingXmlEndTag">
<source>Element is missing an end tag.</source>
<target state="translated">В элементе отсутствует конечный тег.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlPrefix">
<source>XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed.</source>
<target state="translated">Префикс пространства имен XML "{0}" зарезервирован для использования XML, и пространство имен URI не может быть изменено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingVersionInXmlDecl">
<source>Required attribute 'version' missing from XML declaration.</source>
<target state="translated">В объявлении XML отсутствует необходимый атрибут "version".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalAttributeInXmlDecl">
<source>XML declaration does not allow attribute '{0}{1}{2}'.</source>
<target state="translated">В объявлении XML не может быть атрибута "{0}{1}{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_QuotedEmbeddedExpression">
<source>Embedded expression cannot appear inside a quoted attribute value. Try removing quotes.</source>
<target state="translated">Вложенное выражение не может появляться внутри значения атрибута в кавычках. Попробуйте убрать кавычки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VersionMustBeFirstInXmlDecl">
<source>XML attribute 'version' must be the first attribute in XML declaration.</source>
<target state="translated">Атрибут XML "version" должен быть первым атрибутом в объявлении XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOrder">
<source>XML attribute '{0}' must appear before XML attribute '{1}'.</source>
<target state="translated">Атрибут XML "{0}" должен предшествовать атрибуту XML "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndEmbedded">
<source>Expected closing '%>' for embedded expression.</source>
<target state="translated">Для вложенного выражения требуются закрывающие символы "%>".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndPI">
<source>Expected closing '?>' for XML processor instruction.</source>
<target state="translated">В инструкции XML-процессора требуется закрывающие символы "?>".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndComment">
<source>Expected closing '-->' for XML comment.</source>
<target state="translated">В комментарии XML требуются закрывающие символы "-->".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndCData">
<source>Expected closing ']]>' for XML CDATA section.</source>
<target state="translated">Требуются закрывающие символы "]]>" для XML-секции CDATA.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSQuote">
<source>Expected matching closing single quote for XML attribute value.</source>
<target state="translated">Для значения атрибута XML требуется закрывающая одинарная кавычка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQuote">
<source>Expected matching closing double quote for XML attribute value.</source>
<target state="translated">Для значения атрибута XML требуется закрывающая двойная кавычка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLT">
<source>Expected beginning '<' for an XML tag.</source>
<target state="translated">Для XML-тега требуется открывающий символ "<".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartAttributeValue">
<source>Expected quoted XML attribute value or embedded expression.</source>
<target state="translated">Требуется заключенное в кавычки значение атрибута XML или вложенное выражение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDiv">
<source>Expected '/' for XML end tag.</source>
<target state="translated">Для закрывающего XML-тега требуется символ "/".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoXmlAxesLateBinding">
<source>XML axis properties do not support late binding.</source>
<target state="translated">Свойства оси XML не поддерживают позднее связывание.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlStartNameChar">
<source>Character '{0}' ({1}) is not allowed at the beginning of an XML name.</source>
<target state="translated">Не допускается использование символа "{0}" ({1}) в начале имени XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlNameChar">
<source>Character '{0}' ({1}) is not allowed in an XML name.</source>
<target state="translated">Не допускается использование символа "{0}" ({1}) в имени XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlCommentChar">
<source>Character sequence '--' is not allowed in an XML comment.</source>
<target state="translated">Последовательность символов "--" недопустима в XML-комментарии.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmbeddedExpression">
<source>An embedded expression cannot be used here.</source>
<target state="translated">Вложенное выражение не может быть здесь использовано.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlWhiteSpace">
<source>Missing required white space.</source>
<target state="translated">Отсутствует обязательный пробел.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalProcessingInstructionName">
<source>XML processing instruction name '{0}' is not valid.</source>
<target state="translated">Недопустимое имя инструкции по обработке XML "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DTDNotSupported">
<source>XML DTDs are not supported.</source>
<target state="translated">Шаблоны DTD XML не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlWhiteSpace">
<source>White space cannot appear here.</source>
<target state="translated">Здесь не может находиться пробел.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSColon">
<source>Expected closing ';' for XML entity.</source>
<target state="translated">Для XML-сущности требуется закрывающий знак ";".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlBeginEmbedded">
<source>Expected '%=' at start of an embedded expression.</source>
<target state="translated">В начале вложенного выражения требуется "%=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEntityReference">
<source>XML entity references are not supported.</source>
<target state="translated">Ссылки на специальный символ XML не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue1">
<source>Attribute value is not valid; expecting '{0}'.</source>
<target state="translated">Недопустимое значение атрибута; ожидается значение "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue2">
<source>Attribute value is not valid; expecting '{0}' or '{1}'.</source>
<target state="translated">Недопустимое значение атрибута; ожидается значение "{0}" или "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlNamespace">
<source>Prefix '{0}' cannot be bound to namespace name reserved for '{1}'.</source>
<target state="translated">Префикс "{0}" не может быть привязан к имени пространства имен, зарезервированных для "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalDefaultNamespace">
<source>Namespace declaration with prefix cannot have an empty value inside an XML literal.</source>
<target state="translated">Объявление пространства имен вместе с префиксом не может иметь пустое значение внутри XML-литерала.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualifiedNameNotAllowed">
<source>':' is not allowed. XML qualified names cannot be used in this context.</source>
<target state="translated">'Символ ":" не допустим. Не удается использовать уточненные XML-имена в этом контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlns">
<source>Namespace declaration must start with 'xmlns'.</source>
<target state="translated">Объявление пространства имен должно начинаться с "xmlns".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlnsPrefix">
<source>Element names cannot use the 'xmlns' prefix.</source>
<target state="translated">В именах элементов не может использоваться префикс "xmlns".</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlFeaturesNotAvailable">
<source>XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.</source>
<target state="translated">Литералы XML и свойства оси XML недоступны. Добавьте ссылки на System.Xml, System.Xml.Linq и System.Core или другие сборки, объявляющие типы System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute и System.Xml.Linq.XNamespace.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToReadUacManifest2">
<source>Unable to open Win32 manifest file '{0}' : {1}</source>
<target state="translated">Не удалось открыть файл манифеста Win32 "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3">
<source>Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">Не удается преобразовать "{0}" в "{1}". Вы можете использовать свойство "Value", чтобы получить строковое значение первого элемента "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3_Title">
<source>Cannot convert IEnumerable(Of XElement) to String</source>
<target state="translated">Невозможно преобразовать IEnumerable(XElement) в строку</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatchForXml3">
<source>Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">Значение типа "{0}" невозможно преобразовать в "{1}". Вы можете использовать свойство "Value", чтобы получить строковое значение первого элемента "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperandsForXml4">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'.</source>
<target state="translated">Оператор "{0}" не определен для типов "{1}" и "{2}". Вы можете использовать свойство "Value", чтобы получить строковое значение первого элемента "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FullWidthAsXmlDelimiter">
<source>Full width characters are not valid as XML delimiters.</source>
<target state="translated">Широкие символы не допускаются в качестве разделителей XML.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSubsystemVersion">
<source>The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise.</source>
<target state="translated">Значение "{0}" не является допустимой версией подсистемы. Для ARM или AppContainerExe должна быть указана версия 6.02 или выше, в остальных случаях — версия 4.00 или выше.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFileAlignment">
<source>Invalid file section alignment '{0}'</source>
<target state="translated">Недопустимое выравнивание разделов файла "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOutputName">
<source>Invalid output name: {0}</source>
<target state="translated">Недопустимое имя выходных данных: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInformationFormat">
<source>Invalid debug information format: {0}</source>
<target state="translated">Недопустимый формат отладочной информации: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibAnycpu32bitPreferredConflict">
<source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe.</source>
<target state="translated">Параметр /platform:anycpu32bitpreferred можно использовать только вместе с параметрами /t:exe, /t:winexe и /t:appcontainerexe.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedAccess">
<source>Expression has the type '{0}' which is a restricted type and cannot be used to access members inherited from 'Object' or 'ValueType'.</source>
<target state="translated">Выражение имеет тип "{0}", который является ограниченным типом и не может использоваться для доступа к членам, унаследованным из "Object" или "ValueType".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedConversion1">
<source>Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'.</source>
<target state="translated">Выражение типа "{0}" невозможно преобразовать в "Object" или "ValueType".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInLabel">
<source>Type characters are not allowed in label identifiers.</source>
<target state="translated">Символы типа недопустимы в идентификаторах меток.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedType1">
<source>'{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.</source>
<target state="translated">"{0}" не может принимать значение Null и не может быть использовано в качестве типа данных элемента массива, поля, анонимного типа члена, аргумента типа, параметра "ByRef" или оператора return.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInAlias">
<source>Type characters are not allowed on Imports aliases.</source>
<target state="translated">Символы типа недопустимы для псевдонимов Imports.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleConstructorOnBase">
<source>Class '{0}' has no accessible 'Sub New' and cannot be inherited.</source>
<target state="translated">Класс "{0}" не имеет доступного "Sub New" и не может быть унаследован.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInStruct">
<source>Local variables within methods of structures cannot be declared 'Static'.</source>
<target state="translated">Локальные переменные в методах структур не могут объявляться как "Static".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalStatic1">
<source>Static local variable '{0}' is already declared.</source>
<target state="translated">Статическая локальная переменная "{0}" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportAliasConflictsWithType2">
<source>Imports alias '{0}' conflicts with '{1}' declared in the root namespace.</source>
<target state="translated">Псевдоним Imports "{0}" конфликтует с "{1}", объявленном в корневом пространстве имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantShadowAMustOverride1">
<source>'{0}' cannot shadow a method declared 'MustOverride'.</source>
<target state="translated">"{0}" не может сделать теневым метод, объявленный как "MustOverride".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleEventImplMismatch3">
<source>Event '{0}' cannot implement event '{2}.{1}' because its delegate type does not match the delegate type of another event implemented by '{0}'.</source>
<target state="translated">Событию "{0}" не удается реализовать событие "{2}.{1}", поскольку его тип делегата не соответствует типу делегата другого события, реализованного "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSpecifierCombo2">
<source>'{0}' and '{1}' cannot be combined.</source>
<target state="translated">"{0}" и "{1}" объединять нельзя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeOverloads2">
<source>{0} '{1}' must be declared 'Overloads' because another '{1}' is declared 'Overloads' or 'Overrides'.</source>
<target state="translated">{0} "{1}" должно быть объявлено как "Overloads", поскольку другая переменная "{1}" объявлена как "Overloads" или "Overrides".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverridesInClass1">
<source>'{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.</source>
<target state="translated">"{0}" должна быть объявлена как "MustInherit", потому что она содержит методы, объявленные как "MustOverride".</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInClass">
<source>'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.</source>
<target state="translated">'В "Handles" в классах должна указываться переменная, объявленная с модификатором "WithEvents", либо объект "MyBase", "MyClass" или "Me", ограниченный одним идентификатором.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberShadowsMustOverride5">
<source>'{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'.</source>
<target state="translated">"{0}", неявно объявленный для {1} "{2}", не может затенять метод "MustOverride" в базе {3} "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotOverrideInAccessibleMember">
<source>'{0}' cannot override '{1}' because it is not accessible in this context.</source>
<target state="translated">"{0}" не может переопределить "{1}", поскольку он недоступен в данном контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInModule">
<source>'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.</source>
<target state="translated">'В "Handles" в модулях должна указываться переменная с модификатором WithEvents, ограниченная одним идентификатором.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOpRequiresReferenceTypes1">
<source>'IsNot' requires operands that have reference types, but this operand has the value type '{0}'.</source>
<target state="translated">'Для "IsNot" требуются операнды ссылочных типов, а этот операнд имеет тип значения "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClashWithReservedEnumMember1">
<source>'{0}' conflicts with the reserved member by this name that is implicitly declared in all enums.</source>
<target state="translated">"{0}" конфликтует с зарезервированным членом по данному имени, которое явно объявлено во всех перечислениях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedEnumMember2">
<source>'{0}' is already declared in this {1}.</source>
<target state="translated">"{0}" уже объявлено в {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadUseOfVoid">
<source>'System.Void' can only be used in a GetType expression.</source>
<target state="translated">'System.Void можно использовать только в выражении GetType.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplMismatch5">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because their delegate types '{3}' and '{4}' do not match.</source>
<target state="translated">Событию "{0}" не удается реализовать событие "{1}" в интерфейсе "{2}" из-за несовпадения их типов делегатов "{3}" и "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeUnavailable3">
<source>Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'.</source>
<target state="translated">Тип "{0}" в сборке "{1}" переадресован в сборку "{2}". Либо ссылка на "{2}" отсутствует в вашем проекте, либо тип "{0}" отсутствует в сборке "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeFwdCycle2">
<source>'{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type.</source>
<target state="translated">"{0}" в сборке "{1}" был перемещен к себе и поэтому является недопустимым типом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeInCCExpression">
<source>Non-intrinsic type names are not allowed in conditional compilation expressions.</source>
<target state="translated">Имена типов, отличных от встроенных, недопустимы в выражениях условной компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCCExpression">
<source>Syntax error in conditional compilation expression.</source>
<target state="translated">Синтаксическая ошибка в выражении условной компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidArrayDisallowed">
<source>Arrays of type 'System.Void' are not allowed in this expression.</source>
<target state="translated">Массивы типа "System.Void" недопустимы в данном выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataMembersAmbiguous3">
<source>'{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'.</source>
<target state="translated">"{0}" неоднозначно, поскольку несколько видов членов с данным именем существует в {1} "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfExprAlwaysFalse2">
<source>Expression of type '{0}' can never be of type '{1}'.</source>
<target state="translated">Выражение типа "{0}" не может относиться к типу "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyPrivatePartialMethods1">
<source>Partial methods must be declared 'Private' instead of '{0}'.</source>
<target state="translated">Разделяемые методы должны быть объявлены "Private", а не "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBePrivate">
<source>Partial methods must be declared 'Private'.</source>
<target state="translated">Разделяемые методы должны быть объявлены как "Private".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOnePartialMethodAllowed2">
<source>Method '{0}' cannot be declared 'Partial' because only one method '{1}' can be marked 'Partial'.</source>
<target state="translated">Метод "{0}" не может быть объявлен "Partial", так как только один метод "{1}" может быть помечен как "Partial".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneImplementingMethodAllowed3">
<source>Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method.</source>
<target state="translated">Метод "{0}" не может реализовывать разделяемый метод "{1}", так как "{2}" он уже реализован. Только один метод может реализовать разделяемый метод.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodMustBeEmpty">
<source>Partial methods must have empty method bodies.</source>
<target state="translated">Разделяемые методы должны иметь пустое тело метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBeSub1">
<source>'{0}' cannot be declared 'Partial' because partial methods must be Subs.</source>
<target state="translated">"{0}" не может быть объявлен "Partial", так как разделяемые методы должны быть Subs.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodGenericConstraints2">
<source>Method '{0}' does not have the same generic constraints as the partial method '{1}'.</source>
<target state="translated">Метод "{0}" не имеет те же универсальные ограничения, что и разделяемый метод "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialDeclarationImplements1">
<source>Partial method '{0}' cannot use the 'Implements' keyword.</source>
<target state="translated">Разделяемый метод "{0}" не может использовать ключевое слово "Implements".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPartialMethodInAddressOf1">
<source>'AddressOf' cannot be applied to '{0}' because '{0}' is a partial method without an implementation.</source>
<target state="translated">'"AddressOf" не может быть применен к "{0}", так как "{0}" является разделяемым методом без реализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementationMustBePrivate2">
<source>Method '{0}' must be declared 'Private' in order to implement partial method '{1}'.</source>
<target state="translated">Метод "{0}" должен быть объявлен как "Private", чтобы реализовать частичный метод "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamNamesMustMatch3">
<source>Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'.</source>
<target state="translated">Имя параметра "{0}" не соответствует имени соответствующего параметра "{1}", определенного для объявления разделяемого метода "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodTypeParamNameMismatch3">
<source>Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'.</source>
<target state="translated">Имя параметра типа "{0}" не соответствует "{1}", соответствующий параметр типа, определенный для объявления разделяемого метода "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeSharedProperty1">
<source>'Shared' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Свойству атрибута "Shared" "{0}" нельзя присваивать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeReadOnlyProperty1">
<source>'ReadOnly' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Свойству атрибута "ReadOnly" "{0}" нельзя присваивать значение.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceName1">
<source>Resource name '{0}' cannot be used more than once.</source>
<target state="translated">Имя ресурса "{0}" не может использоваться более одного раза.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceFileName1">
<source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly.</source>
<target state="translated">Каждый связанный ресурс и модуль должны иметь уникальное имя файла. Имя файла "{0}" определено более одного раза в этой сборке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustBeClassNotStruct1">
<source>'{0}' cannot be used as an attribute because it is not a class.</source>
<target state="translated">"{0}" нельзя использовать как атрибут, поскольку он не является классом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustInheritSysAttr">
<source>'{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'.</source>
<target state="translated">"{0}" нельзя использовать как атрибут, так как он не является производным от "System.Attribute".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeCannotBeAbstract">
<source>'{0}' cannot be used as an attribute because it is declared 'MustInherit'.</source>
<target state="translated">"{0}" не может использоваться как атрибут, поскольку он объявлен как "MustInherit".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToOpenResourceFile1">
<source>Unable to open resource file '{0}': {1}</source>
<target state="translated">Не удалось открыть файл ресурсов "{0}". {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicProperty1">
<source>Attribute member '{0}' cannot be the target of an assignment because it is not declared 'Public'.</source>
<target state="translated">Члену атрибута "{0}" нельзя присваивать значение, поскольку он не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_STAThreadAndMTAThread0">
<source>'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.</source>
<target state="translated">'Атрибуты "System.STAThreadAttribute" и "System.MTAThreadAttribute" не могут вместе использоваться для одного метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndirectUnreferencedAssembly4">
<source>Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project.</source>
<target state="translated">В проекте "{0}" имеется косвенная ссылка на сборку "{1}", которая содержит "{2}". Добавьте к проекту ссылку на файл "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicType1">
<source>Type '{0}' cannot be used in an attribute because it is not declared 'Public'.</source>
<target state="translated">Тип "{0}" нельзя использовать в атрибуте, поскольку он не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicContType2">
<source>Type '{0}' cannot be used in an attribute because its container '{1}' is not declared 'Public'.</source>
<target state="translated">Тип "{0}" нельзя использовать в атрибуте, поскольку его контейнер "{1}" не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnNonEmptySubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к блоку Sub, Function или Operator с непустым телом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnDeclare">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Declare.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не применим к оператору Declare.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnGetOrSet">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Get or Set.</source>
<target state="translated">'Атрибут System.Runtime.InteropServices.DllImportAttribute не может применяться к оператору Get или Set.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnGenericSubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a method that is generic or contained in a generic type.</source>
<target state="translated">'Атрибут System.Runtime.InteropServices.DllImportAttribute не может применяться к универсальному методу или методу, содержащемуся в универсальном типе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassOnGeneric">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute не может применяться к универсальному классу или классу, содержащемуся в универсальном типе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInstanceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методу экземпляра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInterfaceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to interface methods.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методам интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnEventMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to 'AddHandler', 'RemoveHandler' or 'RaiseEvent' method.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методам "AddHandler", "RemoveHandler" и "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadArguments">
<source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source>
<target state="translated">Недопустимая дружественная ссылка на сборку "{0}". Объявления InternalsVisibleTo не содержат определения версии, языка и региональных параметров, токена открытого ключа или архитектуры процессора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyStrongNameRequired">
<source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source>
<target state="translated">Недопустимая дружественная ссылка на сборку "{0}". Сборки, подписанные строгим именем, должны содержать в объявлении InternalsVisibleTo открытый ключ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyNameInvalid">
<source>Friend declaration '{0}' is invalid and cannot be resolved.</source>
<target state="translated">Дружественное объявление "{0}" недопустимо и не может быть разрешено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadAccessOverride2">
<source>Member '{0}' cannot override member '{1}' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.</source>
<target state="translated">Член "{0}" не может переопределить член "{1}", определенный в другой сборке или проекте, так как модификатор доступа "Protected Friend" расширяет доступность. Вместо него используйте "Protected".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfLocalBeforeDeclaration1">
<source>Local variable '{0}' cannot be referred to before it is declared.</source>
<target state="translated">Невозможно указать локальную переменную "{0}" до ее объявления.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromModule1">
<source>'{0}' is not valid within a Module.</source>
<target state="translated">"{0}" не является допустимым в модуле.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BogusWithinLineIf">
<source>Statement cannot end a block outside of a line 'If' statement.</source>
<target state="translated">Нельзя завершить блок, внешний по отношению к однострочному оператору If.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CharToIntegralTypeMismatch1">
<source>'Char' values cannot be converted to '{0}'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit.</source>
<target state="translated">'Значения "Char" невозможно преобразовать в "{0}". Используйте "Microsoft.VisualBasic.AscW" для интерпретации символа как символа Юникода или "Microsoft.VisualBasic.Val" для интерпретации его как цифры.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IntegralToCharTypeMismatch1">
<source>'{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit.</source>
<target state="translated">'"Значения "{0}" невозможно преобразовать в "Char". Используйте "Microsoft.VisualBasic.ChrW" для интерпретации числового значения как символа Юникода или сначала преобразуйте его в значение типа "String" для получения цифры.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDirectDelegateConstruction1">
<source>Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.</source>
<target state="translated">Делегат "{0}" требует выражение "AddressOf" или лямбда-выражение в качестве единственного аргумента конструктора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodMustBeFirstStatementOnLine">
<source>Method declaration statements must be the first statement on a logical line.</source>
<target state="translated">Операторы объявления методов должны указываться первыми в логической строке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrAssignmentNotFieldOrProp1">
<source>'{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property.</source>
<target state="translated">"{0}" нельзя указать как параметр в описателе атрибута, поскольку он не является полем или свойством.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectComparison1">
<source>Option Strict On disallows operands of type Object for operator '{0}'. Use the 'Is' operator to test for object identity.</source>
<target state="translated">Option Strict On не разрешает операнды типа Object для оператора "{0}". Используйте оператор "Is" для проверки идентификатора объекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstituentArraySizes">
<source>Bounds can be specified only for the top-level array when initializing an array of arrays.</source>
<target state="translated">При инициализации массива массивов границы могут задаваться только для массива верхнего уровня.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileAttributeNotAssemblyOrModule">
<source>'Assembly' or 'Module' expected.</source>
<target state="translated">'Требуется "Assembly" или "Module".</target>
<note />
</trans-unit>
<trans-unit id="ERR_FunctionResultCannotBeIndexed1">
<source>'{0}' has no parameters and its return type cannot be indexed.</source>
<target state="translated">"{0}" не имеет параметров, поэтому невозможно проиндексировать его возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentSyntax">
<source>Comma, ')', or a valid expression continuation expected.</source>
<target state="translated">Требуется запятая, ")" или допустимое продолжение выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedResumeOrGoto">
<source>'Resume' or 'GoTo' expected.</source>
<target state="translated">'Требуется "Resume" или "GoTo".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperator">
<source>'=' expected.</source>
<target state="translated">'Требуется "=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted2">
<source>Parameter '{0}' in '{1}' already has a matching omitted argument.</source>
<target state="translated">Параметр "{0}" в "{1}" уже имеет соответствующий пропущенный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotCallEvent1">
<source>'{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.</source>
<target state="translated">"{0}" является событием и не может вызываться напрямую. Для порождения события используйте оператор "RaiseEvent".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachCollectionDesignPattern1">
<source>Expression is of type '{0}', which is not a collection type.</source>
<target state="translated">Выражение имеет тип "{0}", не являющийся типом коллекции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultValueForNonOptionalParam">
<source>Default values cannot be supplied for parameters that are not declared 'Optional'.</source>
<target state="translated">Значения по умолчанию не могут задаваться для параметров, не объявленных как "Optional".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyBase">
<source>'MyBase' must be followed by '.' and an identifier.</source>
<target state="translated">'После "MyBase" должны следовать "." и идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyClass">
<source>'MyClass' must be followed by '.' and an identifier.</source>
<target state="translated">'После "MyClass" должны следовать "." и идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictArgumentCopyBackNarrowing3">
<source>Option Strict On disallows narrowing from type '{1}' to type '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">Option Strict On не разрешает сужение из типа "{1}" в тип "{2}" при копировании значения параметра "ByRef" "{0}" обратно в соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseifAfterElse">
<source>'#ElseIf' cannot follow '#Else' as part of a '#If' block.</source>
<target state="translated">'Блок "#ElseIf" не может следовать за "#Else" в пределах блока "#If".</target>
<note />
</trans-unit>
<trans-unit id="ERR_StandaloneAttribute">
<source>Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.</source>
<target state="translated">Спецификатор атрибута не является законченным оператором. Для назначения атрибута следующему оператору используйте символ продолжения строки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoUniqueConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как его базовый класс "{1}" имеет более чем один доступный "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraNextVariable">
<source>'Next' statement names more variables than there are matching 'For' statements.</source>
<target state="translated">'В операторе "Next" указано больше переменных, чем в соответствующих операторах "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCallTooMany2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" из "{1}" имеет более чем один доступный "Sub New", который может быть вызван без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForCtlVarArraySizesSpecified">
<source>Array declared as for loop control variable cannot be declared with an initial size.</source>
<target state="translated">Массив, объявляемый для переменной цикла For, не может объявляться с начальным размером.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNewOverloads">
<source>The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'.</source>
<target state="translated">Ключевое слово "{0}" используется для перегрузки наследуемых членов. Не используйте ключевое слово "{0}" при перегрузке "Sub New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnGenericParam">
<source>Type character cannot be used in a type parameter declaration.</source>
<target state="translated">Символ типа нельзя использовать в объявлении параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments1">
<source>Too few type arguments to '{0}'.</source>
<target state="translated">Слишком мало аргументов типа в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments1">
<source>Too many type arguments to '{0}'.</source>
<target state="translated">Слишком много аргументов типа в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericConstraintNotSatisfied2">
<source>Type argument '{0}' does not inherit from or implement the constraint type '{1}'.</source>
<target state="translated">Аргумент типа "{0}" не наследует или реализует строгий тип "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric1">
<source>'{0}' has no type parameters and so cannot have type arguments.</source>
<target state="translated">"{0}" не имеет параметров типа и поэтому не может иметь аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnGenericParam">
<source>'New' cannot be used on a type parameter that does not have a 'New' constraint.</source>
<target state="translated">'"New" нельзя использовать для параметра-типа, у которого нет ограничения "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleClassConstraints1">
<source>Type parameter '{0}' can only have one constraint that is a class.</source>
<target state="translated">Параметр типа "{0}" может иметь только одно ограничение, которое является классом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstNotClassInterfaceOrTypeParam1">
<source>Type constraint '{0}' must be either a class, interface or type parameter.</source>
<target state="translated">Тип ограничения "{0}" должен быть классом, интерфейсом или параметром типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateTypeParamName1">
<source>Type parameter already declared with name '{0}'.</source>
<target state="translated">Параметр типа уже объявлен с именем "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam2">
<source>Type parameter '{0}' for '{1}' cannot be inferred.</source>
<target state="translated">Невозможно получить параметр типа "{0}" для "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorGenericParam1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'Операнд "Is" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является параметром типа без ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentCopyBackNarrowing3">
<source>Copying the value of 'ByRef' parameter '{0}' back to the matching argument narrows from type '{1}' to type '{2}'.</source>
<target state="translated">Копирование значения параметра "ByRef" "{0}" обратно в соответствующий аргумент сводит тип "{1}" к типу "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingGenericParamWithMember1">
<source>'{0}' has the same name as a type parameter.</source>
<target state="translated">"{0}" имеет такое же имя, как и параметр типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamBase2">
<source>{0} '{1}' cannot inherit from a type parameter.</source>
<target state="translated">{0} "{1}" не может наследовать от параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsGenericParam">
<source>Type parameter not allowed in 'Implements' clause.</source>
<target state="translated">Параметр-тип нельзя использовать в предложении "Implements".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyNullLowerBound">
<source>Array lower bounds can be only '0'.</source>
<target state="translated">Нижняя граница массива должна равняться 0.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassConstraintNotInheritable1">
<source>Type constraint cannot be a 'NotInheritable' class.</source>
<target state="translated">Ограничение типа не может быть классом, объявленным как "NotInheritable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintIsRestrictedType1">
<source>'{0}' cannot be used as a type constraint.</source>
<target state="translated">"{0}" нельзя использовать как ограничение типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamsOnInvalidMember">
<source>Type parameters cannot be specified on this declaration.</source>
<target state="translated">Параметры типа нельзя указать в этом объявлении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericArgsOnAttributeSpecifier">
<source>Type arguments are not valid because attributes cannot be generic.</source>
<target state="translated">Недопустимые аргументы типа, поскольку атрибуты не могут быть универсального типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrCannotBeGenerics">
<source>Type parameters, generic types or types contained in generic types cannot be used as attributes.</source>
<target state="translated">Параметры-типы, универсальные типы и типы, содержащиеся внутри универсальных типов, нельзя использовать в качестве атрибутов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInGenericMethod">
<source>Local variables within generic methods cannot be declared 'Static'.</source>
<target state="translated">Локальные переменные в универсальных методах не могут объявляться как "Static".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntMemberShadowsGenericParam3">
<source>{0} '{1}' implicitly defines a member '{2}' which has the same name as a type parameter.</source>
<target state="translated">{0} "{1}" неявно определяет член "{2}", который имеет то же имя в качестве параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintAlreadyExists1">
<source>Constraint type '{0}' already specified for this type parameter.</source>
<target state="translated">Тип ограничения "{0}" уже указан для этого параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfacePossiblyImplTwice2">
<source>Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку это может вызвать конфликт с реализацией другого существующего интерфейса "{1}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModulesCannotBeGeneric">
<source>Modules cannot be generic.</source>
<target state="translated">Модули не могут быть общими.</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericClassCannotInheritAttr">
<source>Classes that are generic or contained in a generic type cannot inherit from an attribute class.</source>
<target state="translated">Универсальные классы и классы, содержащиеся в универсальном типе, не могут наследовать от класса атрибута.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DeclaresCantBeInGeneric">
<source>'Declare' statements are not allowed in generic types or types contained in generic types.</source>
<target state="translated">'Операторы "Declare" нельзя использовать в универсальных типах или типах, содержащихся в универсальных типах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithConstraintMismatch2">
<source>'{0}' cannot override '{1}' because they differ by type parameter constraints.</source>
<target state="translated">"{0}" не может переопределить "{1}", так как они отличаются по ограничениям параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsWithConstraintMismatch3">
<source>'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints.</source>
<target state="translated">"{0}" не может реализовать "{1}.{2}", поскольку они отличаются ограничениями параметра типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OpenTypeDisallowed">
<source>Type parameters or types constructed with type parameters are not allowed in attribute arguments.</source>
<target state="translated">Параметры-типы или типы, содержащие параметры-типы, нельзя использовать в аргументах атрибутов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesInvalidOnGenericMethod">
<source>Generic methods cannot use 'Handles' clause.</source>
<target state="translated">В универсальных методах нельзя использовать предложение "Handles".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleNewConstraints">
<source>'New' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'Ограничение "New" нельзя указывать несколько раз для одного параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritForNewConstraint2">
<source>Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" объявлен как "MustInherit" и не удовлетворяет ограничению "New", накладываемому на параметр типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableNewForNewConstraint2">
<source>Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" должен иметь конструктор открытого экземпляра без параметров для удовлетворения ограничения "New" для параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGenericParamForNewConstraint2">
<source>Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">Параметр типа "{0}" должен иметь либо ограничение "New", либо ограничение "Structure" в соответствии с ограничением "New" параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewArgsDisallowedForTypeParam">
<source>Arguments cannot be passed to a 'New' used on a type parameter.</source>
<target state="translated">Аргументы нельзя передать в оператор "New" для параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRawGenericTypeImport1">
<source>Generic type '{0}' cannot be imported more than once.</source>
<target state="translated">Универсальный тип "{0}" нельзя импортировать более одного раза.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypeArgumentCountOverloadCand1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of type arguments.</source>
<target state="translated">Произошел сбой разрешения перегрузки, так как "{0}" принимает такое число аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeArgsUnexpected">
<source>Type arguments unexpected.</source>
<target state="translated">Непредвиденные аргументы типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameSameAsMethodTypeParam1">
<source>'{0}' is already declared as a type parameter of this method.</source>
<target state="translated">"{0}" уже объявлен в качестве параметра типа этого метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamNameFunctionNameCollision">
<source>Type parameter cannot have the same name as its defining function.</source>
<target state="translated">Имя параметра-типа не может совпадать с именем определяющей его функции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstraintSyntax">
<source>Type or 'New' expected.</source>
<target state="translated">Требуется тип или "New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OfExpected">
<source>'Of' required when specifying type arguments for a generic type or method.</source>
<target state="translated">'При задании аргументов-типов для универсального типа или метода, необходимо использовать "Of".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayOfRawGenericInvalid">
<source>'(' unexpected. Arrays of uninstantiated generic types are not allowed.</source>
<target state="translated">'Непредвиденная круглая скобка "(". Массивы не-экземплярных общих типов не допустимы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachAmbiguousIEnumerable1">
<source>'For Each' on type '{0}' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'.</source>
<target state="translated">Оператор "For Each" с типом "{0}" неоднозначен, поскольку этот тип реализует создание множества экземпляров "System.Collections.Generic.IEnumerable(Of T)".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorGenericParam1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'Операнд "IsNot" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является параметром типа без ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamQualifierDisallowed">
<source>Type parameters cannot be used as qualifiers.</source>
<target state="translated">Параметры-типы нельзя использовать в качестве определителей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingCommaOrRParen">
<source>Comma or ')' expected.</source>
<target state="translated">Требуется запятая или ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingAsCommaOrRParen">
<source>'As', comma or ')' expected.</source>
<target state="translated">'Требуется "As", запятая или ")".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleReferenceConstraints">
<source>'Class' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'Ограничение "Class" нельзя указывать несколько раз для одного параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleValueConstraints">
<source>'Structure' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'Ограничение "Structure" нельзя указывать несколько раз для одного параметра-типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewAndValueConstraintsCombined">
<source>'New' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'Ограничения "New" и "Structure" нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndValueConstraintsCombined">
<source>'Class' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'Ограничения Class и Structure нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraint2">
<source>Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" не удовлетворяет ограничению "Structure" для параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForRefConstraint2">
<source>Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'.</source>
<target state="translated">Аргумент типа "{0}" не удовлетворяет ограничению "Class" для параметра типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndClassTypeConstrCombined">
<source>'Class' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'Ограничение "Class" и ограничение c указанием конкретного типа класса нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueAndClassTypeConstrCombined">
<source>'Structure' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'Ограничение "Structure" и ограничение c указанием конкретного типа класса нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectIndirect4">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'.</source>
<target state="translated">Косвенное ограничение "{0}", полученное из ограничения параметра типа "{1}", конфликтует с косвенным ограничением "{2}", полученным из ограничения параметра типа "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashDirectIndirect3">
<source>Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'.</source>
<target state="translated">Ограничение "{0}" конфликтует с косвенным ограничением "{1}", полученным из ограничения параметра типа "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectDirect3">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'.</source>
<target state="translated">Косвенное ограничение "{0}", полученное из ограничения параметра типа "{1}", конфликтует с ограничением "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycleLink2">
<source>
'{0}' is constrained to '{1}'.</source>
<target state="translated">
"{0}' ограничен значением "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycle2">
<source>Type parameter '{0}' cannot be constrained to itself: {1}</source>
<target state="translated">Параметр типа "{0}" не может быть ограничен самим собой: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamWithStructConstAsConst">
<source>Type parameter with a 'Structure' constraint cannot be used as a constraint.</source>
<target state="translated">Параметр-тип с ограничением "Structure" нельзя использовать в качестве ограничения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableDisallowedForStructConstr1">
<source>'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed.</source>
<target state="translated">'"System.Nullable" не удовлетворяет ограничению "Structure" для параметра типа "{0}". Разрешены только типы "Structure", не допускающие значения Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingDirectConstraints3">
<source>Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'.</source>
<target state="translated">Ограничение "{0}" конфликтует с ограничением "{1}", уже указанным для параметра типа "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithInterface2">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку он может совпадать с интерфейсом "{1}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseUnifiesWithInterfaces3">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с интерфейсом "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceBaseUnifiesWithBase4">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the interface '{3}' inherits for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с интерфейсом "{2}", от которого наследуется интерфейс "{3}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithBase3">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' from which the interface '{2}' inherits for some type arguments.</source>
<target state="translated">Невозможно наследовать интерфейс "{0}", поскольку он может совпадать с интерфейсом "{1}", от которого наследуется интерфейс "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsBaseUnifiesWithInterfaces3">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to implemented interface '{2}' for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с реализованным интерфейсом "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceBaseUnifiesWithBase4">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the implemented interface '{3}' inherits for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку интерфейс "{1}", от которого он наследуется, может совпадать с интерфейсом "{2}", от которого наследуется реализованный интерфейс "{3}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceUnifiesWithBase3">
<source>Cannot implement interface '{0}' because it could be identical to interface '{1}' from which the implemented interface '{2}' inherits for some type arguments.</source>
<target state="translated">Невозможно реализовать интерфейс "{0}", поскольку он может совпадать с интерфейсом "{1}", от которого наследуется реализованный интерфейс "{2}" для некоторых аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalsCantBeStructGenericParams">
<source>Generic parameters used as optional parameter types must be class constrained.</source>
<target state="translated">Общие параметры, используемые в качестве необязательных параметров типов, должны иметь ограничения класса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNullableMethod">
<source>Methods of 'System.Nullable(Of T)' cannot be used as operands of the 'AddressOf' operator.</source>
<target state="translated">Методы, принадлежащие "System.Nullable(Of T)", не могут использоваться как операнды для оператора "AddressOf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorNullable1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'Операнд "Is" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является типом, допускающим значение Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorNullable1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'Операнд "IsNot" типа "{0}" можно сравнивать только с "Nothing", поскольку "{0}" является типом, допускающим значение Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingTypeOutsideClass1">
<source>'{0}' cannot be declared 'Shadows' outside of a class, structure, or interface.</source>
<target state="translated">"{0}" невозможно объявить "Shadows" вне области класса, структуры или интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertySetParamCollisionWithValue">
<source>Property parameters cannot have the name 'Value'.</source>
<target state="translated">Параметры свойств не могут иметь имя "Value".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SxSIndirectRefHigherThanDirectRef3">
<source>The project currently contains references to more than one version of '{0}', a direct reference to version {2} and an indirect reference to version {1}. Change the direct reference to use version {1} (or higher) of {0}.</source>
<target state="translated">В настоящее время проект содержит ссылки на более чем одну версию "{0}", прямую ссылку на версию {2} и косвенную ссылку на версию {1}. Измените прямую ссылку на использование версии {1} (или выше) для {0}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReferenceStrong">
<source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source>
<target state="translated">Импортировано несколько сборок с одинаковыми удостоверениями: "{0}" и "{1}". Удалите одну из повторяющихся ссылок.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReference2">
<source>Project already has a reference to assembly '{0}'. A second reference to '{1}' cannot be added.</source>
<target state="translated">Проект уже содержит ссылку на сборку "{0}". Вторую ссылку на "{1}" добавить нельзя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCallOrIndex">
<source>Illegal call expression or index expression.</source>
<target state="translated">Некорректное выражение call или index.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictDefaultPropertyAttribute">
<source>Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'.</source>
<target state="translated">Свойство по умолчанию конфликтует с "DefaultMemberAttribute", определенным в "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeUuid2">
<source>'{0}' cannot be applied because the format of the GUID '{1}' is not correct.</source>
<target state="translated">"{0}" не может использоваться из-за неверного формата GUID "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassAndReservedAttribute1">
<source>'Microsoft.VisualBasic.ComClassAttribute' and '{0}' cannot both be applied to the same class.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" и "{0}" не могут быть назначены одному классу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass2">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because its container '{1}' is not declared 'Public'.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" нельзя использовать для "{0}", так как контейнер "{1}" не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispIdZero1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property.</source>
<target state="translated">'"System.Runtime.InteropServices.DispIdAttribute" нельзя использовать для "{0}", так как "Microsoft.VisualBasic.ComClassAttribute" резервирует нулевое значение для свойства по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispId1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero.</source>
<target state="translated">'"System.Runtime.InteropServices.DispIdAttribute" нельзя использовать для "{0}", так как "Microsoft.VisualBasic.ComClassAttribute" резервирует значения меньше нуля.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassDuplicateGuids1">
<source>'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on '{0}' cannot have the same value.</source>
<target state="translated">'Значения параметров "InterfaceId" и "EventsId" для "Microsoft.VisualBasic.ComClassAttribute" в "{0}" не могут совпадать.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassCantBeAbstract0">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute не может применяться к классу, объявленному с модификатором MustInherit.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass1">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because it is not declared 'Public'.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" нельзя использовать для "{0}", так как он не объявлен как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnknownOperator">
<source>Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">В объявлении оператора должен использоваться один из следующих операторов: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateConversionCategoryUsed">
<source>'Widening' and 'Narrowing' cannot be combined.</source>
<target state="translated">'"Widening" и "Narrowing" нельзя использовать вместе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorNotOverloadable">
<source>Operator is not overloadable. Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">Оператор не поддерживает перегрузку. В объявлении оператора должен использоваться один из следующих операторов: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHandles">
<source>'Handles' is not valid on operator declarations.</source>
<target state="translated">'Недопустимое использование "Handles" в объявлении оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplements">
<source>'Implements' is not valid on operator declarations.</source>
<target state="translated">'Недопустимое использование "Implements" в объявлении оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorExpected">
<source>'End Operator' expected.</source>
<target state="translated">'Требуется оператор "End Operator".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorNotAtLineStart">
<source>'End Operator' must be the first statement on a line.</source>
<target state="translated">'Оператор "End Operator" должен быть первым выражением в строке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndOperator">
<source>'End Operator' must be preceded by a matching 'Operator'.</source>
<target state="translated">'Оператору "End Operator" должен предшествовать соответствующий оператор "Operator".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitOperatorNotValid">
<source>'Exit Operator' is not valid. Use 'Return' to exit an operator.</source>
<target state="translated">'Недопустимое применение оператора Exit Operator. Используйте "Return", чтобы выйти из оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayIllegal1">
<source>'{0}' parameters cannot be declared 'ParamArray'.</source>
<target state="translated">'"Параметры {0}" не могут быть объявлены "ParamArray".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalIllegal1">
<source>'{0}' parameters cannot be declared 'Optional'.</source>
<target state="translated">"{0}" не могут быть объявлены "Optional".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBePublic">
<source>Operators must be declared 'Public'.</source>
<target state="translated">Операторы необходимо объявить как "Public".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBeShared">
<source>Operators must be declared 'Shared'.</source>
<target state="translated">Операторы необходимо объявить как "Shared".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOperatorFlags1">
<source>Operators cannot be declared '{0}'.</source>
<target state="translated">Операторы не могут быть объявлены "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneParameterRequired1">
<source>Operator '{0}' must have one parameter.</source>
<target state="translated">Оператор "{0}" должен иметь один параметр.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TwoParametersRequired1">
<source>Operator '{0}' must have two parameters.</source>
<target state="translated">Оператор "{0}" должен иметь два параметра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneOrTwoParametersRequired1">
<source>Operator '{0}' must have either one or two parameters.</source>
<target state="translated">Оператор "{0}" должен иметь один или два параметра.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvMustBeWideningOrNarrowing">
<source>Conversion operators must be declared either 'Widening' or 'Narrowing'.</source>
<target state="translated">Операторы преобразования должны быть объявлены как Widening или Narrowing.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorDeclaredInModule">
<source>Operators cannot be declared in modules.</source>
<target state="translated">Операторы нельзя объявлять в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSpecifierOnNonConversion1">
<source>Only conversion operators can be declared '{0}'.</source>
<target state="translated">Только операторы преобразования могут быть объявлены как "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryParamMustBeContainingType1">
<source>Parameter of this unary operator must be of the containing type '{0}'.</source>
<target state="translated">Тип параметра унарного оператора должен быть вмещающим "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryParamMustBeContainingType1">
<source>At least one parameter of this binary operator must be of the containing type '{0}'.</source>
<target state="translated">По крайней мере один из параметров данного бинарного оператора должен иметь вмещающий тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvParamMustBeContainingType1">
<source>Either the parameter type or the return type of this conversion operator must be of the containing type '{0}'.</source>
<target state="translated">Тип параметр или возвращаемый тип данного оператора преобразования должны иметь вмещающий тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresBoolReturnType1">
<source>Operator '{0}' must have a return type of Boolean.</source>
<target state="translated">Оператор "{0}" должен иметь логический возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToSameType">
<source>Conversion operators cannot convert from a type to the same type.</source>
<target state="translated">Операторы преобразования не могут приводить тип к этому же типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToInterfaceType">
<source>Conversion operators cannot convert to an interface type.</source>
<target state="translated">Операторы преобразования не могут приводить к типу интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToBaseType">
<source>Conversion operators cannot convert from a type to its base type.</source>
<target state="translated">Операторы преобразования не могут приводить тип к его базовому типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToDerivedType">
<source>Conversion operators cannot convert from a type to its derived type.</source>
<target state="translated">Операторы преобразования не могут приводить тип к его производному типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToObject">
<source>Conversion operators cannot convert to Object.</source>
<target state="translated">Операторы преобразования не могут приводить к объекту.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromInterfaceType">
<source>Conversion operators cannot convert from an interface type.</source>
<target state="translated">Исходным типом оператора преобразования не может быть тип интерфейса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromBaseType">
<source>Conversion operators cannot convert from a base type.</source>
<target state="translated">Исходным типом оператора преобразования не может быть базовый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromDerivedType">
<source>Conversion operators cannot convert from a derived type.</source>
<target state="translated">Исходным типом оператора преобразования не может быть производный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromObject">
<source>Conversion operators cannot convert from Object.</source>
<target state="translated">Исходным типом оператора преобразования не может быть объект.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MatchingOperatorExpected2">
<source>Matching '{0}' operator is required for '{1}'.</source>
<target state="translated">Соответствующий оператор "{0}" требуется для "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableLogicalOperator3">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression.</source>
<target state="translated">Типы возврата и параметров "{0}" должны быть "{1}" для использования в выражении "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionOperatorRequired3">
<source>Type '{0}' must define operator '{1}' to be used in a '{2}' expression.</source>
<target state="translated">Тип "{0}" должен указывать оператор "{1}" для использования в выражении "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CopyBackTypeMismatch3">
<source>Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'.</source>
<target state="translated">Не удается скопировать значение параметра "ByRef" "{0}" обратно в соответствующий аргумент, поскольку тип "{1}" невозможно преобразовать в тип "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopOperatorRequired2">
<source>Type '{0}' must define operator '{1}' to be used in a 'For' statement.</source>
<target state="translated">Тип "{0}" должен определять оператор "{1}" для использования в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopOperator2">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">Типы возврата и параметров "{0}" должны быть "{1}" для использования в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopRelOperator2">
<source>Parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">Типы параметров "{0}" должны быть "{1}" для использования в операторе "For".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresIntegerParameter1">
<source>Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'.</source>
<target state="translated">Оператор "{0}" должен иметь второй параметр типа "Integer" или "Integer?".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyNullableOnBoth">
<source>Nullable modifier cannot be specified on both a variable and its type.</source>
<target state="translated">Модификатор, допускающий значений NULL, не может быть одновременно применен к переменной и ее типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraintNull">
<source>Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.</source>
<target state="translated">Тип "{0}" должен быть типом значения или аргументом типа, ограниченным "Structure" для использования с "Nullable" или с модификатором "?", допускающим значение Null.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArrayAndNullableOnBoth">
<source>Nullable modifier '?' and array modifiers '(' and ')' cannot be specified on both a variable and its type.</source>
<target state="translated">Модификатор "?", допускающий значения NULL, и модификаторы массива "(" и ")" не могут быть применены к переменной и ее типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyTypeCharacterOnIIF">
<source>Expressions used with an 'If' expression cannot contain type characters.</source>
<target state="translated">Выражения, используемые с выражением "If", не могут содержать символы типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFName">
<source>'If' operands cannot be named arguments.</source>
<target state="translated">'Операндами "If" не могут быть именованные аргументы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion">
<source>Cannot infer a common type for the second and third operands of the 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">Не удается определить общий тип второго и третьего операнда бинарного оператора "If". Один из них должен иметь расширяющее преобразование в другой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCondTypeInIIF">
<source>First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type.</source>
<target state="translated">Первым операндом в бинарном выражении "If" должен быть тип, допускающий значения NULL, или ссылочный тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCallIIF">
<source>'If' operator cannot be used in a 'Call' statement.</source>
<target state="translated">'Оператор "If" не может использоваться в операторе "Call".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyAsNewAndNullable">
<source>Nullable modifier cannot be specified in variable declarations with 'As New'.</source>
<target state="translated">Модификатор, допускающий значения NULL, не может быть задан в объявлениях переменных с "As New".</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion2">
<source>Cannot infer a common type for the first and second operands of the binary 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">Не удается определить общий тип первого и второго операнда бинарного оператора "If". Один из них должен иметь расширяющее преобразование в другой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNullTypeInCCExpression">
<source>Nullable types are not allowed in conditional compilation expressions.</source>
<target state="translated">Типы, допускающие значения NULL, нельзя использовать в выражениях условной компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableImplicit">
<source>Nullable modifier cannot be used with a variable whose implicit type is 'Object'.</source>
<target state="translated">Модификатор, допускающий значения NULL, не может быть использован с переменной, чьим неявным типом является "Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRuntimeHelper">
<source>Requested operation is not available because the runtime library function '{0}' is not defined.</source>
<target state="translated">Запрошенная операция недоступна, поскольку не определена функция библиотеки среды выполнения "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterGlobalNameSpace">
<source>'Global' must be followed by '.' and an identifier.</source>
<target state="translated">'За "Global" должны идти "." и идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalExpectedIdentifier">
<source>'Global' not allowed in this context; identifier expected.</source>
<target state="translated">'"Global" нельзя использовать в данном контексте; требуется идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalInHandles">
<source>'Global' not allowed in handles; local name expected.</source>
<target state="translated">'"Global" нельзя использовать в обработчиках; требуется локальное имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseIfNoMatchingIf">
<source>'ElseIf' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'Оператору "ElseIf" должен предшествовать соответствующий "If" или "ElseIf".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor2">
<source>Attribute constructor has a 'ByRef' parameter of type '{0}'; cannot use constructors with byref parameters to apply the attribute.</source>
<target state="translated">Конструктор атрибута имеет параметр "ByRef" типа "{0}"; для работы с атрибутами нельзя использовать конструкторы с параметрами byref.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndUsingWithoutUsing">
<source>'End Using' must be preceded by a matching 'Using'.</source>
<target state="translated">'Оператору "End Using" должен предшествовать соответствующий ему оператор "Using".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndUsing">
<source>'Using' must end with a matching 'End Using'.</source>
<target state="translated">'Операнд "Using" должен завершаться соответствующим операндом "End Using".</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoUsing">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Using' statement that does not contain this statement.</source>
<target state="translated">'Недопустимый оператор "GoTo {0}", поскольку "{0}" находится в теле оператора "Using", не содержащего данный оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingRequiresDisposePattern">
<source>'Using' operand of type '{0}' must implement 'System.IDisposable'.</source>
<target state="translated">'Операнд "Using" типа "{0}" должен реализовать "System.IDisposable".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarNeedsInitializer">
<source>'Using' resource variable must have an explicit initialization.</source>
<target state="translated">'Для переменной ресурса в "Using" требуется явная инициализация.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarCantBeArray">
<source>'Using' resource variable type can not be array type.</source>
<target state="translated">'Тип переменной ресурса в операторе "Using" не может быть массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInUsing">
<source>'On Error' statements are not valid within 'Using' statements.</source>
<target state="translated">'Операторы "On Error" нельзя использовать в операторе "Using".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyNameConflictInMyCollection">
<source>'{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace.</source>
<target state="translated">"{0}" имеет то же имя, что и член, используемый для типа "{1}" в группе "My". Переименуйте тип или его вложенное пространство имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitVar">
<source>Implicit variable '{0}' is invalid because of '{1}'.</source>
<target state="translated">Неявная переменная "{0}" недопустима из-за "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectInitializerRequiresFieldName">
<source>Object initializers require a field name to initialize.</source>
<target state="translated">Инициализаторы объектов требуют для инициализации имя поля.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedFrom">
<source>'From' expected.</source>
<target state="translated">'Требуется "From".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch1">
<source>Nested function does not have the same signature as delegate '{0}'.</source>
<target state="translated">Вложенная функция не имеет одинаковой подписи с делегатом "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch2">
<source>Nested sub does not have a signature that is compatible with delegate '{0}'.</source>
<target state="translated">Подпись вложенного подчиненного несовместима с делегатом "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamQuery1">
<source>'ByRef' parameter '{0}' cannot be used in a query expression.</source>
<target state="translated">'Параметр "ByRef" "{0}" нельзя использовать в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionTreeNotSupported">
<source>Expression cannot be converted into an expression tree.</source>
<target state="translated">Выражение не может быть преобразовано в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeQuery">
<source>Instance members and 'Me' cannot be used within query expressions in structures.</source>
<target state="translated">Члены экземпляров и "Me" не могут быть использованы в выражениях запроса в структурах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InferringNonArrayType1">
<source>Variable cannot be initialized with non-array type '{0}'.</source>
<target state="translated">Не удается инициализировать переменную с типом "{0}", не являющимся массивом.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefParamInExpressionTree">
<source>References to 'ByRef' parameters cannot be converted to an expression tree.</source>
<target state="translated">Ссылки на параметры "ByRef" не могут быть преобразованы в дерево выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAnonTypeMemberName1">
<source>Anonymous type member or property '{0}' is already declared.</source>
<target state="translated">Анонимный член типа или свойство "{0}" уже объявлены.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAnonymousTypeForExprTree">
<source>Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.</source>
<target state="translated">Не удается преобразовать анонимный тип к дереву выражения, так как свойство типа используется для инициализации другого свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftAnonymousType1">
<source>Anonymous type property '{0}' cannot be used in the definition of a lambda expression within the same initialization list.</source>
<target state="translated">Нельзя использовать свойство анонимного типа "{0}" в определении лямбда-выражения в рамках одного списка инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionOnlyAllowedOnModuleSubOrFunction">
<source>'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations.</source>
<target state="translated">'Атрибут "Extension" можно применять только к объявлениям "Module", "Sub" или "Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNotInModule">
<source>Extension methods can be defined only in modules.</source>
<target state="translated">Методы расширения могут определяться только в модулях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNoParams">
<source>Extension methods must declare at least one parameter. The first parameter specifies which type to extend.</source>
<target state="translated">Методы расширения должны объявлять не менее одного параметра. Первый параметр указывает тип для расширения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOptionalFirstArg">
<source>'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'"Optional" нельзя применять к первому параметру метода расширения. Первый параметр указывает тип для расширения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodParamArrayFirstArg">
<source>'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'"ParamArray" нельзя применять к первому параметру метода расширения. Первый параметр указывает тип для расширения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeFieldNameInference">
<source>Anonymous type member name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">Имя члена анонимного типа может быть определено только из простого или полного имени без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMemberOfAnonymousType2">
<source>'{0}' is not a member of '{1}'; it does not exist in the current context.</source>
<target state="translated">"{0}" не является членом "{1}"; он не существует в текущем контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionAttributeInvalid">
<source>The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods.</source>
<target state="translated">Нестандартная версия атрибута "System.Runtime.CompilerServices.ExtensionAttribute", обнаруженная компилятором, недопустима. Флаги использования ее атрибутов должны быть установлены таким образом, чтобы задействовать сборки, классы и методы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypePropertyOutOfOrder1">
<source>Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established.</source>
<target state="translated">Свойство члена анонимного типа "{0}" нельзя использовать для определения типа другого свойства члена, поскольку тип "{0}" еще не установлен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in anonymous type declarations.</source>
<target state="translated">Символы типа не могут быть использованы в объявлении анонимного типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleLiteralDisallowsTypeChar">
<source>Type characters cannot be used in tuple literals.</source>
<target state="translated">Символы типа невозможно использовать в литералах кортежа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewWithTupleTypeSyntax">
<source>'New' cannot be used with tuple type. Use a tuple literal expression instead.</source>
<target state="translated">'"New" невозможно использовать с типом кортежа. Вместо этого примените литеральное выражение кортежа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct">
<source>Predefined type '{0}' must be a structure.</source>
<target state="translated">Предопределенный тип "{0}" должен быть структурой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodUncallable1">
<source>Extension method '{0}' has type constraints that can never be satisfied.</source>
<target state="translated">Метод расширения "{0}" содержит ограничения типа, которые не могут быть соблюдены.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate3">
<source>
Extension method '{0}' defined in '{1}': {2}</source>
<target state="translated">
Метод расширения "{0}" определен в "{1}": {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatch">
<source>Method does not have a signature compatible with the delegate.</source>
<target state="translated">Метод не имеет сигнатуры, совместимой с сигнатурой делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingTypeInferenceFails">
<source>Type arguments could not be inferred from the delegate.</source>
<target state="translated">Аргументы-типы не могут быть определены из делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs">
<source>Too many arguments.</source>
<target state="translated">Слишком много аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted1">
<source>Parameter '{0}' already has a matching omitted argument.</source>
<target state="translated">Параметр "{0}" уже имеет соответствующий пропущенный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice1">
<source>Parameter '{0}' already has a matching argument.</source>
<target state="translated">Параметр "{0}" уже имеет соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound1">
<source>'{0}' is not a method parameter.</source>
<target state="translated">"{0}" не является параметром метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument1">
<source>Argument not specified for parameter '{0}'.</source>
<target state="translated">Аргумент, не указанный для параметра "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam1">
<source>Type parameter '{0}' cannot be inferred.</source>
<target state="translated">Невозможно получить параметр типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate2">
<source>
Extension method '{0}' defined in '{1}'.</source>
<target state="translated">
Метод расширения "{0}" определен в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNeedField">
<source>Anonymous type must contain at least one member.</source>
<target state="translated">Анонимный тип должен содержать по крайней мере один член.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNameWithoutPeriod">
<source>Anonymous type member name must be preceded by a period.</source>
<target state="translated">Имени члена анонимного типа должна предшествовать точка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeExpectedIdentifier">
<source>Identifier expected, preceded with a period.</source>
<target state="translated">Требуется идентификатор, перед которым должна стоять точка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs2">
<source>Too many arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">Слишком много аргументов в методе расширения "{0}", определенном в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted3">
<source>Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument.</source>
<target state="translated">Параметр "{0}" метода расширения "{1}", заданного в "{2}", уже имеет соответствующий пропущенный аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice3">
<source>Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument.</source>
<target state="translated">Параметр "{0}" метода расширения "{1}", заданного в "{2}", уже имеет соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound3">
<source>'{0}' is not a parameter of extension method '{1}' defined in '{2}'.</source>
<target state="translated">"{0}" не является параметром метода расширения "{1}", определенного в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument3">
<source>Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'.</source>
<target state="translated">Аргумент, не указанный для параметра "{0}" метода расширения "{1}", определен в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam3">
<source>Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred.</source>
<target state="translated">Невозможно получить параметр типа "{0}" для метода расширения "{1}", определенного в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments2">
<source>Too few type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">Слишком мало аргументов типа в методе расширения "{0}", определенном в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments2">
<source>Too many type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">Слишком много аргументов типа в методе расширения "{0}", определенного в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInOrEq">
<source>'In' or '=' expected.</source>
<target state="translated">'Требуется "In" или "=".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQueryableSource">
<source>Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.</source>
<target state="translated">Выражение типа "{0}" недоступно для запроса. Убедитесь, что не пропущена ссылка на сборку и (или) импорт пространства имен для поставщика LINQ.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryOperatorNotFound">
<source>Definition of method '{0}' is not accessible in this context.</source>
<target state="translated">Определение метода "{0}" недоступно в этом контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseOnErrorGotoWithClosure">
<source>Method cannot contain both a '{0}' statement and a definition of a variable that is used in a lambda or query expression.</source>
<target state="translated">Метод не может одновременно содержать оператор "{0}" и определение переменной, которая используется в лямбда-выражении или выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotGotoNonScopeBlocksWithClosure">
<source>'{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression.</source>
<target state="translated">"{0}{1}" является недопустимым, поскольку "{2}" находится внутри области, которая определяет переменную, используемую в лямбда-выражении или выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeQuery">
<source>Instance of restricted type '{0}' cannot be used in a query expression.</source>
<target state="translated">Экземпляр ограниченного типа "{0}" нельзя использовать в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeFieldNameInference">
<source>Range variable name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">Имя переменной диапазона может выводиться только из простого или проверенного имени без аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryDuplicateAnonTypeMemberName1">
<source>Range variable '{0}' is already declared.</source>
<target state="translated">Переменная диапазона "{0}" уже объявлена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in range variable declarations.</source>
<target state="translated">Не удается использовать символы типа в объявлениях переменной диапазона.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyInClosure">
<source>'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.</source>
<target state="translated">'Доступной только для чтения переменной (ReadOnly) нельзя присваивать значение в лямбда-выражении внутри конструктора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoMultiDimArrayCreation">
<source>Multi-dimensional array cannot be converted to an expression tree.</source>
<target state="translated">Многомерный массив не может быть преобразован в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoLateBind">
<source>Late binding operations cannot be converted to an expression tree.</source>
<target state="translated">Операции позднего связывания не могут быть преобразованы в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedBy">
<source>'By' expected.</source>
<target state="translated">'Требуется "By".</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryInvalidControlVariableName1">
<source>Range variable name cannot match the name of a member of the 'Object' class.</source>
<target state="translated">Имя переменной диапазона не может совпадать с именем члена класса "Object".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIn">
<source>'In' expected.</source>
<target state="translated">'Требуется "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryNameNotDeclared">
<source>Name '{0}' is either not declared or not in the current scope.</source>
<target state="translated">Имя "{0}" не объявлено или не существует в текущей области.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedFunctionArgumentNarrowing3">
<source>Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">Возвращаемый тип вложенной функции соответствующего параметра "{0}" сужается с "{1}" к "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonTypeFieldXMLNameInference">
<source>Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">Имя члена анонимного типа не может быть определено из идентификатора XML, который не является допустимым идентификатором языка Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonTypeFieldXMLNameInference">
<source>Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">Имя переменной диапазона не может быть определено из идентификатора XML, который не является допустимым идентификатором Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInto">
<source>'Into' expected.</source>
<target state="translated">'Требуется "Into".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnAggregation">
<source>Aggregate function name cannot be used with a type character.</source>
<target state="translated">Имя агрегатной функции не может использоваться вместе с символом типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOn">
<source>'On' expected.</source>
<target state="translated">'Требуется "On".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEquals">
<source>'Equals' expected.</source>
<target state="translated">'Требуется "Equals".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAnd">
<source>'And' expected.</source>
<target state="translated">'Требуется "And".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsTypeMismatch">
<source>'Equals' cannot compare a value of type '{0}' with a value of type '{1}'.</source>
<target state="translated">'"Equals" не может сравнить значение типа "{0}" со значением типа "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsOperandIsBad">
<source>You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) {0} must appear on one side of the 'Equals' operator, and range variable(s) {1} must appear on the other.</source>
<target state="translated">С обеих сторон оператора "Equals" должны присутствовать ссылки хотя бы на одну переменную диапазона. Переменные диапазона {0} должны располагаться с одной стороны оператора "Equals", а переменные диапазона {1} — с другой.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotDelegate1">
<source>Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">Лямбда-выражение не может быть преобразовано в "{0}", поскольку "{0}" не является типом делегата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotCreatableDelegate1">
<source>Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">Лямбда-выражение не может быть преобразовано в "{0}", поскольку тип "{0}" объявлен как "MustInherit" и не может быть создан.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotInferNullableForVariable1">
<source>A nullable type cannot be inferred for variable '{0}'.</source>
<target state="translated">Тип, допускающий значение Null, не может быть определен для переменной "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableTypeInferenceNotSupported">
<source>Nullable type inference is not supported in this context.</source>
<target state="translated">Определение типа, допускающего значения NULL, не поддерживается в текущем контексте.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedJoin">
<source>'Join' expected.</source>
<target state="translated">'Требуется "Join".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableParameterMustSpecifyType">
<source>Nullable parameters must specify a type.</source>
<target state="translated">Параметры, допускающие значения NULL, должны задавать тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal2">
<source>Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">Переменная диапазона "{0}" скрывает переменную во внешнем блоке, ранее определенную переменную диапазона или неявно объявленную переменную в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdasCannotHaveAttributes">
<source>Attributes cannot be applied to parameters of lambda expressions.</source>
<target state="translated">Атрибуты не могут быть применены к параметрам лямбда-выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaInSelectCaseExpr">
<source>Lambda expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">Лямбда-выражения являются недопустимыми в первом выражении инструкции "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfInSelectCaseExpr">
<source>'AddressOf' expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">'Выражения "AddressOf" недопустимы в первом выражении оператора "Select Case".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableCharNotSupported">
<source>The '?' character cannot be used here.</source>
<target state="translated">Символ "?" нельзя употреблять здесь.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeLambda">
<source>Instance members and 'Me' cannot be used within a lambda expression in structures.</source>
<target state="translated">Члены экземпляров и "Me" не могут быть использованы внутри лямбда-выражений в структурах.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamLambda1">
<source>'ByRef' parameter '{0}' cannot be used in a lambda expression.</source>
<target state="translated">'Параметр "ByRef" "{0}" нельзя использовать в лямбда-выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeLambda">
<source>Instance of restricted type '{0}' cannot be used in a lambda expression.</source>
<target state="translated">Экземпляр ограниченного типа "{0}" нельзя использовать в лямбда-выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaParamShadowLocal1">
<source>Lambda parameter '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">Лямбда-параметр "{0}" скрывает переменную во внешнем блоке, ранее определенную переменную диапазона или неявно объявленную переменную в выражении запроса.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObjectLambda">
<source>Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.</source>
<target state="translated">Параметр "Strict On" требует, чтобы все лямбда-выражения были объявлены с использованием предложения "As" в случае, если тип не может быть определен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyParamsOnLambdaParamNoType">
<source>Array modifiers cannot be specified on lambda expression parameter name. They must be specified on its type.</source>
<target state="translated">Модификаторы массива не могут указываться в имени параметра лямбда-выражения. Они должны задаваться по его типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов, так как возможны несколько типов. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, так как возможен более чем один тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов, так как возможен более чем один тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">Типы данных параметров-типов не могут быть определены из этих аргументов, так как возможны несколько типов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, так как возможен более чем один тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в "{1}", не могут быть получены из этих аргументов, так как возможен более чем один тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типов не могут быть определены из этих аргументов, так как они не могут быть приведены к одному типу. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в {1}", не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип. Явное указание типов данных может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">Типы данных параметров типов не могут быть определены из этих аргументов, так как они не могут быть приведены к одному типу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">Типы данных параметров типа в методе "{0}" не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">Типы данных параметров типа в методе расширения "{0}", которые определены в {1}", не могут быть получены из этих аргументов, потому что они не преобразованы в тот же тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff2">
<source>Option Strict On does not allow narrowing in implicit type conversions between method '{0}' and delegate '{1}'.</source>
<target state="translated">Параметр Strict On не разрешает сужение в преобразованиях явного типа между методом '{0}' и делегатом '{1}'.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleReturnTypeOfMember2">
<source>'{0}' is not accessible in this context because the return type is not accessible.</source>
<target state="translated">"{0}" в этом контексте недоступен, так как недоступен возвращаемый тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifierOrGroup">
<source>'Group' or an identifier expected.</source>
<target state="translated">'Требуется "Group" или идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedGroup">
<source>'Group' not allowed in this context; identifier expected.</source>
<target state="translated">'В данном контексте "Group" не разрешено; ожидался идентификатор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff3">
<source>Option Strict On does not allow narrowing in implicit type conversions between extension method '{0}' defined in '{2}' and delegate '{1}'.</source>
<target state="translated">Параметр Strict On не разрешает сужение в преобразованиях явного типа между методом расширения "{0}", определенным в "{2}", и делегатом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible3">
<source>Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">Метод расширения "{0}", определенный в "{2}", не имеет сигнатуры, совместимой с делегатом "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing2">
<source>Argument matching parameter '{0}' narrows to '{1}'.</source>
<target state="translated">Аргумент, соответствующий параметру "{0}", сужен до "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate1">
<source>
{0}</source>
<target state="translated">
{0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyInitializedInStructure">
<source>Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.</source>
<target state="translated">Автоматически реализуемые свойства, содержащиеся в Структурах не могут иметь инициализатор, кроме случаев, когда они помечены как "Общие".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsElements">
<source>XML elements cannot be selected from type '{0}'.</source>
<target state="translated">Невозможно выбрать элементы XML из типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsAttributes">
<source>XML attributes cannot be selected from type '{0}'.</source>
<target state="translated">Невозможно выбрать атрибуты XML из типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsDescendants">
<source>XML descendant elements cannot be selected from type '{0}'.</source>
<target state="translated">Невозможно выбрать элементы-потомки XML из типа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric2">
<source>Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments.</source>
<target state="translated">Метод расширения "{0}", определенный в "{1}", не является универсальным (или не имеет параметров свободного типа) и поэтому не может иметь аргументов типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodCannotBeLateBound">
<source>Late-bound extension methods are not supported.</source>
<target state="translated">Методы расширения с поздним связыванием не поддерживаются.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceArrayRankMismatch1">
<source>Cannot infer a data type for '{0}' because the array dimensions do not match.</source>
<target state="translated">Невозможно получить тип данных для "{0}", так как размеры массива не совпадают.</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryStrictDisallowImplicitObject">
<source>Type of the range variable cannot be inferred, and late binding is not allowed with Option Strict on. Use an 'As' clause to specify the type.</source>
<target state="translated">Тип переменной диапазона не может быть определен, и с Option Strict On поздняя привязка не допускается. Используйте предложение "As", чтобы указать тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedInterfaceWithGeneric">
<source>Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.</source>
<target state="translated">Тип "{0}" нельзя внедрить, поскольку он имеет универсальный аргумент. Попробуйте отключить внедрение типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseGenericTypeAcrossAssemblyBoundaries">
<source>Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source>
<target state="translated">Тип "{0}" нельзя использовать за границами сборки, так как он имеет аргумент универсального типа, являющийся внедренным типом взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">"{0}" является устаревшим: "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2_Title">
<source>Type or member is obsolete</source>
<target state="translated">Тип или член устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4">
<source>{0} '{1}' shadows an overloadable member declared in the base {2} '{3}'. If you want to overload the base method, this method must be declared 'Overloads'.</source>
<target state="translated">{0} "{1}" затеняет переопределяемый член, объявленный в базе {2} "{3}". Если вы хотите перегрузить базовый метод, этот метод должен быть объявлен "Overloads".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4_Title">
<source>Member shadows an overloadable member declared in the base type</source>
<target state="translated">Член затемняет перегружаемый член, объявленный в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5">
<source>{0} '{1}' conflicts with {2} '{1}' in the base {3} '{4}' and should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" конфликтует с "{2}" в базе {1} "{3}" {4} и должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5_Title">
<source>Member conflicts with member in the base type and should be declared 'Shadows'</source>
<target state="translated">Член конфликтует с членом в базовом типе и должен быть объявлен как Shadows</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2">
<source>{0} '{1}' shadows an overridable method in the base {2} '{3}'. To override the base method, this method must be declared 'Overrides'.</source>
<target state="translated">{0} "{1}" затеняет переопределяемый метод в базе {2} "{3}". Для переопределения базового метода, этот метод должен быть объявлен "Overrides".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2_Title">
<source>Member shadows an overridable method in the base type</source>
<target state="translated">Член затемняет переопределяемый метод в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4">
<source>Default property '{0}' conflicts with the default property '{1}' in the base {2} '{3}'. '{0}' will be the default property. '{0}' should be declared 'Shadows'.</source>
<target state="translated">Свойство по умолчанию "{0}" противоречит свойству по умолчанию "{1}" в базе {2} "{3}". "{0}" будет свойством по умолчанию. "{0}" следует объявить "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4_Title">
<source>Default property conflicts with the default property in the base type</source>
<target state="translated">Свойство по умолчанию конфликтует со свойством по умолчанию в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">"{0}" является устаревшим.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1_Title">
<source>Type or member is obsolete</source>
<target state="translated">Тип или член устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0">
<source>Possible problem detected while building assembly: {0}</source>
<target state="translated">При создании сборки обнаружена потенциальная проблема: {0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">Обнаружена возможная проблема при создании сборки</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1">
<source>Possible problem detected while building assembly '{0}': {1}</source>
<target state="translated">При создании сборки обнаружена потенциальная проблема "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">Обнаружена возможная проблема при создании сборки</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class '{0}' but '{0}' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" указан для класса "{0}", но "{0}" не имеет открытых членов, которые могут быть использованы через COM; поэтому COM-интерфейсы не создаются.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class but class has no public members that can be exposed to COM</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute указан для класса, но класс не содержит открытые члены, которые можно предоставить для COM</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member in the base {3} '{4}', and so the {0} should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", что конфликтует с членом в базе {3} "{4}", поэтому {0} должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5_Title">
<source>Property or event implicitly declares type or member that conflicts with a member in the base type</source>
<target state="translated">Свойство или событие неявно объявляет тип или член, который конфликтует с членом в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in the base {4} '{5}' and should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" конфликтует с членом, который был неявно объявлен для {2} "{3}" в базе {4} "{5}" и должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6_Title">
<source>Member conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">Член конфликтует с членом, неявно объявленным для свойства или события в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member implicitly declared for {3} '{4}' in the base {5} '{6}'. {0} should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" неявно объявляет "{2}", что конфликтует с членом, который был неявно объявлен для {3} "{4}" в базе {5} "{6}". {0} должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7_Title">
<source>Property or event implicitly declares member, which conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">Свойство или событие неявно объявляет член, который конфликтует с членом, неявно объявленным для свойства или события в базовом типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело: '{2}'.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3_Title">
<source>Property accessor is obsolete</source>
<target state="translated">Метод доступа свойства устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">"{0}" средство доступа для "{1}" устарело.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2_Title">
<source>Property accessor is obsolete</source>
<target state="translated">Метод доступа свойства устарел</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1">
<source>Type of member '{0}' is not CLS-compliant.</source>
<target state="translated">Тип члена "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1_Title">
<source>Type of member is not CLS-compliant</source>
<target state="translated">Тип члена несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant.</source>
<target state="translated">"{0}" несовместим с CLS, так как унаследован от "{1}", который несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because it derives from base type that is not CLS-compliant</source>
<target state="translated">Тип несовместим с CLS, так как он наследуется от базового типа, который несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1">
<source>Return type of function '{0}' is not CLS-compliant.</source>
<target state="translated">Тип возвращаемого значения "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1_Title">
<source>Return type of function is not CLS-compliant</source>
<target state="translated">Тип возвращаемого значения функции несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1">
<source>Type of parameter '{0}' is not CLS-compliant.</source>
<target state="translated">Тип параметра "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1_Title">
<source>Type of parameter is not CLS-compliant</source>
<target state="translated">Тип параметра несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant.</source>
<target state="translated">"{0}" несовместим с CLS, так как унаследованный интерфейс "{1}" несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because the interface it inherits from is not CLS-compliant</source>
<target state="translated">Тип несовместим с CLS, так как наследуемый интерфейс несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3">
<source>{0} '{1}' cannot be marked CLS-compliant because its containing type '{2}' is not CLS-compliant.</source>
<target state="translated">{0} "{1}" не может быть помечен как совместимый с CLS, так как тип, который он содержит "{2}", несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3_Title">
<source>Member cannot be marked CLS-compliant because its containing type is not CLS-compliant</source>
<target state="translated">Член невозможно пометить как совместимый с CLS, так как его содержащий тип несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1">
<source>Name '{0}' is not CLS-compliant.</source>
<target state="translated">Тип "{0}" не совместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1_Title">
<source>Name is not CLS-compliant</source>
<target state="translated">Имя несовместимо с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1">
<source>Underlying type '{0}' of Enum is not CLS-compliant.</source>
<target state="translated">Базовый тип "{0}" Enum не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1_Title">
<source>Underlying type of Enum is not CLS-compliant</source>
<target state="translated">Базовый тип перечисления несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1">
<source>Non CLS-compliant '{0}' is not allowed in a CLS-compliant interface.</source>
<target state="translated">Не допускается "{0}", несовместимый с CLS, для интерфейса, совместимого с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1_Title">
<source>Non CLS-compliant member is not allowed in a CLS-compliant interface</source>
<target state="translated">Член, несовместимый с CLS, запрещено использовать в интерфейсе, совместимом с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type '{0}'.</source>
<target state="translated">В типе "{0}", совместимом с CLS, запрещено использовать член MustOverride, несовместимый с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1_Title">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type</source>
<target state="translated">Член MustOverride, несовместимый с CLS, запрещено использовать в типе, совместимом с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2">
<source>'{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types.</source>
<target state="translated">"{0}" несовместим с CLS, так как перегружает "{1}", который отличается от него только массивом типов параметра массива или рангом типов параметра массива.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2_Title">
<source>Method is not CLS-compliant because it overloads method which differs from it only by array of array parameter types or by the rank of the array parameter types</source>
<target state="translated">Метод несовместим с CLS, так как он перегружает метод, который отличается от него только массивом типов параметров массива или рангом типов параметров массива</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1">
<source>Root namespace '{0}' is not CLS-compliant.</source>
<target state="translated">Корневое пространство имен "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1_Title">
<source>Root namespace is not CLS-compliant</source>
<target state="translated">Корневое пространство имен несовместимо с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2">
<source>Name '{0}' in the root namespace '{1}' is not CLS-compliant.</source>
<target state="translated">Имя "{0}" в корневом пространстве имен "{1}" не совместимо с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2_Title">
<source>Part of the root namespace is not CLS-compliant</source>
<target state="translated">Часть корневого пространства имен несовместима с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1">
<source>Generic parameter constraint type '{0}' is not CLS-compliant.</source>
<target state="translated">Универсальный тип параметра ограничения "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1_Title">
<source>Generic parameter constraint type is not CLS-compliant</source>
<target state="translated">Тип ограничения общего параметра несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1">
<source>Type '{0}' is not CLS-compliant.</source>
<target state="translated">Тип "{0}" не совместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1_Title">
<source>Type is not CLS-compliant</source>
<target state="translated">Тип несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1">
<source>Type of optional value for optional parameter '{0}' is not CLS-compliant.</source>
<target state="translated">Тип необязательного значения для необязательного параметра "{0}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1_Title">
<source>Type of optional value for optional parameter is not CLS-compliant</source>
<target state="translated">Тип дополнительного значения для дополнительного параметра несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.</source>
<target state="translated">Атрибут System.CLSCompliantAttribute нельзя применять к свойствам "Get" или "Set".</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet_Title">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'</source>
<target state="translated">Атрибут System.CLSCompliantAttribute невозможно применить к свойствам Get или Set</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6">
<source>{0} '{1}' and partial {2} '{3}' conflict in {4} '{5}', but are being merged because one of them is declared partial.</source>
<target state="translated">{0} "{1}" и частичный {2} "{3}" конфликтуют в {4} "{5}", но объединены, так как один из них объявлен разделяемым.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6_Title">
<source>Type and partial type conflict, but are being merged because one of them is declared partial</source>
<target state="translated">Тип и разделяемый тип конфликтуют, но выполняется их объединение, так как один из них объявлен разделяемым</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1">
<source>Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.</source>
<target state="translated">Параметр типа "{0}" имеет то же имя в качестве параметра типа вмещающего типа. Параметр типа вмещающего типа будет затенен.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1_Title">
<source>Type parameter has the same name as a type parameter of an enclosing type</source>
<target state="translated">Параметр типа имеет то же имя, что и параметр типа, в который он входит</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1">
<source>Could not find standard library '{0}'.</source>
<target state="translated">Не удалось найти стандартную библиотеку "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1_Title">
<source>Could not find standard library</source>
<target state="translated">Не удалось найти стандартную библиотеку</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2">
<source>Delegate type '{0}' of event '{1}' is not CLS-compliant.</source>
<target state="translated">Тип делегата "{0}" события "{1}" не удовлетворяет требованиям CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2_Title">
<source>Delegate type of event is not CLS-compliant</source>
<target state="translated">Тип делегата события несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate.</source>
<target state="translated">Атрибут System.Diagnostics.DebuggerHiddenAttribute не влияет на методы "Get" или "Set", когда применяется к определению свойства. Применяйте атрибут непосредственно к соответствующим методам "Get" и "Set".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties_Title">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition</source>
<target state="translated">Атрибут System.Diagnostics.DebuggerHiddenAttribute не влияет на Get или Set при применении к определению свойств</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange">
<source>Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound.</source>
<target state="translated">Указан недопустимый диапазон для оператора "Case". Убедитесь, что нижняя граница меньше или равна верхней границе.</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange_Title">
<source>Range specified for 'Case' statement is not valid</source>
<target state="translated">Диапазон, указанный для оператора Case, недопустим</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3">
<source>'{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant.</source>
<target state="translated">"{0}" метод для события "{1}" не может быть помечен как совместимый с CLS, потому что тип, который он содержит, "{2}" несовместим с CLS.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3_Title">
<source>AddHandler or RemoveHandler method for event cannot be marked CLS compliant because its containing type is not CLS compliant</source>
<target state="translated">Метод AddHandler или RemoveHandler для события невозможно пометить как совместимый с CLS, так как его содержащий тип несовместим с CLS</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2">
<source>'{0}' in designer-generated type '{1}' should call InitializeComponent method.</source>
<target state="translated">"{0}" в типе, созданном конструктором "{1}", должен вызывать метод InitializeComponent.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2_Title">
<source>Constructor in designer-generated type should call InitializeComponent method</source>
<target state="translated">Конструктор в типе, созданном конструктором, должен вызывать метод InitializeComponent</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3">
<source>Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'.</source>
<target state="translated">Регистр пространства имен "{0}" не соответствует регистру имени пространства имен "{1}" в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3_Title">
<source>Casing of namespace name does not match</source>
<target state="translated">Регистр имен для пространств имен не соответствует требованиям</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1">
<source>Namespace or type specified in the Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">Пространство имен или тип, указанный в Imports "{0}", не содержит открытый член или не может быть найден. Убедитесь, что пространство имен или тип заданы и содержат хотя бы один открытый член. Убедитесь, что импортируемое имя элемента не использует псевдонимы.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1_Title">
<source>Namespace or type specified in Imports statement doesn't contain any public member or cannot be found</source>
<target state="translated">Пространство имен или тип, указанный в операторе Imports, не содержит открытый член, или невозможно найти пространство имен или тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1">
<source>Namespace or type specified in the project-level Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">Пространство имен или тип, указанные в операторе Imports "{0}" проекта, не содержат открытые члены или не могут быть найдены. Убедитесь, что пространство имен или тип определены и содержат хотя бы один открытый член. Убедитесь, что имя импортируемого элемента не имеет псевдонимов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1_Title">
<source>Namespace or type imported at project level doesn't contain any public member or cannot be found</source>
<target state="translated">Пространство имен или тип, импортированный на уровне проекта, не содержит открытый член, или невозможно найти пространство имен или тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2">
<source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly from assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source>
<target state="translated">Была создана ссылка на внедренную сборку взаимодействия "{0}", так как существует косвенная ссылка на эту сборку, созданная сборкой "{1}". Рассмотрите возможность изменения свойства "Внедрять типы взаимодействия" в любой сборке.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2_Title">
<source>A reference was created to embedded interop assembly because of an indirect reference to that assembly</source>
<target state="translated">Была создана ссылка на внедренную сборку взаимодействия из-за непрямой ссылки на эту сборку</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">Класс должен объявлять Sub New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">Класс "{0}" должен объявить "Sub New", так как "{1}" в базовом классе "{2}" помечен как устаревший: "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">Класс должен объявлять Sub New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">Первый оператор Sub New должен быть явным вызовом в MyBase.New или MyClass.New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'</source>
<target state="translated">Первый оператор в "Sub New" должен иметь явный вызов в "MyBase.New" или "MyClass.New", так как "{0}" в базовом классе "{1}" из "{2}" помечен как устаревший: "{3}"</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">Первый оператор Sub New должен быть явным вызовом в MyBase.New или MyClass.New, так как конструктор в базовом классе отмечен как устаревший</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator">
<source>Operator without an 'As' clause; type of Object assumed.</source>
<target state="translated">Оператор без предложения "As"; предполагаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator_Title">
<source>Operator without an 'As' clause</source>
<target state="translated">Оператор без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2">
<source>Type arguments inferred for method '{0}' result in the following warnings :{1}</source>
<target state="translated">Тип аргументов, выведенных для метода "{0}", выдает следующие предупреждения: {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2_Title">
<source>Type arguments inferred for method result in warnings</source>
<target state="translated">Аргументы типов, определяемые для результата метода в предупреждениях</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations.</source>
<target state="translated">Атрибут "Conditional" допустим только в объявлениях "Sub".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction_Title">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations</source>
<target state="translated">Атрибут Conditional допустим только в объявлениях Sub</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute">
<source>Use command-line option '{0}' or appropriate project settings instead of '{1}'.</source>
<target state="translated">Используйте параметр командной строки "{0}" или подходящие параметры проекта вместо "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute_Title">
<source>Use command-line option /keyfile, /keycontainer, or /delaysign instead of AssemblyKeyFileAttribute, AssemblyKeyNameAttribute, or AssemblyDelaySignAttribute</source>
<target state="translated">Используйте параметр командной строки /keyfile, /keycontainer или /delaysign вместо AssemblyKeyFileAttribute, AssemblyKeyNameAttribute или AssemblyDelaySignAttribute</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall">
<source>Statement recursively calls the containing '{0}' for event '{1}'.</source>
<target state="translated">Выражение рекурсивно вызывает содержащийся "{0}" для события "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall_Title">
<source>Statement recursively calls the event's containing AddHandler</source>
<target state="translated">Оператор рекурсивно вызывает содержащий его AddHandler события</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack">
<source>Implicit conversion from '{1}' to '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">Неявное преобразование "{1}" в "{2}" при копировании значения параметра "ByRef" "{0}" обратно в соответствующий аргумент.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack_Title">
<source>Implicit conversion in copying the value of 'ByRef' parameter back to the matching argument</source>
<target state="translated">Неявное преобразование при выполнении обратного копирования значения параметра ByRef в соответствующий аргумент</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2">
<source>{0} '{1}' conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'.</source>
<target state="translated">{0} "{1}" конфликтует с другими членами с тем же именем в иерархии наследования и должен быть объявлен "Shadows".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2_Title">
<source>Method conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'</source>
<target state="translated">Метод конфликтует с другими членами того же имени в иерархии наследования, поэтому должен быть объявлен как Shadows</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall">
<source>Expression recursively calls the containing Operator '{0}'.</source>
<target state="translated">Выражение рекурсивно вызывает содержащийся оператор "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall_Title">
<source>Expression recursively calls the containing Operator</source>
<target state="translated">Выражение рекурсивно вызывает содержащий его оператор</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2">
<source>Implicit conversion from '{0}' to '{1}'.</source>
<target state="translated">Неявное преобразование "{0}" в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2_Title">
<source>Implicit conversion</source>
<target state="translated">Неявное преобразование</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing">
<source>Local variable '{0}' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">Локальная переменная "{0}" доступна только для чтения и ее тип является структурой. Вызов членов или передача ByRef не меняет ее содержания и может привести к непредвиденным результатам. Попробуйте объявить переменную за пределами блока "Using".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type is a structure</source>
<target state="translated">Локальная переменная, объявленная оператором Using, доступна только для чтения и имеет тип структуры</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing">
<source>Local variable '{0}' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">Локальная переменная "{0}" доступна только для чтения. Если ее тип является структурой, вызов членов или передача ByRef не меняет ее содержания и может привести к непредвиденным результатам. Попробуйте объявить переменную за пределами блока "Using".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type may be a structure</source>
<target state="translated">Локальная переменная, объявленная оператором Using, доступна только для чтения и может иметь тип структуры</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1_Title">
<source>Implicit conversion</source>
<target state="translated">Неявное преобразование</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution">
<source>Late bound resolution; runtime errors could occur.</source>
<target state="translated">Позднее разрешение перегруженных объектов; возможна ошибка времени выполнения.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution_Title">
<source>Late bound resolution</source>
<target state="translated">Динамическое разрешение границ</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1">
<source>Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity.</source>
<target state="translated">Операнды типа Object, используемые для оператора "{0}"; используется оператор "Is", чтобы проверить идентификатор объекта.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">В операторе используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2">
<source>Operands of type Object used for operator '{0}'; runtime errors could occur.</source>
<target state="translated">Операнды типа Object, используемые для оператора "{0}"; возможна ошибка выполнения.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">В операторе используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">Объявление переменной без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1_Title">
<source>Function without an 'As' clause</source>
<target state="translated">Функция без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1_Title">
<source>Property without an 'As' clause</source>
<target state="translated">Свойство без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl">
<source>Variable declaration without an 'As' clause; type of Object assumed.</source>
<target state="translated">Переменная объявлена без предложения "As"; предполагаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">Объявление переменной без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction">
<source>Function without an 'As' clause; return type of Object assumed.</source>
<target state="translated">Функция без предложения "As"; предполагаемый возвращаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction_Title">
<source>Function without an 'As' clause</source>
<target state="translated">Функция без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty">
<source>Property without an 'As' clause; type of Object assumed.</source>
<target state="translated">Свойство без предложения "As"; предполагаемый тип — Object.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty_Title">
<source>Property without an 'As' clause</source>
<target state="translated">Свойство без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal">
<source>Unused local variable: '{0}'.</source>
<target state="translated">Неиспользованная локальная переменная: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal_Title">
<source>Unused local variable</source>
<target state="translated">Неиспользуемая локальная переменная</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance">
<source>Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.</source>
<target state="translated">Доступ к общему члену, члену-константе, члену-перечислению или вложенному типу через экземпляр; заданное выражение не будет вычислено.</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance_Title">
<source>Access of shared member, constant member, enum member or nested type through an instance</source>
<target state="translated">Доступ общего члена, члена константы, члена перечисления или вложенного типа с помощью экземпляра</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall">
<source>Expression recursively calls the containing property '{0}'.</source>
<target state="translated">Выражение рекурсивно вызывает содержащееся свойство "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall_Title">
<source>Expression recursively calls the containing property</source>
<target state="translated">Выражение рекурсивно вызывает содержащее его свойство</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch">
<source>'Catch' block never reached, because '{0}' inherits from '{1}'.</source>
<target state="translated">'Невозможно достичь блока Catch, поскольку "{0}" наследуется от "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch_Title">
<source>'Catch' block never reached; exception type's base type handled above in the same Try statement</source>
<target state="translated">'Блок Catch недоступен; базовый тип типа исключения обрабатывается выше в том же операторе Try</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef">
<source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">Переменная "{0}" передается по ссылке, прежде чем ей присваивается значение. Во время выполнения может появиться пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">Переменная передана ссылкой до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch">
<source>'Catch' block never reached; '{0}' handled above in the same Try statement.</source>
<target state="translated">'Невозможно достичь блок "Catch"; "{0}" обрабатывается выше в том же операторе Try.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch_Title">
<source>'Catch' block never reached; exception type handled above in the same Try statement</source>
<target state="translated">'Блок Catch недоступен; обработанный выше тип исключения находится в том же операторе Try</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not">
<source>Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity.</source>
<target state="translated">Операнды типа Object, используемые для оператора "{0}"; используется оператор "IsNot", чтобы проверить идентификатор объекта.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not_Title">
<source>Operands of type Object used for operator <></source>
<target state="translated">В операторе <> используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum">
<source>Bad checksum value, non hex digits or odd number of hex digits.</source>
<target state="translated">Некорректное значение контрольной суммы: не шестнадцатеричный формат или нечетное количество шестнадцатеричных цифр.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum_Title">
<source>Bad checksum value, non hex digits or odd number of hex digits</source>
<target state="translated">Некорректное значение контрольной суммы: не шестнадцатеричный формат или нечетное количество шестнадцатеричных цифр</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum">
<source>File name already declared with a different GUID and checksum value.</source>
<target state="translated">Имя файла уже объявлено с другим GUID и контрольной суммой.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum_Title">
<source>File name already declared with a different GUID and checksum value</source>
<target state="translated">Имя файла уже объявлено с другим GUID и контрольной суммой</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum">
<source>Bad GUID format.</source>
<target state="translated">Недействительный формат GUID.</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum_Title">
<source>Bad GUID format</source>
<target state="translated">Недействительный формат GUID</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur.</source>
<target state="translated">В выражениях для операторов "Select", "Case" используются операнды типа Object; возможна ошибка времени выполнения.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase_Title">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements</source>
<target state="translated">В выражениях для операторов Select и Case используются операнды типа Object</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.</source>
<target state="translated">Это выражение всегда будет иметь результат "Nothing" (из-за распространения значения Null от оператора равенства). Для проверки на значение NULL рекомендуется использовать "Is Nothing".</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">Вычисление этого выражения всегда будет иметь значение Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'.</source>
<target state="translated">Это выражение всегда будет иметь результат "Nothing" (из-за распространения значения Null от оператора равенства). Для проверки на значение NULL рекомендуется использовать "IsNot Nothing".</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">Вычисление этого выражения всегда будет иметь значение Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst">
<source>Unused local constant: '{0}'.</source>
<target state="translated">Неиспользованная локальная константа: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst_Title">
<source>Unused local constant</source>
<target state="translated">Неиспользуемая локальная константа</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class '{0}' implicitly declares {1} '{2}', which conflicts with a member of the same name in {3} '{4}'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base {4}.</source>
<target state="translated">'"Microsoft.VisualBasic.ComClassAttribute" для класса "{0}" неявно объявляет {1} "{2}", что конфликтует с членом, имеющим то же имя в {3} "{4}". Используйте "Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)", если вы хотите скрыть имя в базе{4}.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class implicitly declares member, which conflicts with a member of the same name</source>
<target state="translated">'Атрибут Microsoft.VisualBasic.ComClassAttribute в классе неявно объявляет член, который конфликтует с членом, обладающим тем же именем</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1">
<source>'{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.</source>
<target state="translated">'Для "{0}" невозможно использование через COM как свойство "Let". Вы не сможете присвоить значения, не являющиеся объектом (например, числа или строки), с помощью оператора "Let" для этого свойства с версии Visual Basic 6.0.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1_Title">
<source>Property cannot be exposed to COM as a property 'Let'</source>
<target state="translated">Невозможно предоставить свойство для COM как свойство Let</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef">
<source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">Используется переменная "{0}", прежде чем ей было присвоено значение. Во время выполнения может появиться пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">Переменная используется до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1">
<source>Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">Функция "{0}" не возвращает значение для всех путей к коду. Во время выполнения при использовании результата может возникнуть пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">Функция не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1">
<source>Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">Оператор "{0}" не возвращает значение для всех путей к коду. Во время выполнения при использовании результата может возникнуть пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">Оператор не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1">
<source>Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">Свойство "{0}" не возвращает значение для всех путей к коду. Во время выполнения при использовании результата может возникнуть пустая ссылка на исключение.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">Свойство не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr">
<source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source>
<target state="translated">Переменная "{0}" передается по ссылке, прежде чем ей присваивается значение. Во время выполнения может появиться пустая ссылка на исключение. Убедитесь, что перед использованием инициализирована структура или все ссылочные члены</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">Переменная передана ссылкой до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr">
<source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use</source>
<target state="translated">Используется переменная "{0}", прежде чем ей было присвоено значение. Во время выполнения может появиться пустая ссылка на исключение. Убедитесь, что перед использованием инициализирована структура или все ссылочные члены</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">Переменная используется до того, как ей было назначено значение</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference">
<source>Static variable declared without an 'As' clause; type of Object assumed.</source>
<target state="translated">Статическая переменная объявлена без предложения "As"; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference_Title">
<source>Static variable declared without an 'As' clause</source>
<target state="translated">Статическая переменная, объявленная без предложения As</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName">
<source>Assembly reference '{0}' is invalid and cannot be resolved.</source>
<target state="translated">Ссылка сборки "{0}" является недопустимой и не может быть разрешена.</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName_Title">
<source>Assembly reference is invalid and cannot be resolved</source>
<target state="translated">Ссылка на сборку недопустима и не может быть разрешена</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine">
<source>XML comment block must immediately precede the language element to which it applies. XML comment will be ignored.</source>
<target state="translated">Непосредственно перед блоком комментариев XML должен находиться элемент языка, к которому он применяется. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine_Title">
<source>XML comment block must immediately precede the language element to which it applies</source>
<target state="translated">Блок комментариев XML должен находиться непосредственно перед элементом языка, к которому он применяется</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock">
<source>Only one XML comment block is allowed per language element.</source>
<target state="translated">Только один блок комментариев XML допускается для каждого элемента языка.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock_Title">
<source>Only one XML comment block is allowed per language element</source>
<target state="translated">Только один блок комментариев XML допускается для каждого элемента языка</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine">
<source>XML comment must be the first statement on a line. XML comment will be ignored.</source>
<target state="translated">Комментарий XML должен быть первым оператором строки. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine_Title">
<source>XML comment must be the first statement on a line</source>
<target state="translated">Комментарий XML должен быть первым оператором в строке</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod">
<source>XML comment cannot appear within a method or a property. XML comment will be ignored.</source>
<target state="translated">Комментарий XML не может находиться внутри метода или свойства. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod_Title">
<source>XML comment cannot appear within a method or a property</source>
<target state="translated">Комментарий XML не должен содержаться в методе или свойстве</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1">
<source>XML documentation parse error: {0} XML comment will be ignored.</source>
<target state="translated">Ошибка синтаксического анализа документации XML: Комментарий XML {0} будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1_Title">
<source>XML documentation parse error</source>
<target state="translated">Ошибка анализа документации XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1">
<source>XML comment tag '{0}' appears with identical attributes more than once in the same XML comment block.</source>
<target state="translated">Тег "{0}" комментария XML с одинаковыми атрибутами более одного раза появляется в том же блоке комментариев XML.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1_Title">
<source>XML comment tag appears with identical attributes more than once in the same XML comment block</source>
<target state="translated">Тег комментария XML с идентичными атрибутами встречается больше одного раза в одном блоке комментариев XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2">
<source>XML comment tag '{0}' is not permitted on a '{1}' language element.</source>
<target state="translated">Тег комментария XML "{0}" недопустим для элемента языка "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2_Title">
<source>XML comment tag is not permitted on language element</source>
<target state="translated">Тег комментария XML запрещен в элементе языка</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2">
<source>XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement.</source>
<target state="translated">Параметр комментария XML "{0}" не соответствует параметру соответствующего оператора "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2_Title">
<source>XML comment parameter does not match a parameter on the corresponding declaration statement</source>
<target state="translated">Параметр комментария XML не совпадает с параметром в соответствующем операторе объявления</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName">
<source>XML comment parameter must have a 'name' attribute.</source>
<target state="translated">Параметр комментария XML должен содержать атрибут "name".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName_Title">
<source>XML comment parameter must have a 'name' attribute</source>
<target state="translated">Параметр комментария XML должен содержать атрибут name</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1">
<source>XML comment has a tag with a 'cref' attribute '{0}' that could not be resolved.</source>
<target state="translated">Комментарий XML содержит тег с атрибутом "cref" "{0}", который не удается разрешить.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1_Title">
<source>XML comment has a tag with a 'cref' attribute that could not be resolved</source>
<target state="translated">Комментарий XML содержит тег с атрибутом cref, который не удалось разрешить</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1">
<source>XML comment tag 'include' must have a '{0}' attribute. XML comment will be ignored.</source>
<target state="translated">Тег комментария XML "include" должен содержать атрибут "{0}". Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1_Title">
<source>XML comment tag 'include' must have 'file' and 'path' attributes</source>
<target state="translated">Тег комментария XML "include" должен иметь атрибуты file и path</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2">
<source>Unable to create XML documentation file '{0}': {1}</source>
<target state="translated">Не удается создать файл XML-документации "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2_Title">
<source>Unable to create XML documentation file</source>
<target state="translated">Не удалось создать XML-файл документации</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement">
<source>XML documentation comments must precede member or type declarations.</source>
<target state="translated">Комментарии XML-документации должны предшествовать объявлениям членов или типов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement_Title">
<source>XML documentation comments must precede member or type declarations</source>
<target state="translated">Комментарии XML-документации должны предшествовать объявлениям членов или типов</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.</source>
<target state="translated">Тег комментария XML "returns" недопустим для свойства "WriteOnly".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty_Title">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property</source>
<target state="translated">Тег комментария XML "returns" недопустим для свойства WriteOnly</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType">
<source>XML comment cannot be applied more than once on a partial {0}. XML comments for this {0} will be ignored.</source>
<target state="translated">Комментарий XML не может быть применен более одного раза для частичного значения {0}. Комментарий XML для {0} будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType_Title">
<source>XML comment cannot be applied more than once on a partial type</source>
<target state="translated">Комментарий XML не может применяться больше одного раза в разделенном типе</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element.</source>
<target state="translated">Тег комментария XML "returns" недопустим для элемента языка "declare sub".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub_Title">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element</source>
<target state="translated">Тег комментария XML "returns" недопустим для элемента языка declare sub</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag">
<source>XML documentation parse error: Start tag '{0}' doesn't have a matching end tag. XML comment will be ignored.</source>
<target state="translated">Ошибка синтаксического анализа документации XML: Начальный тег "{0}" не имеет соответствующего конечного тега. Комментарий XML будет игнорироваться.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag_Title">
<source>XML documentation parse error: Start tag doesn't have a matching end tag</source>
<target state="translated">Ошибка анализа документации XML: открывающий тег не имеет соответствущего закрывающего тега</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2">
<source>XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement.</source>
<target state="translated">Параметр типа комментария XML "{0}" не соответствует параметру соответствующего оператора "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2_Title">
<source>XML comment type parameter does not match a type parameter on the corresponding declaration statement</source>
<target state="translated">Параметр типа комментария XML не совпадает с параметром типа в соответствующем операторе объявления</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName">
<source>XML comment type parameter must have a 'name' attribute.</source>
<target state="translated">Параметр типа комментария XML должен содержать атрибут "name".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName_Title">
<source>XML comment type parameter must have a 'name' attribute</source>
<target state="translated">Параметр типа комментария XML должен содержать атрибут name</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef">
<source>XML comment exception must have a 'cref' attribute.</source>
<target state="translated">Исключение для комментария XML должно содержать атрибут "cref".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef_Title">
<source>XML comment exception must have a 'cref' attribute</source>
<target state="translated">Исключение для комментария XML должно содержать атрибут cref</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment">
<source>Unable to include XML fragment '{0}' of file '{1}'.</source>
<target state="translated">Не удалось включить фрагмент XML "{0}" файла "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment_Title">
<source>Unable to include XML fragment</source>
<target state="translated">Не удалось включить фрагмент XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML">
<source>Unable to include XML fragment '{1}' of file '{0}'. {2}</source>
<target state="translated">Не удалось включить фрагмент XML "{1}" файла "{0}". {2}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML_Title">
<source>Unable to include XML fragment</source>
<target state="translated">Не удалось включить фрагмент XML</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2">
<source>Runtime errors might occur when converting '{0}' to '{1}'.</source>
<target state="translated">Ошибки выполнения могут произойти при преобразовании "{0}" в "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2_Title">
<source>Runtime errors might occur when converting to or from interface type</source>
<target state="translated">Ошибки среды выполнения могут происходить при преобразовании в тип или из типа интерфейса</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda">
<source>Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">Использование переменной цикла в лямбда-выражении может привести к непредвиденным результатам. Вместо этого можно создать локальную переменную внутри цикла и присвоить ей значение переменной цикла.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda_Title">
<source>Using the iteration variable in a lambda expression may have unexpected results</source>
<target state="translated">Использование переменной итерации в лямбда-выражении может привести к непредусмотренным результатам</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler">
<source>Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.</source>
<target state="translated">Лямбда-выражение не будет удалено из обработчика этого события. Присвойте переменной лямбда-выражение и используйте переменную, чтобы добавить или удалить событие.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler_Title">
<source>Lambda expression will not be removed from this event handler</source>
<target state="translated">Лямбда-выражение не будет удалено из этого обработчика событий</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery">
<source>Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">Использование переменной цикла в выражении запроса может привести к непредвиденным результатам. Вместо этого можно создать локальную переменную внутри цикла и присвоить ей значение переменной цикла.</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery_Title">
<source>Using the iteration variable in a query expression may have unexpected results</source>
<target state="translated">Использование переменной итерации в выражении запроса может привести к непредусмотренным результатам</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler.</source>
<target state="translated">Выражение "AddressOf" не работает в этом контексте, так как аргумент метода "AddressOf" требует преобразование в тип делегата события. Можно присвоить выражение "AddressOf" переменной и использовать ее для добавления и удаления события.</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler_Title">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event</source>
<target state="translated">Выражение AddressOf не оказывает влияния в этом контексте, так как аргумент метода для AddressOf требует неявного преобразования в тип делегата события</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl">
<source>Range variable is assumed to be of type Object because its type cannot be inferred. Use an 'As' clause to specify a different type.</source>
<target state="translated">Предполагается, что переменная диапазона является типом Object, так как этот тип не может быть определен. Используйте предложение "As", чтобы указать другой тип.</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl_Title">
<source>Range variable is assumed to be of type Object because its type cannot be inferred</source>
<target state="translated">Предполагается, что переменная диапазона имеет тип Object, так как ее тип невозможно определить</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingFunction">
<source>Multiline lambda expression is missing 'End Function'.</source>
<target state="translated">В многострочном лямбда-выражении отсутствует "End Function".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingSub">
<source>Multiline lambda expression is missing 'End Sub'.</source>
<target state="translated">В многострочном лямбда-выражении отсутствует "End Sub".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOnLambdaReturnType">
<source>Attributes cannot be applied to return types of lambda expressions.</source>
<target state="translated">Не удается применить атрибуты к возвращаемым типам лямбда-выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubDisallowsStatement">
<source>Statement is not valid inside a single-line statement lambda.</source>
<target state="translated">Недопустимый оператор в лямбде однострочного оператора.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesBang">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>)!key</source>
<target state="translated">Эту лямбду однострочного оператора необходимо заключить в круглые скобки. Например: (Sub() <оператор>)!key</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesDot">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>).Invoke()</source>
<target state="translated">Эту лямбду однострочного оператора необходимо заключить в круглые скобки. Например: (Sub() <оператор>).Invoke()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesLParen">
<source>This single-line statement lambda must be enclosed in parentheses. For example: Call (Sub() <statement>) ()</source>
<target state="translated">Эту лямбду однострочного оператора необходимо заключить в круглые скобки. Например: Call (Sub() <оператор>) ()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresSingleStatement">
<source>Single-line statement lambdas must include exactly one statement.</source>
<target state="translated">В лямбдах однострочного оператора может содержаться только один оператор.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StaticInLambda">
<source>Static local variables cannot be declared inside lambda expressions.</source>
<target state="translated">Статические локальные переменные нельзя задавать в лямбда-выражениях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializedExpandedProperty">
<source>Expanded Properties cannot be initialized.</source>
<target state="translated">Невозможно инициировать расширенные свойства.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantHaveParams">
<source>Auto-implemented properties cannot have parameters.</source>
<target state="translated">Автоматически реализованные свойства не могут иметь параметры.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantBeWriteOnly">
<source>Auto-implemented properties cannot be WriteOnly.</source>
<target state="translated">Автоматически реализуемые свойства не могут иметь значение WriteOnly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFCount">
<source>'If' operator requires either two or three operands.</source>
<target state="translated">'Оператор "If" должен содержать два или три операнда.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotACollection1">
<source>Cannot initialize the type '{0}' with a collection initializer because it is not a collection type.</source>
<target state="translated">Невозможно инициализировать тип "{0}" с инициализатором набора, так как он не является типом коллекции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAddMethod1">
<source>Cannot initialize the type '{0}' with a collection initializer because it does not have an accessible 'Add' method.</source>
<target state="translated">Невозможно инициализировать тип "{0}" с инициализатором набора, так как он не имеет доступного метода "Add".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCombineInitializers">
<source>An Object Initializer and a Collection Initializer cannot be combined in the same initialization.</source>
<target state="translated">Инициализатор объектов и инициализатор коллекций не могут объединяться в одной инициализации.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmptyAggregateInitializer">
<source>An aggregate collection initializer entry must contain at least one element.</source>
<target state="translated">Запись агрегатного инициализатора коллекции должна содержать по меньшей мере один элемент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndElementNoMatchingStart">
<source>XML end element must be preceded by a matching start element.</source>
<target state="translated">Перед конечным XML-элементом должен идти соответствующий начальный элемент.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdasCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside a lambda expression.</source>
<target state="translated">'Сообщения "On Error" и "Resume" не могут находиться в лямбда-выражении.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceDisallowedHere">
<source>Keywords 'Out' and 'In' can only be used in interface and delegate declarations.</source>
<target state="translated">Ключевые слова "Out" и "In" могут использоваться только в объявлениях интерфейсов и делегатов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndCDataNotAllowedInContent">
<source>The literal string ']]>' is not allowed in element content.</source>
<target state="translated">Использование строки литерала "]]>" в содержимом элемента не допускается.</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadsModifierInModule">
<source>Inappropriate use of '{0}' keyword in a module.</source>
<target state="translated">Неправильное использование ключевого слова "{0}" в модуле.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedTypeOrNamespace1">
<source>Type or namespace '{0}' is not defined.</source>
<target state="translated">Тип или пространство имен "{0}" не определено.</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentityDirectCastForFloat">
<source>Using DirectCast operator to cast a floating-point value to the same type is not supported.</source>
<target state="translated">Использование оператора DirectCast для приведения значения с плавающей точкой к тому же типу не поддерживается.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete.</source>
<target state="translated">Использование оператора DirectCast для приведения типа значения к тому же типу больше не нужно.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType_Title">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete</source>
<target state="translated">Использование оператора DirectCast для приведения типа значения к тому же типу больше не нужно</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode">
<source>Unreachable code detected.</source>
<target state="translated">Обнаружен недостижимый код.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode_Title">
<source>Unreachable code detected</source>
<target state="translated">Обнаружен недостижимый код</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1">
<source>Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Функция "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">Функция не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1">
<source>Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Оператор "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">Оператор не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1">
<source>Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Свойство "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">Свойство не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedGlobalNamespace">
<source>Global namespace may not be nested in another namespace.</source>
<target state="translated">Глобальные пространства имен нельзя вкладывать в другие пространства имен.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatch6">
<source>'{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'.</source>
<target state="translated">"{0}" не может представлять тип "{1}" в {2} "{3}" посредством {4} "{5}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMetaDataReference1">
<source>'{0}' cannot be referenced because it is not a valid assembly.</source>
<target state="translated">'"Задание ссылок на "{0}" не предусмотрено, поскольку это недопустимая сборка.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementAllAccessors">
<source>'{0}' cannot be implemented by a {1} property.</source>
<target state="translated">"{0}" невозможно реализовать с помощью свойства {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMustOverride">
<source>
{0}: {1}</source>
<target state="translated">
{0}: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfTooManyTypesObjectDisallowed">
<source>Cannot infer a common type because more than one type is possible.</source>
<target state="translated">Не удается получить общий тип, так как возможно больше одного типа.</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed">
<source>Cannot infer a common type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">Не удается получить общий тип, так как возможно больше одного типа: предполагается "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed_Title">
<source>Cannot infer a common type because more than one type is possible</source>
<target state="translated">Не удается получить общий тип, так как возможно больше одного типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoTypeObjectDisallowed">
<source>Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.</source>
<target state="translated">Не удается получить общий тип, так как параметр Strict On не разрешает предположение "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed">
<source>Cannot infer a common type; 'Object' assumed.</source>
<target state="translated">Не удается определить общий тип; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed_Title">
<source>Cannot infer a common type</source>
<target state="translated">Невозможно получить общий тип</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoType">
<source>Cannot infer a common type.</source>
<target state="translated">Не удалось определить общий тип.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyFileFailure">
<source>Error extracting public key from file '{0}': {1}</source>
<target state="translated">Ошибка извлечения открытого ключа из файла "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyContainerFailure">
<source>Error extracting public key from container '{0}': {1}</source>
<target state="translated">Ошибка извлечения открытого ключа из контейнера "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefNotEqualToThis">
<source>Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</source>
<target state="translated">Дружественный доступ предоставлен "{0}", однако открытый ключ выходной сборки не соответствует ключу, определенному атрибутом предоставляющей сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefSigningMismatch">
<source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source>
<target state="translated">Дружественный доступ предоставлен "{0}", однако состояние подписи строгого имени выходной сборки не соответствует состоянию предоставляющей сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNoKey">
<source>Public sign was specified and requires a public key, but no public key was specified</source>
<target state="translated">Указана общедоступная подпись, и требуется открытый ключ, но открытый ключ не указан.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNetModule">
<source>Public signing is not supported for netmodules.</source>
<target state="translated">Общедоступные подписи не поддерживаются для netmodule.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning">
<source>Attribute '{0}' is ignored when public signing is specified.</source>
<target state="translated">Атрибут "{0}" пропускается при указании общедоступного подписывания.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title">
<source>Attribute is ignored when public signing is specified.</source>
<target state="translated">Атрибут пропускается при указании общедоступного подписывания.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey">
<source>Delay signing was specified and requires a public key, but no public key was specified.</source>
<target state="translated">Была указана отложенная подпись, для которой требуется открытый ключ. Открытый ключ не был указан.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey_Title">
<source>Delay signing was specified and requires a public key, but no public key was specified</source>
<target state="translated">Была указана отложенная подпись, для которой требуется открытый ключ, но открытый ключ не был указан</target>
<note />
</trans-unit>
<trans-unit id="ERR_SignButNoPrivateKey">
<source>Key file '{0}' is missing the private key needed for signing.</source>
<target state="translated">Файл ключа "{0}" не содержит закрытого ключа, необходимого для подписания.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FailureSigningAssembly">
<source>Error signing assembly '{0}': {1}</source>
<target state="translated">Ошибка при подписи сборки "{0}": {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat">
<source>The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]]</source>
<target state="translated">Указанная строка версии не соответствует требуемому формату: основной номер[.дополнительный номер[.сборка|*[.редакция|*]]]</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">Указанная строка версии не соответствует рекомендованному формату — основной номер.дополнительный номер.сборка.редакция</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat_Title">
<source>The specified version string does not conform to the recommended format</source>
<target state="translated">Указанная строка версии не соответствует рекомендуемому формату</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat2">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">Указанная строка версии не соответствует рекомендованному формату — основной номер.дополнительный номер.сборка.редакция</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCultureForExe">
<source>Executables cannot be satellite assemblies; culture should always be empty</source>
<target state="translated">Исполняемые файлы не могут быть вспомогательными сборками; язык и региональные параметры должны быть пустыми.</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored">
<source>The entry point of the program is global script code; ignoring '{0}' entry point.</source>
<target state="translated">Точкой входа программы является глобальный код скрипта; игнорируйте точку входа "{0}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored_Title">
<source>The entry point of the program is global script code; ignoring entry point</source>
<target state="translated">Точка входа в программе является глобальным кодом скрипта; выполняется пропуск точки входа</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName">
<source>The xmlns attribute has special meaning and should not be written with a prefix.</source>
<target state="translated">Атрибут xmlns имеет особое значение и не должен быть написан с префиксом.</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName_Title">
<source>The xmlns attribute has special meaning and should not be written with a prefix</source>
<target state="translated">Атрибут xmlns имеет особое значение и не должен быть записан с префиксом</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName">
<source>It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:{0}' to define a prefix named '{0}'?</source>
<target state="translated">Не рекомендуется иметь атрибуты с именем xmlns. Имелось в виду написание "xmlns:{0}" для определения префикса с именем "{0}"?</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName_Title">
<source>It is not recommended to have attributes named xmlns</source>
<target state="translated">Атрибуты не рекомендуется называть "xmlns"</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSingleScript">
<source>Expected a single script (.vbx file)</source>
<target state="translated">Ожидался отдельный скрипт (VBX-файл)</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedAssemblyName">
<source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source>
<target state="translated">Имя сборки "{0}" зарезервировано и не может использоваться как ссылка в интерактивном сеансе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts">
<source>#R is only allowed in scripts</source>
<target state="translated">#R допускается только в скриптах</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAllowedInScript">
<source>You cannot declare Namespace in script code</source>
<target state="translated">Нельзя объявить пространство имен в коде скрипта</target>
<note />
</trans-unit>
<trans-unit id="ERR_KeywordNotAllowedInScript">
<source>You cannot use '{0}' in top-level script code</source>
<target state="translated">Нельзя использовать "{0}" в коде скрипта верхнего уровня.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoType">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">Не удалось определить возвращаемый тип. Для указания возвращаемого типа рекомендуется добавлять предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed">
<source>Cannot infer a return type; 'Object' assumed.</source>
<target state="translated">Не удается определить тип возвращаемого значения; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed_Title">
<source>Cannot infer a return type</source>
<target state="translated">Невозможно определить тип возвращаемого значения</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed">
<source>Cannot infer a return type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">Не удается получить тип возвращаемого значения, так как возможно больше одного типа; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed_Title">
<source>Cannot infer a return type because more than one type is possible</source>
<target state="translated">Невозможно определить тип возвращаемого значения, так как возможно больше одного типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoTypeObjectDisallowed">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">Не удалось определить возвращаемый тип. Для указания возвращаемого типа рекомендуется добавлять предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaTooManyTypesObjectDisallowed">
<source>Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">Не удается получить возвращаемый тип, так как возможно больше одного типа. Для указания возвращаемого типа рекомендуется добавлять предложение "As".</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch">
<source>The command line switch '{0}' is not yet implemented and was ignored.</source>
<target state="translated">Переключатель командной строки "{0}" еще не реализован и был пропущен.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch_Title">
<source>Command line switch is not yet implemented</source>
<target state="translated">Переключатель командной строки еще не реализован</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoTypeObjectDisallowed">
<source>Cannot infer an element type, and Option Strict On does not allow 'Object' to be assumed. Specifying the type of the array might correct this error.</source>
<target state="translated">Не удается получить тип элемента, параметр Strict On не разрешает предположение "Object". Указание типа массива может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoType">
<source>Cannot infer an element type. Specifying the type of the array might correct this error.</source>
<target state="translated">Не удалось определить тип элемента. Указание типа массива может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitTooManyTypesObjectDisallowed">
<source>Cannot infer an element type because more than one type is possible. Specifying the type of the array might correct this error.</source>
<target state="translated">Не удается получить тип элемента, так как возможно больше одного типа. Указание типа массива может исправить эту ошибку.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed">
<source>Cannot infer an element type; 'Object' assumed.</source>
<target state="translated">Не удается определить тип элемента; предполагаемый тип — "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed_Title">
<source>Cannot infer an element type</source>
<target state="translated">Невозможно определить тип элемента</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed">
<source>Cannot infer an element type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">Не удается получить тип элемента, так как возможно больше одного типа: предполагается "Object".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed_Title">
<source>Cannot infer an element type because more than one type is possible</source>
<target state="translated">Невозможно определить тип элемента, так как возможно больше одного типа</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3">
<source>Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed.</source>
<target state="translated">Не удалось получить тип данных "{0}" в "{1}". "{2}" предполагается.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3_Title">
<source>Data type could not be inferred</source>
<target state="translated">Не удалось определить тип данных</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousCastConversion2">
<source>Option Strict On does not allow implicit conversions from '{0}' to '{1}' because the conversion is ambiguous.</source>
<target state="translated">Параметр Strict On не допускает неявные преобразования из "{0}" в "{1}", поскольку такое преобразование неоднозначно.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2">
<source>Conversion from '{0}' to '{1}' may be ambiguous.</source>
<target state="translated">Преобразование "{0}" в "{1}" может привести к неоднозначности.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2_Title">
<source>Conversion may be ambiguous</source>
<target state="translated">Преобразование может быть неоднозначным</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте использовать "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3_Title">
<source>Type cannot be converted to target collection type</source>
<target state="translated">Невозможно преобразовать тип в целевой тип коллекции</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedIn6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">"{4}" нельзя преобразовать в "{5}", так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "In" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedOut6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">'{4}" нельзя преобразовать в "{5}", так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "Out" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">Неявное преобразование "{4}" в "{5}"; возможны ошибки преобразования, так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "In" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'In' generic parameter</source>
<target state="translated">Неявное преобразование; может произойти сбой этого преобразования, так как целевой тип не наследуется от типа источника, как это требуется для универсального параметра In</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">Неявное преобразование "{4}" в "{5}"; возможно ошибки преобразования, так как "{0}" не наследованы из "{1}" в соответствии с требованием универсального параметра "Out" "{2}" в "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'Out' generic parameter</source>
<target state="translated">Неявное преобразование; может произойти сбой этого преобразования, так как целевой тип не наследуется из типа источника, как это требуется для универсального параметра Out</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр In, "In {2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">Тип невозможно преобразовать в целевой тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">"{0}" нельзя преобразовать в "{1}". Попробуйте изменить "{2}" в определении "{3}" на параметр типа Out, "Out {2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">Тип невозможно преобразовать в целевой тип</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3">
<source>Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'.</source>
<target state="translated">Интерфейс "{0}" неоднозначен с другим реализованным интерфейсом "{1}" из-за параметров "In" и "Out" в "{2}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3_Title">
<source>Interface is ambiguous with another implemented interface due to 'In' and 'Out' parameters</source>
<target state="translated">Интерфейс неоднозначен, так как другой интерфейс реализован в соответствии с параметрами In и Out</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInterfaceNesting">
<source>Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.</source>
<target state="translated">Перечисления, классы и структуры не могут быть объявлены в интерфейсе, имеющем параметр типа "In" или "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VariancePreventsSynthesizedEvents2">
<source>Event definitions with parameters are not allowed in an interface such as '{0}' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within '{0}'. For example, 'Event {1} As Action(Of ...)'.</source>
<target state="translated">Определения событий с параметрами не допускается в интерфейсе, например "{0}", который имеет параметры "In" или "Out". Попробуйте объявить событие с помощью делегата, который не определен в "{0}". Например, "Event {1} As Action(Of ...)".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в этом контексте, так как параметры "In" и "Out" нельзя использовать для параметра ByRef и "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в "{1}" так как параметры "In" и "Out" не допускают значение Null и "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать для "{1}" в "{2}" в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в "{1}" в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать для "{2}" "{3}" в "{1}" в этом контексте, так как "{0}" является параметром "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа свойства в данном контексте, так как "{0}" является параметром типа "In" и свойство не помечено как WriteOnly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReadOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в качестве свойства ReadOnly, так как "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReturnDisallowed1">
<source>Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в качестве возвращаемого типа, так как "{0}" является параметром типа "In".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в этом контексте, потому что тип параметров "In" и "Out" нельзя использовать для типов параметра ByRef и "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByValDisallowed1">
<source>Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" нельзя использовать в качестве типа параметра ByVal, так как "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutConstraintDisallowed1">
<source>Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа ограничения, так как "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в "{1}", так как параметры "In" и "Out" не допускают значение Null и "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться для "{1}" в "{2}" в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться в "{1}" в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может использоваться для "{2}" "{3}" в "{1}" в этом контексте, так как "{0}" является параметром "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа свойства в данном контексте, так как "{0}" является параметром типа "Out" и свойство не помечено как ReadOnly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutWriteOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">Тип "{0}" не может быть использован в качестве типа свойства WriteOnly, так как "{0}" является параметром типа "Out".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowed2">
<source>Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться для "{2}" в "{3}" в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHere3">
<source>Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться для "{2}" в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHereForGeneric5">
<source>Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">Тип "{0}" не может использоваться для "{3}" "{4}" в "{2}" в этом контексте, так как контекст и определение "{0}" вложены в интерфейс "{1}" и "{1}" имеют параметры "In" или "Out". Попробуйте переместить определение "{0}" за пределы "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterNotValidForType">
<source>Parameter not valid for the specified unmanaged type.</source>
<target state="translated">Недопустимый параметр для указанного неуправляемого типа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields">
<source>Unmanaged type '{0}' not valid for fields.</source>
<target state="translated">Неуправляемый тип "{0}" недопустим для полей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields">
<source>Unmanaged type '{0}' is only valid for fields.</source>
<target state="translated">Неуправляемый тип "{0}" допустим только для полей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired1">
<source>Attribute parameter '{0}' must be specified.</source>
<target state="translated">Должен быть указан параметр атрибута "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired2">
<source>Attribute parameter '{0}' or '{1}' must be specified.</source>
<target state="translated">Должен быть указан параметр атрибута "{0}" или "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberConflictWithSynth4">
<source>Conflicts with '{0}', which is implicitly declared for '{1}' in {2} '{3}'.</source>
<target state="translated">Конфликтует с "{0}", неявно объявленным для "{1}" в {2} "{3}".</target>
<note />
</trans-unit>
<trans-unit id="IDS_ProjectSettingsLocationName">
<source><project settings></source>
<target state="translated"><настройки проекта></target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty">
<source>Attributes applied on a return type of a WriteOnly Property have no effect.</source>
<target state="translated">Атрибуты, применяемые к возвращаемому типу свойства WriteOnly, никак не влияют.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty_Title">
<source>Attributes applied on a return type of a WriteOnly Property have no effect</source>
<target state="translated">Атрибуты, применяемые к типу возвращаемого значения свойства WriteOnly, никак не влияют</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidTarget">
<source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source>
<target state="translated">Атрибут безопасности "{0}" не допускается для этого типа объявления. Атрибуты безопасности допустимы только в сборке, типе и объявлениях метода.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AbsentReferenceToPIA1">
<source>Cannot find the interop type that matches the embedded type '{0}'. Are you missing an assembly reference?</source>
<target state="translated">Не удается найти тип взаимодействия, соответствующий внедренному типу взаимодействия "{0}". Возможно, отсутствует ссылка на сборку.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLinkClassWithNoPIA1">
<source>Reference to class '{0}' is not allowed when its assembly is configured to embed interop types.</source>
<target state="translated">Ссылка на класс "{0}" не разрешена, когда его сборка настроена для внедрения типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidStructMemberNoPIA1">
<source>Embedded interop structure '{0}' can contain only public instance fields.</source>
<target state="translated">Внедренная структура взаимодействия "{0}" может содержать только открытые экземпляры полей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPIAAttributeMissing2">
<source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source>
<target state="translated">Не удается внедрить тип взаимодействия "{0}", так как у него отсутствует обязательный атрибут "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoAssemblyGuid1">
<source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source>
<target state="translated">Не удается внедрить типы взаимодействия из сборки "{0}" из-за отсутствия в ней атрибута "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalTypes3">
<source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider disabling the embedding of interop types.</source>
<target state="translated">Не удается внедрить тип взаимодействия "{0}", находящийся в обеих сборках "{1}" и "{2}". Попробуйте отключить внедрение типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoTypeLibAttribute1">
<source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source>
<target state="translated">Внедрение типов взаимодействия из сборки "{0}" невозможно, так как у нее отсутствует атрибут "{1}" или атрибут "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceInterfaceMustBeInterface">
<source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source>
<target state="translated">Интерфейс "{0}" имеет недопустимый исходный интерфейс, который требуется для внедрения события "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNoPIANoBackingMember">
<source>Source interface '{0}' is missing method '{1}', which is required to embed event '{2}'.</source>
<target state="translated">В исходном интерфейсе "{0}" отсутствует метод "{1}", обязательный для внедрения события "{2}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedInteropType">
<source>Nested type '{0}' cannot be embedded.</source>
<target state="translated">Невозможно внедрить вложенный тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalTypeNameClash2">
<source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types.</source>
<target state="translated">Внедрение типа взаимодействия "{0}" из сборки "{1}" служит причиной конфликта имен в текущей сборке. Попробуйте отключить внедрение типов взаимодействия.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InteropMethodWithBody1">
<source>Embedded interop method '{0}' contains a body.</source>
<target state="translated">Внедренный метод взаимодействия "{0}" содержит тело.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncInQuery">
<source>'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.</source>
<target state="translated">'Оператор Await можно использовать только в выражении запроса в первом выражении коллекции начального предложения From или в выражении коллекции предложения Join.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGetAwaiterMethod1">
<source>'Await' requires that the type '{0}' have a suitable GetAwaiter method.</source>
<target state="translated">'Для применения оператора "await" у типа "{0}" должен быть подходящий метод GetAwaiter.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIsCompletedOnCompletedGetResult2">
<source>'Await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.</source>
<target state="translated">'Для использования оператора "Await" необходимо, чтобы у возвращаемого типа "{0}" метода "{1}.GetAwaiter()" были соответствующие члены IsCompleted, OnCompleted и GetResult и чтобы этот тип реализовывал интерфейс INotifyCompletion или ICriticalNotifyCompletion.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoesntImplementAwaitInterface2">
<source>'{0}' does not implement '{1}'.</source>
<target state="translated">"{0}" не реализует "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNothing">
<source>Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.</source>
<target state="translated">Нельзя ожидать значение Nothing. Попробуйте вместо этого ожидать Task.Yield().</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncByRefParam">
<source>Async methods cannot have ByRef parameters.</source>
<target state="translated">Методы с модификатором Async не могут иметь параметры ByRef.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAsyncIteratorModifiers">
<source>'Async' and 'Iterator' modifiers cannot be used together.</source>
<target state="translated">'Модификаторы "Async" и "Iterator" нельзя использовать одновременно.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadResumableAccessReturnVariable">
<source>The implicit return variable of an Iterator or Async method cannot be accessed.</source>
<target state="translated">Нельзя получить доступ к неявно возвращаемой переменной метода, помеченного модификатором Iterator или Async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonGenericTaskAsync">
<source>'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.</source>
<target state="translated">'Операторам "Return" данного метода Async не удается вернуть значение, поскольку для функции указан возвращаемый тип "Task". Попробуйте изменить тип возвращаемого значения на "Task(Of T)".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturnOperand1">
<source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task(Of {0})'.</source>
<target state="translated">Поскольку данный метод является асинхронным, возвращаемое выражение должно относиться к типу "{0}", а не к типу "Task(Of {0})".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturn">
<source>The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).</source>
<target state="translated">Модификатор Async можно использовать только в подпрограммах или в функциях, которые возвращают значения типа Task или Task(Of T).</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAwaitAsyncSub1">
<source>'{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function.</source>
<target state="translated">"{0}" не возвращает значения типа Task, и его нельзя ожидать. Попробуйте заменить его на функцию с модификатором Async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLambdaModifier">
<source>'Only the 'Async' or 'Iterator' modifier is valid on a lambda.</source>
<target state="translated">'В лямбда-выражениях допускаются только модификаторы "Async" или "Iterator".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of {0})'.</source>
<target state="translated">'Оператор await можно использовать только в методах с модификатором async. Попробуйте пометить этот метод модификатором "Async" и изменить его возвращаемый тип на "Task(Of {0})".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncVoidMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.</source>
<target state="translated">'Оператор await можно использовать только в методах с модификатором async. Попробуйте пометить этот метод модификатором async и изменить тип его возвращаемого значения на Task.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncLambda">
<source>'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.</source>
<target state="translated">'Оператор await можно использовать только в лямбда-выражениях с модификатором async. Попробуйте пометить это лямбда-выражение модификатором async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNotInAsyncMethodOrLambda">
<source>'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.</source>
<target state="translated">'Оператор await можно использовать, только если он содержится в методе или лямбда-выражении, помеченном модификатором async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_StatementLambdaInExpressionTree">
<source>Statement lambdas cannot be converted to expression trees.</source>
<target state="translated">Лямбды оператора невозможно преобразовать в деревья выражений.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression">
<source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.</source>
<target state="translated">Поскольку этот вызов не ожидается, выполнение текущего метода продолжается до завершения вызова. Попробуйте применить оператор Await к результату вызова.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression_Title">
<source>Because this call is not awaited, execution of the current method continues before the call is completed</source>
<target state="translated">Так как этот вызов не ожидается, выполнение существующего метода продолжается до тех пор, пока вызов не будет завершен</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotAwait">
<source>Loop control variable cannot include an 'Await'.</source>
<target state="translated">Управляющая переменная цикла не может содержать "Await".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticInitializerInResumable">
<source>Static variables cannot appear inside Async or Iterator methods.</source>
<target state="translated">В методах Async или Iterator нельзя использовать статические переменные.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedResumableType1">
<source>'{0}' cannot be used as a parameter type for an Iterator or Async method.</source>
<target state="translated">"{0}" не может быть использовано в качестве типа параметра для метода Iterator или Async.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorAsync">
<source>Constructor must not have the 'Async' modifier.</source>
<target state="translated">Конструктор не должен иметь модификатор "Async".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustNotBeAsync1">
<source>'{0}' cannot be declared 'Partial' because it has the 'Async' modifier.</source>
<target state="translated">"{0}" не может быть объявлен "Partial", так как имеет модификатор "Async".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumablesCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside async or iterator methods.</source>
<target state="translated">'В методах, помеченных модификатором "Async" или "Iterator", не могут возникать события "On Error" и "Resume".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumableLambdaInExpressionTree">
<source>Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.</source>
<target state="translated">Лямбда-выражения с модификаторами "Async" и "Iterator" нельзя преобразовать в деревья выражений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeResumable1">
<source>Variable of restricted type '{0}' cannot be declared in an Async or Iterator method.</source>
<target state="translated">Переменную ограниченного типа "{0}" нельзя объявить в методе, помеченном модификатором Async или Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInTryHandler">
<source>'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.</source>
<target state="translated">'Оператор Await нельзя использовать в операторах Catch, Finally и SyncLock.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits">
<source>This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.</source>
<target state="translated">В данном асинхронном методе отсутствуют операторы "Await", поэтому метод будет выполняться синхронно. Воспользуйтесь оператором "Await" для ожидания неблокирующих вызовов API или оператором "Await Task.Run(...)" для выполнения связанных с ЦП заданий в фоновом потоке.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits_Title">
<source>This async method lacks 'Await' operators and so will run synchronously</source>
<target state="translated">В асинхронном методе отсутствуют операторы Await; будет выполнен синхронный запуск</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.</source>
<target state="translated">Задача, возвращенная этой функцией Async, будет удалена, а все исключения будут игнорироваться. Попробуйте изменить ее на подпрограмму Async, чтобы исключения распространялись.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate_Title">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored</source>
<target state="translated">Задача, полученная из асинхронной функции, будет удалена, а все исключения в ней — пропущены</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsyncInClassOrStruct">
<source>Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source>
<target state="translated">Методы Async и Iterator недопустимо использовать в [Класс|Структура|Интерфейс|Модуль] с атрибутом "SecurityCritical" или "SecuritySafeCritical".</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsync">
<source>Security attribute '{0}' cannot be applied to an Async or Iterator method.</source>
<target state="translated">Атрибут безопасности "{0}" нельзя применить к методу Async или Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnResumableMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.</source>
<target state="translated">'Атрибут "System.Runtime.InteropServices.DllImportAttribute" не может применяться к методам Async или Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynchronizedAsyncMethod">
<source>'MethodImplOptions.Synchronized' cannot be applied to an Async method.</source>
<target state="translated">'Невозможно применить "MethodImplOptions.Synchronized" к асинхронному методу.</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsyncSubMain">
<source>The 'Main' method cannot be marked 'Async'.</source>
<target state="translated">Метод Main нельзя пометить модификатором Async.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction">
<source>Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.</source>
<target state="translated">Некоторые используемые здесь перегрузки принимают функцию Async, а не подпрограмму Async. Воспользуйтесь функцией Async или выполните явное приведение данной подпрограммы Async к требуемому типу.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction_Title">
<source>Some overloads here take an Async Function rather than an Async Sub</source>
<target state="translated">Некоторые используемые здесь перегрузки принимают функцию с модификатором Async, а не подпрограмму с модификатором Async</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyGroupCollectionAttributeCycle">
<source>MyGroupCollectionAttribute cannot be applied to itself.</source>
<target state="translated">Атрибут MyGroupCollectionAttribute нельзя применить к самому себе.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LiteralExpected">
<source>Literal expected.</source>
<target state="translated">Требуется литерал.</target>
<note />
</trans-unit>
<trans-unit id="ERR_WinRTEventWithoutDelegate">
<source>Event declarations that target WinMD must specify a delegate type. Add an As clause to the event declaration.</source>
<target state="translated">В объявления событий, предназначенных для WinMD, должен указываться тип делегатов. Добавьте в объявление событий предложение As.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MixingWinRTAndNETEvents">
<source>Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}'</source>
<target state="translated">Событие "{0}" не может реализовать событие среды выполнения Windows "{1}" и регулярное событие .NET "{2}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplRemoveHandlerParamWrong">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because the parameters of their 'RemoveHandler' methods do not match.</source>
<target state="translated">Событию "{0}" не удается реализовать событие "{1}" в интерфейсе "{2}" из-за несовпадения параметров их методов "RemoveHandler".</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddParamWrongForWinRT">
<source>The type of the 'AddHandler' method's parameter must be the same as the type of the event.</source>
<target state="translated">Тип параметра метода AddHandler должен совпадать с типом события.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RemoveParamWrongForWinRT">
<source>In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken'</source>
<target state="translated">В событии среды выполнения Windows тип параметра метода "RemoveHandler" должен иметь значение "EventRegistrationToken"</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface5">
<source>'{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed</source>
<target state="translated">"{0}.{1}" из "implements {2}" уже реализован базовым классом "{3}". Повторная реализация интерфейса среды выполнения Windows "{4}" не разрешена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface4">
<source>'{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed</source>
<target state="translated">"{0}.{1}" уже реализован базовым классом "{2}". Повторная реализация интерфейса среды выполнения Windows "{3}" не разрешена.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorByRefParam">
<source>Iterator methods cannot have ByRef parameters.</source>
<target state="translated">Методы с модификатором Iterator не могут иметь параметры ByRef.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorExpressionLambda">
<source>Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.</source>
<target state="translated">Лямбда-выражения, состоящие из одной строки, не могут содержать модификатор Iterator. Используйте лямбда-выражение, состоящее из нескольких строк.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorReturn">
<source>Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.</source>
<target state="translated">Функции с модификатором Iterator должны возвращать интерфейс IEnumerable(Of T) или IEnumerator(Of T) либо неуниверсальные формы перечисления IEnumerable или IEnumerator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadReturnValueInIterator">
<source>To return a value from an Iterator function, use 'Yield' rather than 'Return'.</source>
<target state="translated">Для возвращения значения из функции с модификатором Iterator используйте оператор Yield, а не оператор Return.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInNonIteratorMethod">
<source>'Yield' can only be used in a method marked with the 'Iterator' modifier.</source>
<target state="translated">'Yield можно использовать только в методах, помеченных модификатором Iterator.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInTryHandler">
<source>'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.</source>
<target state="translated">'Yield нельзя использовать в операторе Catch или Finally.</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1">
<source>The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">AddHandler для события среды выполнения Windows "{0}" не возвращает значение для всех путей к коду. Возможно, отсутствует оператор "Return".</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1_Title">
<source>The AddHandler for Windows Runtime event doesn't return a value on all code paths</source>
<target state="translated">Атрибут AddHandler для события среды выполнения Windows не возвращает значение на всех путях к коду</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodDefaultParameterValueMismatch2">
<source>Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">Необязательный параметр метода "{0}" не имеет то же значение по умолчанию, что и соответствующий параметр разделяемого метода "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamArrayMismatch2">
<source>Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">Параметр метода "{0}" отличается по модификатору ParamArray из соответствующего параметра разделяемого метода "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMismatch">
<source>Module name '{0}' stored in '{1}' must match its filename.</source>
<target state="translated">Имя модуля "{0}", сохраненное в "{1}", должно соответствовать его имени файла.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleName">
<source>Invalid module name: {0}</source>
<target state="translated">Недопустимое имя модуля: {0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden">
<source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source.</source>
<target state="translated">Атрибут "{0}" из модуля "{1}" будут игнорироваться в пользу экземпляра в исходнике.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title">
<source>Attribute from module will be ignored in favor of the instance appearing in source</source>
<target state="translated">Вместо атрибута модуля будет показан экземпляр, отображающийся в источнике</target>
<note />
</trans-unit>
<trans-unit id="ERR_CmdOptionConflictsSource">
<source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source>
<target state="translated">Атрибут "{0}", заданный в исходном файле, конфликтует с параметром "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName">
<source>Referenced assembly '{0}' does not have a strong name.</source>
<target state="translated">У сборки "{0}", на которую дается ссылка, нет строгого имени.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title">
<source>Referenced assembly does not have a strong name</source>
<target state="translated">Сборка, на которую указывает ссылка, не имеет строгого имени</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSignaturePublicKey">
<source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source>
<target state="translated">В AssemblySignatureKeyAttribute определен недопустимый открытый ключ подписи.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CollisionWithPublicTypeInModule">
<source>Type '{0}' conflicts with public type defined in added module '{1}'.</source>
<target state="translated">Тип "{0}" конфликтует с общим типом, определенным в добавленном модуле "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypeConflictsWithDeclaration">
<source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">Тип "{0}", экспортированный из модуля "{1}", конфликтует с типом, объявленным в основном модуле этой сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypesConflict">
<source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">Тип "{0}", экспортированный из модуля "{1}", конфликтует с типом "{2}", экспортированным из модуля "{3}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch">
<source>Referenced assembly '{0}' has different culture setting of '{1}'.</source>
<target state="translated">Сборка "{0}", на которую дается ссылка, использует другой параметр языка и региональных параметров "{1}".</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch_Title">
<source>Referenced assembly has different culture setting</source>
<target state="translated">Сборка, на которую указывает ссылка, содержит другой параметр языка и региональных параметров</target>
<note />
</trans-unit>
<trans-unit id="ERR_AgnosticToMachineModule">
<source>Agnostic assembly cannot have a processor specific module '{0}'.</source>
<target state="translated">Безразмерная сборка не может иметь модуль для конкретного процессора "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingMachineModule">
<source>Assembly and module '{0}' cannot target different processors.</source>
<target state="translated">Сборка и модуль "{0}" не могут предназначаться для разных процессоров.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly">
<source>Referenced assembly '{0}' targets a different processor.</source>
<target state="translated">Сборка, на которую дана ссылка "{0}", направлена на другой процессор.</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly_Title">
<source>Referenced assembly targets a different processor</source>
<target state="translated">Сборка, на которую указывает ссылка, предназначена для другого процессора</target>
<note />
</trans-unit>
<trans-unit id="ERR_CryptoHashFailed">
<source>Cryptographic failure while creating hashes.</source>
<target state="translated">Сбой шифрования при создании хэшей.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantHaveWin32ResAndManifest">
<source>Conflicting options specified: Win32 resource file; Win32 manifest.</source>
<target state="translated">Заданы несовместимые параметры: файл ресурсов Win32; манифест Win32.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration">
<source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">Отправленный тип "{0}" конфликтует с типом, объявленным в основном модуле этой сборки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypesConflict">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source>
<target state="translated">Тип "{0}", отправленный в сборку "{1}", конфликтует с типом "{2}", отправленным в сборку "{3}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongMetadataName">
<source>Name '{0}' exceeds the maximum length allowed in metadata.</source>
<target state="translated">Имя "{0}" превышает максимальную длину, допустимую в метаданных.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNetModuleReference">
<source>Reference to '{0}' netmodule missing.</source>
<target state="translated">Отсутствует ссылка на "{0}" netmodule.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMustBeUnique">
<source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source>
<target state="translated">Модуль "{0}" уже определен в этой сборке. Каждый модуль должен иметь уникальное имя.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithExportedType">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">Тип "{0}", отправленный в сборку "{1}", конфликтует с типом "{2}", экспортированным из модуля "{3}".</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDREFERENCE">
<source>Adding assembly reference '{0}'</source>
<target state="translated">Добавление ссылки на сборку "{0}"</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDLINKREFERENCE">
<source>Adding embedded assembly reference '{0}'</source>
<target state="translated">Добавление ссылки на встроенную сборку "{0}"</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDMODULE">
<source>Adding module reference '{0}'</source>
<target state="translated">Добавление ссылки на модуль "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestingViolatesCLS1">
<source>Type '{0}' does not inherit the generic type parameters of its container.</source>
<target state="translated">Тип "{0}" не наследует параметров универсального типа для контейнера.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PDBWritingFailed">
<source>Failure writing debug information: {0}</source>
<target state="translated">Сбой при записи информации отладки: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute">
<source>The parameter has multiple distinct default values.</source>
<target state="translated">Параметр имеет несколько различных значений по умолчанию.</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldHasMultipleDistinctConstantValues">
<source>The field has multiple distinct constant values.</source>
<target state="translated">Поле имеет несколько различных константных значений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncNoPIAReference">
<source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source>
<target state="translated">Не удается продолжить, так как оператор edit содержит ссылку на встроенный тип: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncReferenceToAddedMember">
<source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source>
<target state="translated">Доступ к члену "{0}", добавленному в ходе текущего сеанса отладки, возможен только из его объявляющей сборки "{1}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedModule1">
<source>'{0}' is an unsupported .NET module.</source>
<target state="translated">"{0}" не поддерживается модулем .NET.</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedEvent1">
<source>'{0}' is an unsupported event.</source>
<target state="translated">"{0}" является неподдерживаемым событием.</target>
<note />
</trans-unit>
<trans-unit id="PropertiesCanNotHaveTypeArguments">
<source>Properties can not have type arguments</source>
<target state="translated">Свойства не могут иметь тип аргументов.</target>
<note />
</trans-unit>
<trans-unit id="IdentifierSyntaxNotWithinSyntaxTree">
<source>IdentifierSyntax not within syntax tree</source>
<target state="translated">IdentifierSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="AnonymousObjectCreationExpressionSyntaxNotWithinTree">
<source>AnonymousObjectCreationExpressionSyntax not within syntax tree</source>
<target state="translated">AnonymousObjectCreationExpressionSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="FieldInitializerSyntaxNotWithinSyntaxTree">
<source>FieldInitializerSyntax not within syntax tree</source>
<target state="translated">FieldInitializerSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="IDS_TheSystemCannotFindThePathSpecified">
<source>The system cannot find the path specified</source>
<target state="translated">Системе не удается найти указанный путь</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoPointerTypesInVB">
<source>There are no pointer types in VB.</source>
<target state="translated">В VB нет типов указателей.</target>
<note />
</trans-unit>
<trans-unit id="ThereIsNoDynamicTypeInVB">
<source>There is no dynamic type in VB.</source>
<target state="translated">В VB нет динамического типа.</target>
<note />
</trans-unit>
<trans-unit id="VariableSyntaxNotWithinSyntaxTree">
<source>variableSyntax not within syntax tree</source>
<target state="translated">variableSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="AggregateSyntaxNotWithinSyntaxTree">
<source>AggregateSyntax not within syntax tree</source>
<target state="translated">AggregateSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="FunctionSyntaxNotWithinSyntaxTree">
<source>FunctionSyntax not within syntax tree</source>
<target state="translated">FunctionSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="PositionIsNotWithinSyntax">
<source>Position is not within syntax tree</source>
<target state="translated">Позиция не входит в синтаксическое дерево.</target>
<note />
</trans-unit>
<trans-unit id="RangeVariableSyntaxNotWithinSyntaxTree">
<source>RangeVariableSyntax not within syntax tree</source>
<target state="translated">RangeVariableSyntax находится вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinSyntaxTree">
<source>DeclarationSyntax not within syntax tree</source>
<target state="translated">DeclarationSyntax вне синтаксического дерева</target>
<note />
</trans-unit>
<trans-unit id="StatementOrExpressionIsNotAValidType">
<source>StatementOrExpression is not an ExecutableStatementSyntax or an ExpressionSyntax</source>
<target state="translated">StatementOrExpression не является ExecutableStatementSyntax или ExpressionSyntax</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinTree">
<source>DeclarationSyntax not within tree</source>
<target state="translated">DeclarationSyntax вне дерева</target>
<note />
</trans-unit>
<trans-unit id="TypeParameterNotWithinTree">
<source>TypeParameter not within tree</source>
<target state="translated">TypeParameter находится вне дерева</target>
<note />
</trans-unit>
<trans-unit id="NotWithinTree">
<source> not within tree</source>
<target state="translated"> вне дерева</target>
<note />
</trans-unit>
<trans-unit id="LocationMustBeProvided">
<source>Location must be provided in order to provide minimal type qualification.</source>
<target state="translated">Чтобы выполнить минимальную квалификацию типа, необходимо указать расположение.</target>
<note />
</trans-unit>
<trans-unit id="SemanticModelMustBeProvided">
<source>SemanticModel must be provided in order to provide minimal type qualification.</source>
<target state="translated">Для обеспечения минимального типа квалификации требуется SemanticModel.</target>
<note />
</trans-unit>
<trans-unit id="NumberOfTypeParametersAndArgumentsMustMatch">
<source>the number of type parameters and arguments should be the same</source>
<target state="translated">Число типа параметров и аргументов должно быть одинаковым.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResourceInModule">
<source>Cannot link resource files when building a module</source>
<target state="translated">Не удается связать файлы ресурсов при сборке модуля.</target>
<note />
</trans-unit>
<trans-unit id="NotAVbSymbol">
<source>Not a VB symbol.</source>
<target state="translated">Не символ VB.</target>
<note />
</trans-unit>
<trans-unit id="ElementsCannotBeNull">
<source>Elements cannot be null.</source>
<target state="translated">Элементы не могут иметь значение Null.</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause">
<source>Unused import clause.</source>
<target state="translated">Неиспользуемое предложение import.</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement">
<source>Unused import statement.</source>
<target state="translated">Неиспользуемый оператор import.</target>
<note />
</trans-unit>
<trans-unit id="WrongSemanticModelType">
<source>Expected a {0} SemanticModel.</source>
<target state="translated">Требуется {0} SemanticModel.</target>
<note />
</trans-unit>
<trans-unit id="PositionNotWithinTree">
<source>Position must be within span of the syntax tree.</source>
<target state="translated">Позиция должна находиться в диапазоне синтаксического дерева.</target>
<note />
</trans-unit>
<trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation">
<source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source>
<target state="translated">Предполагаемый синтаксический узел не может принадлежать синтаксическому дереву из текущей компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ChainingSpeculativeModelIsNotSupported">
<source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source>
<target state="translated">Построение цепочки наблюдающей семантической модели не поддерживается. Необходимо создать наблюдающую модель из ненаблюдающей ParentModel.</target>
<note />
</trans-unit>
<trans-unit id="IDS_ToolName">
<source>Microsoft (R) Visual Basic Compiler</source>
<target state="translated">Компилятор Microsoft (R) Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine1">
<source>{0} version {1}</source>
<target state="translated">{0} версии {1}</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine2">
<source>Copyright (C) Microsoft Corporation. All rights reserved.</source>
<target state="translated">© Корпорация Майкрософт (Microsoft Corporation). Все права защищены.</target>
<note />
</trans-unit>
<trans-unit id="IDS_LangVersions">
<source>Supported language versions:</source>
<target state="translated">Поддерживаемые языковые версии:</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong">
<source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">Слишком длинное локальное имя "{0}" для PDB. Попробуйте сократить или компилировать без /debug.</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong_Title">
<source>Local name is too long for PDB</source>
<target state="translated">Локальное имя слишком длинное для PDB-файла</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong">
<source>Import string '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">Импорт строки "{0}" имеет слишком много знаков для PDB. Попробуйте сократить или компилировать без /debug.</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong_Title">
<source>Import string is too long for PDB</source>
<target state="translated">Строка импорта слишком длинная для PDB</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter">
<source>XML comment has a tag with a 'cref' attribute '{0}' that bound to a type parameter. Use the <typeparamref> tag instead.</source>
<target state="translated">Комментарий XML содержит тег с атрибутом "cref" "{0}", который привязан к типу параметра. Вместо этого следует использовать тег <typeparamref>.</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter_Title">
<source>XML comment has a tag with a 'cref' attribute that bound to a type parameter</source>
<target state="translated">Комментарий XML содержит тег с атрибутом cref, который привязан к параметру типа</target>
<note />
</trans-unit>
<trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage">
<source>Linked netmodule metadata must provide a full PE image: '{0}'.</source>
<target state="translated">Связанные метаданные netmodule должны обеспечивать полный образ PE: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated">
<source>An instance of analyzer {0} cannot be created from {1} : {2}.</source>
<target state="translated">Экземпляр анализатора {0} невозможно создать из {1} : {2}"</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated_Title">
<source>Instance of analyzer cannot be created</source>
<target state="translated">Невозможно создать экземпляр анализатора</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly">
<source>The assembly {0} does not contain any analyzers.</source>
<target state="translated">Сборка {0} не содержит анализаторов.</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly_Title">
<source>Assembly does not contain any analyzers</source>
<target state="translated">Сборка не содержит анализаторов</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer">
<source>Unable to load analyzer assembly {0} : {1}.</source>
<target state="translated">Не удается загрузить анализатор сборки{0}: {1}.</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer_Title">
<source>Unable to load analyzer assembly</source>
<target state="translated">Не удалось загрузить сборку анализатора</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer">
<source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source>
<target state="translated">Пропуск некоторых типов в сборке анализатора {0} из-за исключения ReflectionTypeLoadException: {1}.</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title">
<source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source>
<target state="translated">Пропуск загрузки типов в сборке анализатора, завершившихся сбоем из-за ReflectionTypeLoadException</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReadRulesetFile">
<source>Error reading ruleset file {0} - {1}</source>
<target state="translated">Ошибка при чтении файла с набором правил {0} — {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PlatformDoesntSupport">
<source>{0} is not supported in current project type.</source>
<target state="translated">{0} не поддерживается в текущем типе проекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantUseRequiredAttribute">
<source>The RequiredAttribute attribute is not permitted on Visual Basic types.</source>
<target state="translated">Атрибут RequiredAttribute не разрешен для типов Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncodinglessSyntaxTree">
<source>Cannot emit debug information for a source text without encoding.</source>
<target state="translated">Не удается выдать отладочную информацию для исходного текста без кодировки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatSpecifier">
<source>'{0}' is not a valid format specifier</source>
<target state="translated">"{0}" не является допустимым описателем формата.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPreprocessorConstantType">
<source>Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed.</source>
<target state="translated">Константа препроцессора "{0}" типа "{1}" не поддерживается, допускаются только примитивные типы.</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedWarningKeyword">
<source>'Warning' expected.</source>
<target state="translated">'Требуется "Warning".</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotBeMadeNullable1">
<source>'{0}' cannot be made nullable.</source>
<target state="translated">"{0}" не может быть стать параметром, допускающим NULL.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConditionalWithRef">
<source>Leading '?' can only appear inside a 'With' statement, but not inside an object member initializer.</source>
<target state="translated">Символ "?" в начале может находиться только внутри оператора "With", но не внутри инициализатора участников объекта.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullPropagatingOpInExpressionTree">
<source>A null propagating operator cannot be converted into an expression tree.</source>
<target state="translated">Распространяющий NULL оператор невозможно преобразовать в дерево выражения.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongOrComplexExpression">
<source>An expression is too long or complex to compile</source>
<target state="translated">Выражение слишком длинное или сложное для компиляции</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionDoesntHaveName">
<source>This expression does not have a name.</source>
<target state="translated">Выражение не имеет имени.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNameOfSubExpression">
<source>This sub-expression cannot be used inside NameOf argument.</source>
<target state="translated">Невозможно использовать подвыражение в аргументе NameOf.</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodTypeArgsUnexpected">
<source>Method type arguments unexpected.</source>
<target state="translated">Неожиданные аргументы типа метода.</target>
<note />
</trans-unit>
<trans-unit id="NoNoneSearchCriteria">
<source>SearchCriteria is expected.</source>
<target state="translated">Ожидается SearchCriteria.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCulture">
<source>Assembly culture strings may not contain embedded NUL characters.</source>
<target state="translated">Строки языка и региональных параметров сборки могут не содержать встроенных символов NULL.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InReferencedAssembly">
<source>There is an error in a referenced assembly '{0}'.</source>
<target state="translated">Ошибка в связанной сборке "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationFormatWhitespace">
<source>Format specifier may not contain trailing whitespace.</source>
<target state="translated">Указатель формата может не содержать пробел в конце.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationAlignmentOutOfRange">
<source>Alignment value is outside of the supported range.</source>
<target state="translated">Значение выравнивания находится вне диапазона поддерживаемых значений.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolatedStringFactoryError">
<source>There were one or more errors emitting a call to {0}.{1}. Method or its return type may be missing or malformed.</source>
<target state="translated">Возникла одна или несколько ошибок при создании вызова к {0}.{1}. Метод или его тип возвращаемых данных может быть не задан или неправильно сформирован.</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause_Title">
<source>Unused import clause</source>
<target state="translated">Неиспользуемое предложение import</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement_Title">
<source>Unused import statement</source>
<target state="translated">Неиспользуемый оператор import</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantStringTooLong">
<source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source>
<target state="translated">Длина строковой константы, полученной в результате объединения, превышает значение System.Int32.MaxValue. Попробуйте разделить строку на несколько констант.</target>
<note />
</trans-unit>
<trans-unit id="ERR_LanguageVersion">
<source>Visual Basic {0} does not support {1}.</source>
<target state="translated">Visual Basic {0} не поддерживает {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPdbData">
<source>Error reading debug information for '{0}'</source>
<target state="translated">Ошибка чтения отладочной информации для "{0}"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ArrayLiterals">
<source>array literal expressions</source>
<target state="translated">литеральные выражения массива</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AsyncExpressions">
<source>async methods or lambdas</source>
<target state="translated">Асинхронные методы или лямбда-выражения</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AutoProperties">
<source>auto-implemented properties</source>
<target state="translated">автоматически внедренные свойства</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ReadonlyAutoProperties">
<source>readonly auto-implemented properties</source>
<target state="translated">автоматически реализуемые свойства только для чтения</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CoContraVariance">
<source>variance</source>
<target state="translated">расхождение</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CollectionInitializers">
<source>collection initializers</source>
<target state="translated">инициализаторы коллекции</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_GlobalNamespace">
<source>declaring a Global namespace</source>
<target state="translated">объявление глобального пространства имен</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Iterators">
<source>iterators</source>
<target state="translated">итераторы</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuation">
<source>implicit line continuation</source>
<target state="translated">неявное продолжение строки</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_StatementLambdas">
<source>multi-line lambda expressions</source>
<target state="translated">многострочные лямбда-выражения</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_SubLambdas">
<source>'Sub' lambda expressions</source>
<target state="translated">'Лямбда-выражения "Sub"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NullPropagatingOperator">
<source>null conditional operations</source>
<target state="translated">условные операции со значением "null"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NameOfExpressions">
<source>'nameof' expressions</source>
<target state="translated">'выражения "nameof"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_RegionsEverywhere">
<source>region directives within method bodies or regions crossing boundaries of declaration blocks</source>
<target state="translated">директивы region в телах методов или регионах, пересекающих границы блоков объявлений</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_MultilineStringLiterals">
<source>multiline string literals</source>
<target state="translated">строковые литералы из нескольких строк</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CObjInAttributeArguments">
<source>CObj in attribute arguments</source>
<target state="translated">CObj в аргументах атрибута</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuationComments">
<source>line continuation comments</source>
<target state="translated">комментарии продолжения строки</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_TypeOfIsNot">
<source>TypeOf IsNot expression</source>
<target state="translated">Выражение IsNot TypeOf</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_YearFirstDateLiterals">
<source>year-first date literals</source>
<target state="translated">литералы даты с годом на первом месте</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_WarningDirectives">
<source>warning directives</source>
<target state="translated">директивы warning</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialModules">
<source>partial modules</source>
<target state="translated">частичные модули</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialInterfaces">
<source>partial interfaces</source>
<target state="translated">частичные интерфейсы</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite">
<source>implementing read-only or write-only property with read-write property</source>
<target state="translated">реализация свойства только для чтения или только для записи с помощью свойства для чтения и записи</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_DigitSeparators">
<source>digit separators</source>
<target state="translated">цифровые разделители</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_BinaryLiterals">
<source>binary literals</source>
<target state="translated">двоичные литералы</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Tuples">
<source>tuples</source>
<target state="translated">кортежи</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PrivateProtected">
<source>Private Protected</source>
<target state="translated">Частный защищенный</target>
<note />
</trans-unit>
<trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition">
<source>Debug entry point must be a definition of a method declared in the current compilation.</source>
<target state="translated">Точкой входа отладки должно быть определение метода, объявленное в текущей компиляции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPathMap">
<source>The pathmap option was incorrectly formatted.</source>
<target state="translated">Неправильный формат параметра pathmap.</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeIsNotASubmission">
<source>Syntax tree should be created from a submission.</source>
<target state="translated">Дерево синтаксиса должно быть создано из отправки.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyUserStrings">
<source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string or XML literals.</source>
<target state="translated">Объединенная длина пользовательских строк, используемых программой, превышает допустимый предел. Попробуйте сократить использование строковых литералов или XML-литералов.</target>
<note />
</trans-unit>
<trans-unit id="ERR_PeWritingFailure">
<source>An error occurred while writing the output file: {0}</source>
<target state="translated">Произошла ошибка при записи выходного файла: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionMustBeAbsolutePath">
<source>Option '{0}' must be an absolute path.</source>
<target state="translated">Параметр "{0}" должен быть абсолютным путем.</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceLinkRequiresPdb">
<source>/sourcelink switch is only supported when emitting PDB.</source>
<target state="translated">Параметр /sourcelink поддерживается только при создании данных формата PDB.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleDuplicateElementName">
<source>Tuple element names must be unique.</source>
<target state="translated">Имена элементов кортежа должны быть уникальными.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch">
<source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source>
<target state="translated">Имя элемента кортежа "{0}" игнорируется, так как целевым типом "{1}" задано другое имя либо имя не задано.</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch_Title">
<source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source>
<target state="translated">Имя элемента кортежа игнорируется, так как целевым объектом назначения задано другое имя либо имя не задано.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementName">
<source>Tuple element name '{0}' is only allowed at position {1}.</source>
<target state="translated">Имя элемента кортежа "{0}" допускается только в позиции {1}.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementNameAnyPosition">
<source>Tuple element name '{0}' is disallowed at any position.</source>
<target state="translated">Имя элемента кортежа "{0}" не допускается ни в одной позиции.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleTooFewElements">
<source>Tuple must contain at least two elements.</source>
<target state="translated">Кортеж должен содержать по меньшей мере два элемента.</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleElementNamesAttributeMissing">
<source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source>
<target state="translated">Невозможно определить класс или элемент, использующий кортежи, так как не удалось найти необходимый тип компилятора ({0}). Отсутствует ссылка?</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExplicitTupleElementNamesAttribute">
<source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source>
<target state="translated">Невозможно явным образом добавить ссылку на "System.Runtime.CompilerServices.TupleElementNamesAttribute". Используйте синтаксис кортежа для определения имен кортежа.</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefReturningCallInExpressionTree">
<source>An expression tree may not contain a call to a method or property that returns by reference.</source>
<target state="translated">Дерево выражений не может содержать вызов метода или свойства, которые возвращают данные по ссылке.</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedWithoutPdb">
<source>/embed switch is only supported when emitting a PDB.</source>
<target state="translated">Параметр /embed поддерживается только при создании PDB-файла.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInstrumentationKind">
<source>Invalid instrumentation kind: {0}</source>
<target state="translated">Недопустимый тип инструментирования: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DocFileGen">
<source>Error writing to XML documentation file: {0}</source>
<target state="translated">Ошибка при записи в XML-файл документации: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAssemblyName">
<source>Invalid assembly name: {0}</source>
<target state="translated">Недопустимое имя сборки: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeForwardedToMultipleAssemblies">
<source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source>
<target state="translated">Модуль "{0}" в сборке "{1}" перенаправляет тип "{2}" в несколько сборок: "{3}" и "{4}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_Merge_conflict_marker_encountered">
<source>Merge conflict marker encountered</source>
<target state="translated">Встретилась отметка о конфликте слияния</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoRefOutWhenRefOnly">
<source>Do not use refout when using refonly.</source>
<target state="translated">Не используйте refout при использовании refonly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly">
<source>Cannot compile net modules when using /refout or /refonly.</source>
<target state="translated">Не удается скомпилировать сетевые модули при использовании /refout или /refonly.</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNonTrailingNamedArgument">
<source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source>
<target state="translated">Именованный аргумент "{0}" используется не на своем месте, но за ним следует неименованный аргумент</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDocumentationMode">
<source>Provided documentation mode is unsupported or invalid: '{0}'.</source>
<target state="translated">Указанный режим документации не поддерживается или недопустим: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLanguageVersion">
<source>Provided language version is unsupported or invalid: '{0}'.</source>
<target state="translated">Указанная версия языка не поддерживается или недопустима: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSourceCodeKind">
<source>Provided source code kind is unsupported or invalid: '{0}'</source>
<target state="translated">Указанный тип исходного кода не поддерживается или недопустим: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleInferredNamesNotAvailable">
<source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source>
<target state="translated">Имя элемента кортежа "{0}" является выведенным. Для обращения к элементу по выведенному имени используйте версию языка {1} или более позднюю.</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental">
<source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">"{0}" предназначен только для оценки и может быть изменен или удален в будущих обновлениях.</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental_Title">
<source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">Тип предназначен только для оценки и может быть изменен или удален в будущих обновлениях.</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInfo">
<source>Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}'</source>
<target state="translated">Не удается считать сведения об отладке метода "{0}" (маркер 0x{1}) из сборки "{2}".</target>
<note />
</trans-unit>
<trans-unit id="IConversionExpressionIsNotVisualBasicConversion">
<source>{0} is not a valid Visual Basic conversion expression</source>
<target state="translated">{0} не является допустимым выражением преобразования Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="IArgumentIsNotVisualBasicArgument">
<source>{0} is not a valid Visual Basic argument</source>
<target state="translated">{0} не является допустимым аргументом Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LeadingDigitSeparator">
<source>leading digit separator</source>
<target state="translated">разделитель начальных цифр</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleResolutionAmbiguous3">
<source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source>
<target state="translated">Предопределенный тип "{0}" объявлен в нескольких сборках, на которые имеются ссылки: "{1}" и "{2}"</target>
<note />
</trans-unit>
<trans-unit id="ICompoundAssignmentOperationIsNotVisualBasicCompoundAssignment">
<source>{0} is not a valid Visual Basic compound assignment operation</source>
<target state="translated">{0} не является допустимой операцией составного назначения Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHashAlgorithmName">
<source>Invalid hash algorithm name: '{0}'</source>
<target state="translated">Недопустимое имя хэш-алгоритма: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InterpolatedStrings">
<source>interpolated strings</source>
<target state="translated">интерполированные строки</target>
<note />
</trans-unit>
<trans-unit id="FTL_InvalidInputFileName">
<source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source>
<target state="translated">Имя файла "{0}" пустое, содержит недопустимые символы, имеет имя диска без абсолютного пути или слишком длинное.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB">
<source>'{0}' is not supported in VB.</source>
<target state="translated">"{0}" не поддерживается в VB.</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB_Title">
<source>Attribute is not supported in VB</source>
<target state="translated">Атрибут не поддерживается в VB</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/TestUtilities/Async/WaitHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Windows;
using System.Windows.Threading;
namespace Roslyn.Test.Utilities
{
public static class WaitHelper
{
public static void WaitForDispatchedOperationsToComplete(DispatcherPriority priority)
{
Action action = delegate { };
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
new FrameworkElement().Dispatcher.Invoke(action, priority);
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Windows;
using System.Windows.Threading;
namespace Roslyn.Test.Utilities
{
public static class WaitHelper
{
public static void WaitForDispatchedOperationsToComplete(DispatcherPriority priority)
{
Action action = delegate { };
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
new FrameworkElement().Dispatcher.Invoke(action, priority);
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/PlaceholderLocalSymbol.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.Collections.ObjectModel
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend MustInherit Class PlaceholderLocalSymbol
Inherits EELocalSymbolBase
Private ReadOnly _name As String
Friend ReadOnly DisplayName As String
Friend Sub New(method As MethodSymbol, name As String, displayName As String, type As TypeSymbol)
MyBase.New(method, type)
_name = name
Me.DisplayName = displayName
End Sub
Friend Overloads Shared Function Create(
typeNameDecoder As TypeNameDecoder(Of PEModuleSymbol, TypeSymbol),
containingMethod As MethodSymbol,
[alias] As [Alias]) As PlaceholderLocalSymbol
Dim typeName = [alias].Type
Debug.Assert(typeName.Length > 0)
Dim type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName)
Debug.Assert(type IsNot Nothing)
Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing
Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing
CustomTypeInfo.Decode([alias].CustomTypeInfoId, [alias].CustomTypeInfo, dynamicFlags, tupleElementNames)
type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNames.AsImmutableOrNull())
Dim name = [alias].FullName
Dim displayName = [alias].Name
Select Case [alias].Kind
Case DkmClrAliasKind.Exception
Return New ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName)
Case DkmClrAliasKind.StowedException
Return New ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName)
Case DkmClrAliasKind.ReturnValue
Dim index As Integer = 0
PseudoVariableUtilities.TryParseReturnValueIndex(name, index)
Return New ReturnValueLocalSymbol(containingMethod, name, displayName, type, index)
Case DkmClrAliasKind.ObjectId
Return New ObjectIdLocalSymbol(containingMethod, type, name, displayName, isReadOnly:=True)
Case DkmClrAliasKind.Variable
Return New ObjectIdLocalSymbol(containingMethod, type, name, displayName, isReadOnly:=False)
Case Else
Throw ExceptionUtilities.UnexpectedValue([alias].Kind)
End Select
End Function
Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind
Get
Return LocalDeclarationKind.Variable
End Get
End Property
Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property IdentifierLocation As Location
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return NoLocations
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As EELocalSymbolBase
' Pseudo-variables should be rewritten in PlaceholderLocalRewriter
' rather than copied as locals to the target method.
Throw ExceptionUtilities.Unreachable
End Function
Friend MustOverride Overrides ReadOnly Property IsReadOnly As Boolean
Friend MustOverride Function RewriteLocal(
compilation As VisualBasicCompilation,
container As EENamedTypeSymbol,
syntax As SyntaxNode,
isLValue As Boolean,
diagnostics As DiagnosticBag) As BoundExpression
Friend Shared Function ConvertToLocalType(
compilation As VisualBasicCompilation,
expr As BoundExpression,
type As TypeSymbol,
diagnostics As DiagnosticBag) As BoundExpression
Dim syntax = expr.Syntax
Dim exprType = expr.Type
Dim conversionKind As ConversionKind
If type.IsErrorType() Then
diagnostics.Add(type.GetUseSiteInfo().DiagnosticInfo, syntax.GetLocation())
conversionKind = Nothing
ElseIf exprType.IsErrorType() Then
diagnostics.Add(exprType.GetUseSiteInfo().DiagnosticInfo, syntax.GetLocation())
conversionKind = Nothing
Else
Dim useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) = Nothing
Dim pair = Conversions.ClassifyConversion(exprType, type, useSiteInfo)
Debug.Assert(useSiteInfo.Diagnostics Is Nothing, "If this happens, please add a test")
diagnostics.Add(syntax, useSiteInfo.Diagnostics)
Debug.Assert(pair.Value Is Nothing) ' Conversion method.
conversionKind = pair.Key
End If
Return New BoundDirectCast(
syntax,
expr,
conversionKind,
type,
hasErrors:=Not Conversions.ConversionExists(conversionKind)).MakeCompilerGenerated()
End Function
Friend Shared Function GetIntrinsicMethod(compilation As VisualBasicCompilation, methodName As String) As MethodSymbol
Dim type = compilation.GetTypeByMetadataName(ExpressionCompilerConstants.IntrinsicAssemblyTypeMetadataName)
Dim members = type.GetMembers(methodName)
Debug.Assert(members.Length = 1)
Return DirectCast(members(0), MethodSymbol)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.VisualStudio.Debugger.Clr
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend MustInherit Class PlaceholderLocalSymbol
Inherits EELocalSymbolBase
Private ReadOnly _name As String
Friend ReadOnly DisplayName As String
Friend Sub New(method As MethodSymbol, name As String, displayName As String, type As TypeSymbol)
MyBase.New(method, type)
_name = name
Me.DisplayName = displayName
End Sub
Friend Overloads Shared Function Create(
typeNameDecoder As TypeNameDecoder(Of PEModuleSymbol, TypeSymbol),
containingMethod As MethodSymbol,
[alias] As [Alias]) As PlaceholderLocalSymbol
Dim typeName = [alias].Type
Debug.Assert(typeName.Length > 0)
Dim type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName)
Debug.Assert(type IsNot Nothing)
Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing
Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing
CustomTypeInfo.Decode([alias].CustomTypeInfoId, [alias].CustomTypeInfo, dynamicFlags, tupleElementNames)
type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNames.AsImmutableOrNull())
Dim name = [alias].FullName
Dim displayName = [alias].Name
Select Case [alias].Kind
Case DkmClrAliasKind.Exception
Return New ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName)
Case DkmClrAliasKind.StowedException
Return New ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName)
Case DkmClrAliasKind.ReturnValue
Dim index As Integer = 0
PseudoVariableUtilities.TryParseReturnValueIndex(name, index)
Return New ReturnValueLocalSymbol(containingMethod, name, displayName, type, index)
Case DkmClrAliasKind.ObjectId
Return New ObjectIdLocalSymbol(containingMethod, type, name, displayName, isReadOnly:=True)
Case DkmClrAliasKind.Variable
Return New ObjectIdLocalSymbol(containingMethod, type, name, displayName, isReadOnly:=False)
Case Else
Throw ExceptionUtilities.UnexpectedValue([alias].Kind)
End Select
End Function
Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind
Get
Return LocalDeclarationKind.Variable
End Get
End Property
Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property IdentifierLocation As Location
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return NoLocations
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As EELocalSymbolBase
' Pseudo-variables should be rewritten in PlaceholderLocalRewriter
' rather than copied as locals to the target method.
Throw ExceptionUtilities.Unreachable
End Function
Friend MustOverride Overrides ReadOnly Property IsReadOnly As Boolean
Friend MustOverride Function RewriteLocal(
compilation As VisualBasicCompilation,
container As EENamedTypeSymbol,
syntax As SyntaxNode,
isLValue As Boolean,
diagnostics As DiagnosticBag) As BoundExpression
Friend Shared Function ConvertToLocalType(
compilation As VisualBasicCompilation,
expr As BoundExpression,
type As TypeSymbol,
diagnostics As DiagnosticBag) As BoundExpression
Dim syntax = expr.Syntax
Dim exprType = expr.Type
Dim conversionKind As ConversionKind
If type.IsErrorType() Then
diagnostics.Add(type.GetUseSiteInfo().DiagnosticInfo, syntax.GetLocation())
conversionKind = Nothing
ElseIf exprType.IsErrorType() Then
diagnostics.Add(exprType.GetUseSiteInfo().DiagnosticInfo, syntax.GetLocation())
conversionKind = Nothing
Else
Dim useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) = Nothing
Dim pair = Conversions.ClassifyConversion(exprType, type, useSiteInfo)
Debug.Assert(useSiteInfo.Diagnostics Is Nothing, "If this happens, please add a test")
diagnostics.Add(syntax, useSiteInfo.Diagnostics)
Debug.Assert(pair.Value Is Nothing) ' Conversion method.
conversionKind = pair.Key
End If
Return New BoundDirectCast(
syntax,
expr,
conversionKind,
type,
hasErrors:=Not Conversions.ConversionExists(conversionKind)).MakeCompilerGenerated()
End Function
Friend Shared Function GetIntrinsicMethod(compilation As VisualBasicCompilation, methodName As String) As MethodSymbol
Dim type = compilation.GetTypeByMetadataName(ExpressionCompilerConstants.IntrinsicAssemblyTypeMetadataName)
Dim members = type.GetMembers(methodName)
Debug.Assert(members.Length = 1)
Return DirectCast(members(0), MethodSymbol)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ja.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="ja" original="../VBFeaturesResources.resx">
<body>
<trans-unit id="Add_Await">
<source>Add Await</source>
<target state="translated">Await の追加</target>
<note />
</trans-unit>
<trans-unit id="Add_Await_and_ConfigureAwaitFalse">
<source>Add Await and 'ConfigureAwait(false)'</source>
<target state="translated">Await と 'ConfigureAwait(false)' の追加</target>
<note />
</trans-unit>
<trans-unit id="Add_Obsolete">
<source>Add <Obsolete></source>
<target state="translated"><Obsolete> の追加</target>
<note />
</trans-unit>
<trans-unit id="Add_missing_Imports">
<source>Add missing Imports</source>
<target state="translated">欠落している Import の追加</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Add_Shadows">
<source>Add 'Shadows'</source>
<target state="translated">'Shadows' の追加</target>
<note>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Imports_directive_placement_preferences">
<source>Apply Imports directive placement preferences</source>
<target state="translated">Import ディレクティブの配置設定を適用する</target>
<note>{Locked="Import"} "Import" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Me_qualification_preferences">
<source>Apply Me qualification preferences</source>
<target state="translated">Me 修飾設定を適用する</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Change_to_DirectCast">
<source>Change to 'DirectCast'</source>
<target state="translated">'DirectCast' に変更</target>
<note />
</trans-unit>
<trans-unit id="Change_to_TryCast">
<source>Change to 'TryCast'</source>
<target state="translated">'TryCast' に変更</target>
<note />
</trans-unit>
<trans-unit id="Insert_0">
<source>Insert '{0}'.</source>
<target state="translated">{0} の挿入</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement1">
<source>Delete the '{0}' statement.</source>
<target state="translated">'{0}' ステートメントを削除します。</target>
<note />
</trans-unit>
<trans-unit id="Create_event_0_in_1">
<source>Create event {0} in {1}</source>
<target state="translated">イベント {0} を {1} に作成する</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_End_Property_statement">
<source>Insert the missing 'End Property' statement.</source>
<target state="translated">不足している ' End Property' ステートメントを挿入します。</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_0">
<source>Insert the missing '{0}'.</source>
<target state="translated">不足している '{0}' を挿入します。</target>
<note />
</trans-unit>
<trans-unit id="Inline_temporary_variable">
<source>Inline temporary variable</source>
<target state="translated">インラインの一時変数</target>
<note />
</trans-unit>
<trans-unit id="Conflict_s_detected">
<source>Conflict(s) detected.</source>
<target state="translated">競合が検出されました。</target>
<note />
</trans-unit>
<trans-unit id="Introduce_Using_statement">
<source>Introduce 'Using' statement</source>
<target state="translated">’Using’ ステートメントの導入</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Make_0_inheritable">
<source>Make '{0}' inheritable</source>
<target state="translated">'{0}' を継承可能にします</target>
<note />
</trans-unit>
<trans-unit id="Make_private_field_ReadOnly_when_possible">
<source>Make private field ReadOnly when possible</source>
<target state="translated">可能な場合、プライベート フィールドを ReadOnly にする</target>
<note>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Move_the_0_statement_to_line_1">
<source>Move the '{0}' statement to line {1}.</source>
<target state="translated">'{0}' ステートメントを行 {1} に移動します。</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement2">
<source>Delete the '{0}' statement.</source>
<target state="translated">'{0}' ステートメントを削除します。</target>
<note />
</trans-unit>
<trans-unit id="Multiple_Types">
<source><Multiple Types></source>
<target state="translated"><複数の種類></target>
<note />
</trans-unit>
<trans-unit id="Organize_Imports">
<source>Organize Imports</source>
<target state="translated">Import の整理</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Remove_shared_keyword_from_module_member">
<source>Remove 'Shared' keyword from Module member</source>
<target state="translated">モジュール メンバーから 'Shared' キーワードを削除</target>
<note>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Shared_constructor">
<source>Shared constructor</source>
<target state="translated">共有コンストラクター</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_new_field">
<source>Type a name here to declare a new field.</source>
<target state="translated">新しいフィールドを宣言するには、ここに名前を入力します。</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">注: 潜在的な干渉を避けるため、スペースの補完は無効になっています。リストから名前を挿入するには、タブを使用します。</target>
<note />
</trans-unit>
<trans-unit id="_0_Events">
<source>({0} Events)</source>
<target state="translated">({0} イベント)</target>
<note />
</trans-unit>
<trans-unit id="new_field">
<source><new field></source>
<target state="translated"><新しいフィールド></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value">
<source>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</source>
<target state="translated">パラメーターを宣言するには、ここに名前を入力します。先行するキーワードが使用されない場合は、'ByVal' と見なされ、引数が値によって渡されます。</target>
<note />
</trans-unit>
<trans-unit id="parameter_name">
<source><parameter name></source>
<target state="translated"><パラメーター名></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used">
<source>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</source>
<target state="translated">列の新しい名前 (名前の後に '=' が続く) を入力します。これを入力しない場合、元の列名が使用されます。</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name">
<source>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</source>
<target state="translated">注: タブを使用すると自動補完されます。新しい名前への干渉を避けるために、スペースの補完は無効になっています。</target>
<note />
</trans-unit>
<trans-unit id="result_alias">
<source><result alias></source>
<target state="translated"><結果のエイリアス></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_variable_name">
<source>Type a new variable name</source>
<target state="translated">新しい変数の名前を入力します</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">注: 潜在的な干渉を避けるため、スペースと '=' の補完は無効になっています。リストから名前を挿入するには、タブを使用します。</target>
<note />
</trans-unit>
<trans-unit id="new_resource">
<source><new resource></source>
<target state="translated"><新しいリソース></target>
<note />
</trans-unit>
<trans-unit id="AddHandler_statement">
<source>AddHandler statement</source>
<target state="translated">AddHandler ステートメント</target>
<note />
</trans-unit>
<trans-unit id="RemoveHandler_statement">
<source>RemoveHandler statement</source>
<target state="translated">RemoveHandler ステートメント</target>
<note />
</trans-unit>
<trans-unit id="_0_function">
<source>{0} function</source>
<target state="translated">{0} 関数</target>
<note />
</trans-unit>
<trans-unit id="CType_function">
<source>CType function</source>
<target state="translated">CType 関数</target>
<note />
</trans-unit>
<trans-unit id="DirectCast_function">
<source>DirectCast function</source>
<target state="translated">DirectCast 関数</target>
<note />
</trans-unit>
<trans-unit id="TryCast_function">
<source>TryCast function</source>
<target state="translated">TryCast 関数</target>
<note />
</trans-unit>
<trans-unit id="GetType_function">
<source>GetType function</source>
<target state="translated">GetType 関数</target>
<note />
</trans-unit>
<trans-unit id="GetXmlNamespace_function">
<source>GetXmlNamespace function</source>
<target state="translated">GetXmlNamespace 関数</target>
<note />
</trans-unit>
<trans-unit id="Mid_statement">
<source>Mid statement</source>
<target state="translated">Mid ステートメント</target>
<note />
</trans-unit>
<trans-unit id="Fix_Incorrect_Function_Return_Type">
<source>Fix Incorrect Function Return Type</source>
<target state="translated">無効な関数の戻り値の型を修正する</target>
<note />
</trans-unit>
<trans-unit id="Simplify_name_0">
<source>Simplify name '{0}'</source>
<target state="translated">名前 '{0}' の単純化</target>
<note />
</trans-unit>
<trans-unit id="Simplify_member_access_0">
<source>Simplify member access '{0}'</source>
<target state="translated">メンバーのアクセス '{0}' を単純化します</target>
<note />
</trans-unit>
<trans-unit id="Remove_Me_qualification">
<source>Remove 'Me' qualification</source>
<target state="translated">修飾子 'Me' を削除します</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified</source>
<target state="translated">名前を簡素化できます</target>
<note />
</trans-unit>
<trans-unit id="can_t_determine_valid_range_of_statements_to_extract_out">
<source>can't determine valid range of statements to extract out</source>
<target state="translated">抽出するステートメントの有効な範囲を決定できません</target>
<note />
</trans-unit>
<trans-unit id="Not_all_code_paths_return">
<source>Not all code paths return</source>
<target state="translated">返されないコード パスがあります</target>
<note />
</trans-unit>
<trans-unit id="contains_invalid_selection">
<source>contains invalid selection</source>
<target state="translated">無効な選択が含まれています</target>
<note />
</trans-unit>
<trans-unit id="the_selection_contains_syntactic_errors">
<source>the selection contains syntactic errors</source>
<target state="translated">選択範囲に構文エラーが含まれています</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_crossed_over_preprocessors">
<source>Selection can't be crossed over preprocessors</source>
<target state="translated">選択範囲はプリプロセッサと交差することはできません</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_contain_throw_without_enclosing_catch_block">
<source>Selection can't contain throw without enclosing catch block</source>
<target state="translated">選択範囲に外側の catch ブロックのない throw を含めることはできません</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_parts_of_constant_initializer_expression">
<source>Selection can't be parts of constant initializer expression</source>
<target state="translated">選択範囲は定数の初期化子式の一部にすることはできません</target>
<note />
</trans-unit>
<trans-unit id="Argument_used_for_ByRef_parameter_can_t_be_extracted_out">
<source>Argument used for ByRef parameter can't be extracted out</source>
<target state="translated">ByRef パラメーターに対して使用される引数は抽出できません</target>
<note />
</trans-unit>
<trans-unit id="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection">
<source>all static local usages defined in the selection must be included in the selection</source>
<target state="translated">選択範囲で定義されているすべてのスタティック ローカルの使用法は、選択範囲に含める必要があります</target>
<note />
</trans-unit>
<trans-unit id="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement">
<source>Implicit member access can't be included in the selection without containing statement</source>
<target state="translated">暗黙的なメンバー アクセスは、ステートメントを含まずに選択に入れることはできません</target>
<note />
</trans-unit>
<trans-unit id="Selection_must_be_part_of_executable_statements">
<source>Selection must be part of executable statements</source>
<target state="translated">選択範囲は実行可能なステートメントの一部にする必要があります</target>
<note />
</trans-unit>
<trans-unit id="next_statement_control_variable_doesn_t_have_matching_declaration_statement">
<source>next statement control variable doesn't have matching declaration statement</source>
<target state="translated">次のステートメントの制御変数に一致する宣言ステートメントがありません</target>
<note />
</trans-unit>
<trans-unit id="Selection_doesn_t_contain_any_valid_node">
<source>Selection doesn't contain any valid node</source>
<target state="translated">選択範囲に有効なノードが含まれていません</target>
<note />
</trans-unit>
<trans-unit id="no_valid_statement_range_to_extract_out">
<source>no valid statement range to extract out</source>
<target state="translated">抽出する有効なステートメントの範囲がありません</target>
<note />
</trans-unit>
<trans-unit id="Invalid_selection">
<source>Invalid selection</source>
<target state="translated">無効な選択</target>
<note />
</trans-unit>
<trans-unit id="Deprecated">
<source>Deprecated</source>
<target state="translated">非推奨</target>
<note />
</trans-unit>
<trans-unit id="Extension">
<source>Extension</source>
<target state="translated">拡張</target>
<note />
</trans-unit>
<trans-unit id="Awaitable">
<source>Awaitable</source>
<target state="translated">待機可能</target>
<note />
</trans-unit>
<trans-unit id="Awaitable_Extension">
<source>Awaitable, Extension</source>
<target state="translated">待機可能、拡張子</target>
<note />
</trans-unit>
<trans-unit id="new_variable">
<source><new variable></source>
<target state="translated"><新しい変数></target>
<note />
</trans-unit>
<trans-unit id="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName">
<source>Creates a delegate procedure instance that references the specified procedure.
AddressOf <procedureName></source>
<target state="translated">指定されたプロシージャを参照するデリゲート プロシージャ インスタンスを作成します。
AddressOf <procedureName></target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_an_external_procedure_has_another_name_in_its_DLL">
<source>Indicates that an external procedure has another name in its DLL.</source>
<target state="translated">外部プロシージャが DLL の中では別の名前を持つことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2">
<source>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated.
<result> = <expression1> AndAlso <expression2></source>
<target state="translated">2 つの式のショートサーキット論理積を求めます。両方のオペランドが True と評価された場合は True を返します。最初の式が False と評価された場合、2 番目の式は評価されません。
<result> = <expression1> AndAlso <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2">
<source>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated.
<result> = <expression1> And <expression2></source>
<target state="translated">2 つのブール式の場合は論理積、2 つの数値式の場合はビットごとの積を求めます。ブール式の場合、両方の式が True と評価されたときは True を返します。常に両方の式が評価されます。
<result> = <expression1> And <expression2></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default">
<source>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</source>
<target state="translated">Declare ステートメントで使用されます。Ansi 修飾子は Visual Basic がすべての文字列を ANSI 値にマーシャリングし、検索中にその名前を変更せずにプロシージャを調べることを指定します。文字が指定されていない場合の既定値は、ANSI です。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_data_type_in_a_declaration_statement">
<source>Specifies a data type in a declaration statement.</source>
<target state="translated">宣言ステートメントのデータ型を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">ソース ファイルの冒頭にある属性がアセンブリ全体に適用されることを示します。これを示さない場合、属性はクラスやプロパティなどの個別のプログラミング要素にのみ適用されます。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_asynchronous_method_that_can_use_the_Await_operator">
<source>Indicates an asynchronous method that can use the Await operator.</source>
<target state="translated">Await 演算子を使用できる非同期メソッドを示します。</target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails">
<source>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</source>
<target state="translated">Declare ステートメントで使用されます。Auto 修飾子は Visual Basic が .NET Framework の規則に従って文字列をマーシャリングし、実行時プラットフォームの基本文字セットを決定して、最初の検索が失敗した場合には外部プロシージャ名を変更することを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</source>
<target state="translated">呼び出されたプロシージャが、呼び出しコードの引数の基になる値を変更できるように引数を渡すことを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</source>
<target state="translated">呼び出されたプロシージャまたはプロパティが、呼び出しコードの引数の基になる値を変更できないように引数を渡すことを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class">
<source>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</source>
<target state="translated">クラスの名前を宣言し、そのクラスを構成する変数、プロパティ、メソッドの定義を示します。</target>
<note />
</trans-unit>
<trans-unit id="Generates_a_string_concatenation_of_two_expressions">
<source>Generates a string concatenation of two expressions.</source>
<target state="translated">2 つの式の文字列連結を生成します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_defines_one_or_more_constants">
<source>Declares and defines one or more constants.</source>
<target state="translated">1 つ以上の定数を宣言して定義します。</target>
<note />
</trans-unit>
<trans-unit id="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions">
<source>Use 'In' for a type that will only be used for ByVal arguments to functions.</source>
<target state="translated">関数への引数 ByVal としてのみ使用される型には 'In' を使用します。</target>
<note />
</trans-unit>
<trans-unit id="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions">
<source>Use 'Out' for a type that will only be used as a return from functions.</source>
<target state="translated">関数の戻り値としてのみ使用される型には 'Out' を使用します。</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type">
<source>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.
CType(Object As Expression, Object As Type) As Type</source>
<target state="translated">指定されたデータ型、オブジェクト、構造体、クラス、またはインターフェイスに式を明示的に変換した結果を返します。
CType(Object As Expression, Object As Type) As Type</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events">
<source>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</source>
<target state="translated">イベントに対してハンドラーの追加、ハンドラーの削除、イベントの発生に関する追加の特定コードが記述されていることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_reference_to_a_procedure_implemented_in_an_external_file">
<source>Declares a reference to a procedure implemented in an external file.</source>
<target state="translated">外部ファイルに実装されているプロシージャへの参照を宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface">
<source>Identifies a property as the default property of its class, structure, or interface.</source>
<target state="translated">クラス、構造体、またはインターフェイスの既定のプロパティとしてプロパティを識別します。</target>
<note />
</trans-unit>
<trans-unit id="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class">
<source>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</source>
<target state="translated">デリゲートの宣言に使用します。デリゲートとは、型の共有メソッドまたはオブジェクトのインスタンス メソッドを参照する参照型です。変換可能なプロシージャ、またはパラメーターの型と戻り値の型が一致するプロシージャを使用して、このデリゲート クラスのインスタンスを作成できます。</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket">
<source>Declares and allocates storage space for one or more variables.
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</source>
<target state="translated">記憶域を宣言し、1 つ以上の変数に割り当てます。
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_a_floating_point_result">
<source>Divides two numbers and returns a floating-point result.</source>
<target state="translated">2 つの数値を除算して、浮動小数点の結果を返します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_0_block">
<source>Terminates a {0} block.</source>
<target state="translated">{0} ブロックを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_an_0_block">
<source>Terminates an {0} block.</source>
<target state="translated">{0} ブロックを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_a_0_statement">
<source>Terminates the definition of a {0} statement.</source>
<target state="translated">{0} ステートメントの定義を終了します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_0_statement">
<source>Terminates the definition of an {0} statement.</source>
<target state="translated">{0} ステートメントの定義を終了します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_an_enumeration_and_defines_the_values_of_its_members">
<source>Declares an enumeration and defines the values of its members.</source>
<target state="translated">列挙体を宣言し、そのメンバーの値を定義します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are equal. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、両者が等しい場合は True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements">
<source>Used to release array variables and deallocate the memory used for their elements.</source>
<target state="translated">配列変数を解放し、それらの要素に使用されるメモリの割り当てを解除します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_user_defined_event">
<source>Declares a user-defined event.</source>
<target state="translated">ユーザー定義イベントを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure">
<source>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</source>
<target state="translated">Sub プロシージャを終了し、その実行を Sub プロシージャへの呼び出しに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Raises_a_number_to_the_power_of_another_number">
<source>Raises a number to the power of another number.</source>
<target state="translated">数値を別の数値のべき乗値に指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function">
<source>Specifies that the external procedure being referenced in the Declare statement is a Function.</source>
<target state="translated">Declare ステートメントで参照されている外部プロシージャが Function であることを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub">
<source>Specifies that the external procedure being referenced in the Declare statement is a Sub.</source>
<target state="translated">Declare ステートメントで参照されている外部プロシージャを Sub として指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration">
<source>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素が、その宣言を含むアセンブリ内からのみアクセス可能であることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_collection_and_a_range_variable_to_use_in_a_query">
<source>Specifies a collection and a range variable to use in a query.</source>
<target state="translated">クエリで使用するコレクションと範囲変数を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</source>
<target state="translated">Function プロシージャ (呼び出し元のコードに値を返すプロシージャ) を定義する名前、パラメーター、コードを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</source>
<target state="translated">参照型の型引数のみがジェネリック型パラメーターに渡されるように制約します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_constructor_constraint_on_a_generic_type_parameter">
<source>Specifies a constructor constraint on a generic type parameter.</source>
<target state="translated">ジェネリック型パラメーターにコンス トラクター制約を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a value type.</source>
<target state="translated">値型の型引数のみがジェネリック型パラメーターに渡されるように制約します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property">
<source>Declares a Get property procedure that is used to return the current value of a property.</source>
<target state="translated">プロパティの現在の値を返すために使用される Get プロパティ プロシージャを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目より大きい場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目以上の場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_that_a_procedure_handles_a_specified_event">
<source>Declares that a procedure handles a specified event.</source>
<target state="translated">プロシージャが指定されたイベントを処理することを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface">
<source>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</source>
<target state="translated">クラスまたは構造体のメンバーがインターフェイスで定義されているメンバーの実装を提供していることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears">
<source>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</source>
<target state="translated">Implements ステートメントが使用されるクラスまたは構造体の定義に実装する必要のある、1 つ以上のインターフェイス、またはインターフェイス メンバーを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Imports_all_or_specified_elements_of_a_namespace_into_a_file">
<source>Imports all or specified elements of a namespace into a file.</source>
<target state="translated">名前空間のすべてまたは指定された要素をファイルにインポートします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse">
<source>Specifies the group that the loop variable in a For Each statement is to traverse.</source>
<target state="translated">ループ変数が For Each ステートメント内で繰り返し処理するグループを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query">
<source>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</source>
<target state="translated">ループ変数が For Each ステートメントで繰り返し処理するグループを指定するか、クエリ内の範囲変数を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces">
<source>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</source>
<target state="translated">現在のクラスまたはインターフェイスが、属性、変数、プロパティ、プロシージャ、およびイベントを別のクラスまたは一連のインターフェイスから継承するようにします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query">
<source>Specifies the group that the range variable is to traverse in a query.</source>
<target state="translated">範囲変数がクエリでスキャンするグループを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_an_integer_result">
<source>Divides two numbers and returns an integer result.</source>
<target state="translated">2 つの数値を除算して、整数の結果を返します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface">
<source>Declares the name of an interface and the definitions of the members of the interface.</source>
<target state="translated">インターフェイスの名前と、インターフェイスのメンバーの定義を宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure">
<source>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</source>
<target state="translated">式が false であるかどうかを判断します。クラスまたは構造体のインスタンスが OrElse 句で使用される場合は、そのクラスまたは構造体で IsFalse を定義する必要があります。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2">
<source>Compares two object reference variables and returns True if the objects are equal.
<result> = <object1> Is <object2></source>
<target state="translated">2 つのオブジェクト参照変数を比較し、オブジェクトが等しい場合は True を返します
<result> = <object1> Is <object2></target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2">
<source>Compares two object reference variables and returns True if the objects are not equal.
<result> = <object1> IsNot <object2></source>
<target state="translated">2 つのオブジェクト参照変数を比較し、オブジェクトが等しくない場合は True を返します
<result> = <object1> IsNot <object2></target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure">
<source>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</source>
<target state="translated">式が true であるかどうかを判断します。クラスまたは構造体のインスタンスが OrElse 句で使用される場合は、そのクラスまたは構造体で IsTrue を定義する必要があります。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_iterator_method_that_can_use_the_Yield_statement">
<source>Indicates an iterator method that can use the Yield statement.</source>
<target state="translated">Yield ステートメントを使用できる反復子メソッドを示します。</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T">
<source>Defines an iterator lambda expression that can use the Yield statement.
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</source>
<target state="translated">Yield ステートメントを使用できる反復子ラムダ式を定義します。
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_left_shift_on_a_bit_pattern">
<source>Performs an arithmetic left shift on a bit pattern.</source>
<target state="translated">ビット パターンに対して算術左シフトを実行します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目より小さい場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目以下の場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure">
<source>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</source>
<target state="translated">外部プロシージャを含む外部ファイル (DLL またはコード リソース) を識別する句を導入します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern">
<source>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters.
<result> = <string> Like <pattern></source>
<target state="translated">文字列をパターンと比較します。利用できるワイルドカードには、1 文字に一致する ?、および 0 文字以上に一致する * があります。
<result> = <string> Like <pattern></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression">
<source>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</source>
<target state="translated">2 つの数値式の差、または数値式の負の値を返します。</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2">
<source>Divides two numbers and returns only the remainder.
<number1> Mod <number2></source>
<target state="translated">2つの数値を除算し、剰余のみを返します。
<数値1> Mod <数値2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">ソース ファイルの冒頭にある属性がモジュール全体に適用されることを示します。これを示さない場合、属性はクラスやプロパティなどの個別のプログラミング要素にのみ適用されます。</target>
<note />
</trans-unit>
<trans-unit id="Multiplies_two_numbers_and_returns_the_product">
<source>Multiplies two numbers and returns the product.</source>
<target state="translated">2 つの数値を乗算して積を返します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it">
<source>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</source>
<target state="translated">クラスが基本クラスとしてのみ使用でき、オブジェクトを直接作成できないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used">
<source>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</source>
<target state="translated">プロパティやプロシージャがこのクラスで実装されておらず、派生クラスでオーバーライドされないと使用できないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace">
<source>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</source>
<target state="translated">名前空間の名前を宣言し、宣言に続くソース コードがその名前空間内でコンパイルされるようにします。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</source>
<target state="translated">変換演算子 (CType) が、クラスまたは構造体を、元のクラスまたは構造体のいくつかの使用可能な値を保持できない可能性がある型に変換することを示します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、両者が等しくない場合は True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_cannot_be_used_as_a_base_class">
<source>Specifies that a class cannot be used as a base class.</source>
<target state="translated">クラスが基本クラスとして使用できないことを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression">
<source>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression.
<result> = Not <expression></source>
<target state="translated">ブール式で論理否定を実行するか、数値式でビット否定を実行します。
<result> = Not <expression></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class">
<source>Specifies that a property or procedure cannot be overridden in a derived class.</source>
<target state="translated">プロパティまたはプロシージャが派生クラスでオーバーライドできないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure">
<source>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</source>
<target state="translated">ジェネリック クラス、構造体、インターフェイス、デリゲート、またはプロシージャの型パラメーターを識別します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure">
<source>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</source>
<target state="translated">クラスまたは構造体に演算子プロシージャを定義する演算子記号、オペランド、およびコードを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called">
<source>Specifies that a procedure argument can be omitted when the procedure is called.</source>
<target state="translated">プロシージャが呼び出されるときにプロシージャ引数が省略可能であることを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file">
<source>Introduces a statement that specifies a compiler option that applies to the entire source file.</source>
<target state="translated">ソース ファイル全体に適用されるコンパイラ オプションを指定するステートメントを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2">
<source>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated.
<result> = <expression1> OrElse <expression2></source>
<target state="translated">2 つの式の包括的ショートサーキット論理和を求めます。少なくとも 1 つのオペランドが True と評価された場合は True を返します。最初の式が True と評価された場合、2 番目の式は評価されません。
<result> = <expression1> OrElse <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2">
<source>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Or <expression2></source>
<target state="translated">2 つのブール式の包括的論理和または 2 つの数値式のビットごとの和を求めます。ブール式の場合、少なくとも 1 つのオペランドが True と評価された場合は True を返します。常に両方のオペランドが評価されます。
<result> = <expression1> Or <expression2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name">
<source>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</source>
<target state="translated">プロパティまたはプロシージャが、同じ名前の 1 つ以上の既存のプロパティまたはプロシージャを再度宣言することを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class">
<source>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</source>
<target state="translated">プロパティまたはプロシージャが派生クラスで同じ名前のプロパティまたはプロシージャによってオーバーライドできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class">
<source>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</source>
<target state="translated">プロパティまたはプロシージャが基本クラスから継承された同じ名前のプロパティまたはプロシージャをオーバーライドすることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type">
<source>Specifies that a procedure parameter takes an optional array of elements of the specified type.</source>
<target state="translated">プロシージャのパラメーターが、指定された型の、省略可能な要素の配列を受け取ることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure">
<source>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</source>
<target state="translated">メソッド、クラス、または構造体の宣言が、メソッド、クラス、または構造体の部分定義であることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression">
<source>Returns the sum of two numbers, or the positive value of a numeric expression.</source>
<target state="translated">2 つの数値の合計、または数値式の正の値を返します。</target>
<note />
</trans-unit>
<trans-unit id="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed">
<source>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</source>
<target state="translated">配列の次元が変更されるときに配列の内容が消去されないようにします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure">
<source>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素が、モジュール内、クラス内、または構造体内からのみアクセスできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property">
<source>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</source>
<target state="translated">プロパティの名前、およびプロパティの値を格納して取得するために使用されるプロパティ プロシージャを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes">
<source>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</source>
<target state="translated">クラスの1 つ以上の宣言されたメンバーが同じアセンブリ、独自のクラス、および派生クラス内のいずれかからアクセスできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class">
<source>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素が、独自のクラス内または派生クラスからのみアクセスできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions">
<source>Specifies that one or more declared programming elements have no access restrictions.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素にアクセス制限がないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to">
<source>Specifies that a variable or property can be read but not written to.</source>
<target state="translated">変数またはプロパティを読み込めるが、書き込みはできないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Reallocates_storage_space_for_an_array_variable">
<source>Reallocates storage space for an array variable.</source>
<target state="translated">配列変数の記憶域を再割り当てします。</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_right_shift_on_a_bit_pattern">
<source>Performs an arithmetic right shift on a bit pattern</source>
<target state="translated">ビット パターンに対して算術右シフトを実行します</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property">
<source>Declares a Set property procedure that is used to assign a value to a property.</source>
<target state="translated">値をプロパティに割り当てるのに使用する Set プロパティ プロシージャを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class">
<source>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</source>
<target state="translated">宣言されたプログラミング要素が、基本クラスにある、同じ名前を持つ要素を宣言し直して非表示にすることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure">
<source>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素がクラスまたは構造体のすべてのインスタンスに関連付けられていることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates">
<source>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</source>
<target state="translated">1 つ以上の宣言されているローカル変数が残存し、ローカル変数を宣言するプロシージャが終了した後もその最新の値が保持されるように指定します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure">
<source>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</source>
<target state="translated">構造体の名前を宣言し、その構造体を構成する変数、プロパティ、イベント、プロシージャの定義を示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</source>
<target state="translated">Sub プロシージャ (呼び出しコードに値を返さないプロシージャ) を定義する名前、パラメーター、およびコードを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range">
<source>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</source>
<target state="translated">ループ カウンター、配列の範囲、または値が一致する範囲の開始値と終了値を分割します。</target>
<note />
</trans-unit>
<trans-unit id="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName">
<source>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible.
<result> = TypeOf <objectExpression> Is <typeName></source>
<target state="translated">オブジェクト参照変数の実行時の型を判断して、データ型と比較します。2 つの型に互換性があるかどうかに応じて、True または False を返します。
<result> = TypeOf <objectExpression> Is <typeName></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name">
<source>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</source>
<target state="translated">Declare ステートメントで使用されます。Visual Basic が外部プロシージャ呼び出しのすべての文字列を Unicode 値にマーシャリングし、その名前を変更せずにプロシージャを検索することを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</source>
<target state="translated">変換演算子 (CType) が、クラスまたは構造体を、元のクラスまたは構造体のすべての使用可能な値を保持できる型に変換することを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events">
<source>Specifies that one or more declared member variables refer to an instance of a class that can raise events</source>
<target state="translated">1 つ以上の宣言されたメンバー変数が、イベントを発生させる可能性のあるクラスのインスタンスを参照していることを示します</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_can_be_written_to_but_not_read">
<source>Specifies that a property can be written to but not read.</source>
<target state="translated">プロパティに書き込みはできるが、読み込みはできないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2">
<source>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Xor <expression2></source>
<target state="translated">2 つのブール式の場合は排他的論理演算、2 つの数値式の場合はビットごとの排他を求めます。ブール式の場合、2 つの式のうち 1 つのみが True と評価されたときは True を返します。常に両方の式が評価されます。
<result> = <expression1> Xor <expression2></target>
<note />
</trans-unit>
<trans-unit id="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence">
<source>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</source>
<target state="translated">Sum、Average、Count などの集計関数をシーケンスに適用します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</source>
<target state="translated">クエリの Order By 句の並べ替え順序を指定します。最小の要素が最初に表示されます。</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order">
<source>Sets the string comparison method specified in Option Compare to a strict binary sort order.</source>
<target state="translated">Option Compare で指定する文字列の比較方法を、厳密なバイナリの並べ替え順序に設定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By">
<source>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</source>
<target state="translated">グループ化 (Group By) または並べ替え順序 (Order By) に対して使用される要素キーを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket">
<source>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure.
[Call] <procedureName> [(<argumentList>)]</source>
<target state="translated">Function、Sub、またはダイナミック リンク ライブラリ (DLL) プロシージャに実行を移します。
[Call] <procedureName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True">
<source>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</source>
<target state="translated">Select Case ステートメントの前述のケースのいずれも True を返さない場合に実行するステートメントを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True">
<source>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</source>
<target state="translated">後ろに比較演算子と式を付加すると、 Case Is 式と組み合わされた Select Case 式が True と評価された場合に実行されるステートメントを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression">
<source>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested.
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</source>
<target state="translated">Select Case ステートメントの式の値がテストされる値または値のセットを導入します。
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block">
<source>Introduces a statement block to be run if the specified exception occurs inside a Try block.</source>
<target state="translated">指定された例外が Try ブロックの内部で発生した場合に実行されるステートメント ブロックを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text">
<source>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order.
Option Compare {Binary | Text}</source>
<target state="translated">文字列のデータを比較するときに使用する、既定の比較方法を設定します。Text に設定する場合は、大文字と小文字を区別しないテキストの並べ替え順序を使用します。Binary に設定する場合は、厳密なバイナリ並べ替え順序を使用します。
Option Compare {Binary | Text}</target>
<note />
</trans-unit>
<trans-unit id="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals">
<source>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</source>
<target state="translated">条件付きコンパイラ定数を定義します。条件付きコンパイラ定数は、表示されるファイルに対しては常にプライベートです。初期化に使用される式には、条件付きコンパイラ定数とリテラルのみを含めることができます。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop">
<source>Transfers execution immediately to the next iteration of the Do loop.</source>
<target state="translated">実行を Do ループの次の反復処理に直ちに移します。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop">
<source>Transfers execution immediately to the next iteration of the For loop.</source>
<target state="translated">実行を For ループの次の反復処理に直ちに移します。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop">
<source>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</source>
<target state="translated">実行をループの次の反復処理に直ちに移します。Do ループ、For ループ、または While ループで使用できます。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop">
<source>Transfers execution immediately to the next iteration of the While loop.</source>
<target state="translated">実行を While ループの次の反復処理に直ちに移します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</source>
<target state="translated">クエリの Order By 句の並べ替え順序を指定します。最大の要素が最初に表示されます。</target>
<note />
</trans-unit>
<trans-unit id="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values">
<source>Restricts the values of a query result to eliminate duplicate values.</source>
<target state="translated">重複した値がなくなるようにクエリ結果の値を制限します。</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition">
<source>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true.
Do...Loop {While | Until} <condition></source>
<target state="translated">ブール条件が true である間、または条件が true になるまで、ステートメント ブロックを繰り返します。
Do...Loop {While | Until} <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do Until <condition>...Loop</source>
<target state="translated">ブール条件が true になるまでステートメント ブロックを繰り返します。
Do Until <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop">
<source>Repeats a block of statements while a Boolean condition is true.
Do While <condition>...Loop</source>
<target state="translated">ブール条件が true である間、ステートメント ブロックを繰り返します。
Do While <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</source>
<target state="translated">前の条件が True として評価されていない場合にコンパイルされる #If ステートメントにステートメント グループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False">
<source>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</source>
<target state="translated">前の条件テストが False として評価されている場合にテストされる #If ステートメントの条件を導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails">
<source>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</source>
<target state="translated">前の条件テストが失敗した場合にテストされる If ステートメントの条件を導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</source>
<target state="translated">前の条件が True として評価されていない場合に実行される If ステートメントにステートメント グループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_SharpIf_block">
<source>Terminates the definition of an #If block.</source>
<target state="translated">#If ブロックの定義を終了します。</target>
<note />
</trans-unit>
<trans-unit id="Stops_execution_immediately">
<source>Stops execution immediately.</source>
<target state="translated">実行を直ちに停止します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_SharpRegion_block">
<source>Terminates a #Region block.</source>
<target state="translated">#Region ブロックを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation">
<source>Specifies the relationship between element keys to use as the basis of a join operation.</source>
<target state="translated">結合操作の基準として使用する要素キー間の関係を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Simulates_the_occurrence_of_an_error">
<source>Simulates the occurrence of an error.</source>
<target state="translated">エラーの発生をシミュレートします。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement">
<source>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</source>
<target state="translated">Do ループを終了し、その実行を Loop ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement">
<source>Exits a For loop and transfers execution immediately to the statement following the Next statement.</source>
<target state="translated">For ループを終了し、その実行を Next ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While">
<source>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition.
Exit {Do | For | Function | Property | Select | Sub | Try | While}</source>
<target state="translated">プロシージャまたはブロックを終了し、その実行をプロシージャ呼び出しまたはブロック定義に続くステートメントに直ちに転送します。
Exit {Do | For | Function | Property | Select | Sub | Try | While}</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement">
<source>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</source>
<target state="translated">Select ブロックを終了し、その実行を End Select ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement">
<source>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</source>
<target state="translated">Try ブロックを終了し、その実行を End Try ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement">
<source>Exits a While loop and transfers execution immediately to the statement following the End While statement.</source>
<target state="translated">While ループを終了し、その実行を End While ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off">
<source>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement.
Option Explicit {On | Off}</source>
<target state="translated">On に設定されている場合は、Dim、Private、Public、または ReDim ステートメントを使用したすべての変数の明示的な宣言が必要です。
Option Explicit {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_fails_a_conditional_test">
<source>Represents a Boolean value that fails a conditional test.</source>
<target state="translated">条件テストを満たさないブール値を表します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure">
<source>Introduces a statement block to be run before exiting a Try structure.</source>
<target state="translated">Try 構造を終了する前に実行されるステートメント ブロックを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection">
<source>Introduces a loop that is repeated for each element in a collection.</source>
<target state="translated">コレクション内の要素ごとに繰り返されるループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_iterated_a_specified_number_of_times">
<source>Introduces a loop that is iterated a specified number of times.</source>
<target state="translated">指定された回数反復されるループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_list_of_values_as_a_collection_initializer">
<source>Identifies a list of values as a collection initializer</source>
<target state="translated">コレクション初期化子として値一覧を識別します</target>
<note />
</trans-unit>
<trans-unit id="Branches_unconditionally_to_a_specified_line_in_a_procedure">
<source>Branches unconditionally to a specified line in a procedure.</source>
<target state="translated">プロシージャ内の指定した行に無条件に分岐します。</target>
<note />
</trans-unit>
<trans-unit id="Groups_elements_that_have_a_common_key">
<source>Groups elements that have a common key.</source>
<target state="translated">共通のキーを持つ要素をグループ化します。</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</source>
<target state="translated">2 つのシーケンスの要素を組み合わせて、結果をグループ化します。結合操作は一致するキーに基づきます。</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_0_should_be_created">
<source>Use 'Group' to specify that a group named '{0}' should be created.</source>
<target state="translated">Group' を使用して、'{0}' という名前のグループが作成されるように指定します。</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_Group_should_be_created">
<source>Use 'Group' to specify that a group named 'Group' should be created.</source>
<target state="translated">Group' を使用して、'Group' という名前のグループが作成されるように指定します。</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression">
<source>Conditionally compiles selected blocks of code, depending on the value of an expression.</source>
<target state="translated">式の値に応じて、選択したコード ブロックを条件付きでコンパイルします。</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression">
<source>Conditionally executes a group of statements, depending on the value of an expression.</source>
<target state="translated">式の値に応じて、ステートメント グループを条件付きで実行します。</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off">
<source>When set to On, allows the use of local type inference in declaring variables.
Option Infer {On | Off}</source>
<target state="translated">On に設定されている場合は、変数の宣言においてローカル型の推論を使用できます。
Option Infer {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression">
<source>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</source>
<target state="translated">結合またはグループ化サブ式の結果への参照として使用できる識別子を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences. The join operation is based on matching keys.</source>
<target state="translated">2 つのシーケンスの要素を組み合わせます。結合操作は一致するキーに基づきます。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_key_field_in_an_anonymous_type_definition">
<source>Identifies a key field in an anonymous type definition.</source>
<target state="translated">匿名型の定義のキー フィールドを識別します。</target>
<note />
</trans-unit>
<trans-unit id="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable">
<source>Computes a value for each item in the query, and assigns the value to a new range variable.</source>
<target state="translated">クエリ内の各項目の値をコンピューティングし、新しい範囲変数に値を割り当てます。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_is_introduced_with_a_Do_statement">
<source>Terminates a loop that is introduced with a Do statement.</source>
<target state="translated">Do ステートメントで導入されるループを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do...Loop Until <condition></source>
<target state="translated">ブール条件が true になるまでステートメント ブロックを繰り返します。
Do...Loop Until <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition">
<source>Repeats a block of statements while a Boolean condition is true.
Do...Loop While <condition></source>
<target state="translated">ブール条件が true である間、ステートメント ブロックを繰り返します。
Do...Loop While <condition></target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running">
<source>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</source>
<target state="translated">クラスまたは構造体の現在の (コードが実行されている) インスタンスを参照する方法を提供します。</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods">
<source>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</source>
<target state="translated">現在のクラス インスタンスの基本クラスを参照する方法を提供します。MyBase を使用して、MustOverride 基本メソッドを呼び出すことはできません。</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides">
<source>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</source>
<target state="translated">最初に実装されたときの状態のクラスのインスタンス メンバーを参照する (派生クラスのオーバーライドをすべて無視する) 方法を提供します。</target>
<note />
</trans-unit>
<trans-unit id="Creates_a_new_object_instance">
<source>Creates a new object instance.</source>
<target state="translated">新しいオブジェクト インスタンスを作成します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable">
<source>Terminates a loop that iterates through the values of a loop variable.</source>
<target state="translated">ループ変数の値を反復処理するループを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Represents_the_default_value_of_any_data_type">
<source>Represents the default value of any data type.</source>
<target state="translated">任意のデータ型の既定値を表します。</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_off">
<source>Turns a compiler option off.</source>
<target state="translated">コンパイラ オプションをオフにします。</target>
<note />
</trans-unit>
<trans-unit id="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket">
<source>Enables the error-handling routine that starts at the line specified in the line argument.
The specified line must be in the same procedure as the On Error statement.
On Error GoTo [<label> | 0 | -1]</source>
<target state="translated">行引数で指定された行から開始されるエラー処理ルーチンを有効にします。
指定された行は On Error ステートメントと同じプロシージャにする必要があります。
On Error GoTo [<label> | 0 | -1]</target>
<note />
</trans-unit>
<trans-unit id="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error">
<source>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</source>
<target state="translated">ランタイム エラーが発生すると、エラーが発生したステートメントまたはプロシージャ呼び出しに続くステートメントに実行が移ります。</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_on">
<source>Turns a compiler option on.</source>
<target state="translated">コンパイラ オプションをオンにします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation">
<source>Specifies the element keys used to correlate sequences for a join operation.</source>
<target state="translated">結合操作でシーケンスを関連付けるために使用される要素キーを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used">
<source>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</source>
<target state="translated">クエリにおける列の並べ替え順序を指定します。Ascending キーワードまたは Descending キーワードの前に指定できます。いずれも指定されていない場合は、Ascending が使用されます。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent">
<source>Specifies the statements to run when the event is raised by the RaiseEvent statement.
RaiseEvent(<delegateSignature>)...End RaiseEvent</source>
<target state="translated">イベントを RaiseEvent ステートメントによって発生させる場合に実行するステートメントを指定します。
RaiseEvent(<delegateSignature>)...End RaiseEvent</target>
<note />
</trans-unit>
<trans-unit id="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket">
<source>Triggers an event declared at module level within a class, form, or document.
RaiseEvent <eventName> [(<argumentList>)]</source>
<target state="translated">モジュール レベルで宣言されたイベントをクラス、フォーム、またはドキュメントで発生させます。
RaiseEvent <eventName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Collapses_and_hides_sections_of_code_in_Visual_Basic_files">
<source>Collapses and hides sections of code in Visual Basic files.</source>
<target state="translated">Visual Basic ファイルのコードのセクションを折りたたんで非表示にします。</target>
<note />
</trans-unit>
<trans-unit id="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression">
<source>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure.
Return -or- Return <expression></source>
<target state="translated">Function、Sub、Get、Set、または Operator プロシージャを呼び出したコードに実行を戻します。
Return -or- Return <expression></target>
<note />
</trans-unit>
<trans-unit id="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression">
<source>Runs one of several groups of statements, depending on the value of an expression.</source>
<target state="translated">式の値に応じて、いくつかのステートメント グループのいずれかを実行します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_which_columns_to_include_in_the_result_of_a_query">
<source>Specifies which columns to include in the result of a query.</source>
<target state="translated">クエリの結果に含める列を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Skips_elements_up_to_a_specified_position_in_the_collection">
<source>Skips elements up to a specified position in the collection.</source>
<target state="translated">コレクション内の指定された位置までの要素をスキップします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_how_much_to_increment_between_each_loop_iteration">
<source>Specifies how much to increment between each loop iteration.</source>
<target state="translated">ループの反復処理のたびにインクリメントする量を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Suspends_program_execution">
<source>Suspends program execution.</source>
<target state="translated">プログラムの実行を中断します。</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off">
<source>When set to On, restricts implicit data type conversions to only widening conversions.
Option Strict {On | Off}</source>
<target state="translated">On に設定されている場合は、 暗黙的なデータ型の変換を拡大変換のみに制限します。
Option Strict {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock">
<source>Ensures that multiple threads do not execute the statement block at the same time.
SyncLock <object>...End Synclock</source>
<target state="translated">複数のスレッドがステートメント ブロックを同時に実行しないようにします。
SyncLock <object>...End Synclock</target>
<note />
</trans-unit>
<trans-unit id="Includes_elements_up_to_a_specified_position_in_the_collection">
<source>Includes elements up to a specified position in the collection.</source>
<target state="translated">コレクション内の指定された位置までの要素が含まれます。</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive">
<source>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</source>
<target state="translated">Option Compare で指定する文字列の比較方法を、大文字と小文字を区別しないテキストの並べ替え順序に設定します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true">
<source>Introduces a statement block to be compiled or executed if a tested condition is true.</source>
<target state="translated">テストされた条件が True の場合にコンパイルまたは実行されるステートメント ブロックを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code">
<source>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</source>
<target state="translated">構造化例外処理コード、または非構造化例外処理コードで処理できるように、プロシージャ内で例外をスローします。</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_passes_a_conditional_test">
<source>Represents a Boolean value that passes a conditional test.</source>
<target state="translated">条件テストを満たすブール値を表します。</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try">
<source>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code.
Try...[Catch]...{Catch | Finally}...End Try</source>
<target state="translated">コードの実行中に、指定のコード ブロックで発生する可能性のあるエラーの一部またはすべてを処理する方法を提供します。
Try...[Catch]...{Catch | Finally}...End Try</target>
<note />
</trans-unit>
<trans-unit id="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using">
<source>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable.
Using <resource1>[, <resource2>]...End Using</source>
<target state="translated">Using ブロックは、リソース リストの変数を作成して初期化する、ブロックのコードを実行する、終了する前に変数を破棄する、という 3 つのことをします。Using ブロックで使用されるリソースは、System.IDisposable を実装する必要があります。
Using <resource1>[, <resource2>]...End Using</target>
<note />
</trans-unit>
<trans-unit id="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True">
<source>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</source>
<target state="translated">Catch ステートメントに条件テストを追加します。When キーワードの後に続く条件テストが True に評価されるときにのみ、その Catch ステートメントによって例外がキャッチされます。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_filtering_condition_for_a_range_variable_in_a_query">
<source>Specifies the filtering condition for a range variable in a query.</source>
<target state="translated">クエリで範囲変数のフィルター条件を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true">
<source>Runs a series of statements as long as a given condition is true.</source>
<target state="translated">指定された条件が true である限り、一連のステートメントを実行します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true">
<source>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</source>
<target state="translated">Skip および Take 操作の条件を指定します。条件が true である限り、要素はバイパスされるか含まれます。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket">
<source>Specifies the declaration of property initializations in an object initializer.
New <typeName> With {[.<property> = <expression>][,...]}</source>
<target state="translated">オブジェクト初期化子のプロパティ初期化の宣言を指定します。
New <typeName> With {[.<property> = <expression>][,...]}</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With">
<source>Runs a series of statements that refer to a single object or structure.
With <object>...End With</source>
<target state="translated">1 つのオブジェクトまたは構造体を参照する一連のステートメントを実行します。
With <object>...End With</target>
<note />
</trans-unit>
<trans-unit id="Produces_an_element_of_an_IEnumerable_or_IEnumerator">
<source>Produces an element of an IEnumerable or IEnumerator.</source>
<target state="translated">IEnumerable または IEnumerator の要素を生成します。</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression">
<source>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected.
Async Sub/Function(<parameterList>) <expression></source>
<target state="translated">Await 演算子を使用できる非同期ラムダ式を定義します。デリゲート型が想定される場所であれば使用できます。
Async Sub/Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression">
<source>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected.
Function(<parameterList>) <expression></source>
<target state="translated">計算を行い、1 つの値を返すラムダ式を定義します。デリゲート型が想定される場所であれば使用できます。
Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement">
<source>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected.
Sub(<parameterList>) <statement></source>
<target state="translated">ステートメントを実行でき、値を返さないラムダ式を定義します。デリゲート型が想定される場所であれば使用できます。
Sub(<parameterList>) <statement></target>
<note />
</trans-unit>
<trans-unit id="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Disables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">現在の行以降のソース ファイルの部分で指定された警告のレポートを無効にします。</target>
<note />
</trans-unit>
<trans-unit id="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Enables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">現在の行以降のソース ファイルの部分で指定された警告のレポートを有効にします。</target>
<note />
</trans-unit>
<trans-unit id="Insert_Await">
<source>Insert 'Await'.</source>
<target state="translated">Await' を挿入します。</target>
<note />
</trans-unit>
<trans-unit id="Make_0_an_Async_Function">
<source>Make {0} an Async Function.</source>
<target state="translated">{0} を Async Function にします。</target>
<note />
</trans-unit>
<trans-unit id="Convert_0_to_Iterator">
<source>Convert {0} to Iterator</source>
<target state="translated">{0} を反復子に変換</target>
<note />
</trans-unit>
<trans-unit id="Replace_Return_with_Yield">
<source>Replace 'Return' with 'Yield</source>
<target state="translated">Return' を 'Yield' に置き換える</target>
<note />
</trans-unit>
<trans-unit id="Use_the_correct_control_variable">
<source>Use the correct control variable</source>
<target state="translated">正しい制御変数を使用する</target>
<note />
</trans-unit>
<trans-unit id="NameOf_function">
<source>NameOf function</source>
<target state="translated">NameOf 関数</target>
<note />
</trans-unit>
<trans-unit id="Generate_narrowing_conversion_in_0">
<source>Generate narrowing conversion in '{0}'</source>
<target state="translated">'{0}' で縮小変換を生成する</target>
<note />
</trans-unit>
<trans-unit id="Generate_widening_conversion_in_0">
<source>Generate widening conversion in '{0}'</source>
<target state="translated">'{0}' で拡大変換を生成する</target>
<note />
</trans-unit>
<trans-unit id="Try_block">
<source>Try block</source>
<target state="translated">Try ブロック</target>
<note>{Locked="Try"} "Try" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Catch_clause">
<source>Catch clause</source>
<target state="translated">Catch 句</target>
<note>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Finally_clause">
<source>Finally clause</source>
<target state="translated">Finally 句</target>
<note>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_statement">
<source>Using statement</source>
<target state="translated">Using ステートメント</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_block">
<source>Using block</source>
<target state="translated">Using ブロック</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_statement">
<source>With statement</source>
<target state="translated">With ステートメント</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_block">
<source>With block</source>
<target state="translated">With ブロック</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_statement">
<source>SyncLock statement</source>
<target state="translated">SyncLock ステートメント</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_block">
<source>SyncLock block</source>
<target state="translated">SyncLock ブロック</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_statement">
<source>For Each statement</source>
<target state="translated">For Each ステートメント</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_block">
<source>For Each block</source>
<target state="translated">For Each ブロック</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="On_Error_statement">
<source>On Error statement</source>
<target state="translated">On Error ステートメント</target>
<note>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Resume_statement">
<source>Resume statement</source>
<target state="translated">Resume ステートメント</target>
<note>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Yield_statement">
<source>Yield statement</source>
<target state="translated">Yield ステートメント</target>
<note>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Await_expression">
<source>Await expression</source>
<target state="translated">Await 式</target>
<note>{Locked="Await"} "Await" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Lambda">
<source>Lambda</source>
<target state="translated">ラムダ</target>
<note />
</trans-unit>
<trans-unit id="Where_clause">
<source>Where clause</source>
<target state="translated">Where 句</target>
<note>{Locked="Where"} "Where" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Select_clause">
<source>Select clause</source>
<target state="translated">Select 句</target>
<note>{Locked="Select"} "Select" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="From_clause">
<source>From clause</source>
<target state="translated">From 句</target>
<note>{Locked="From"} "From" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Aggregate_clause">
<source>Aggregate clause</source>
<target state="translated">Aggregate 句</target>
<note>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Let_clause">
<source>Let clause</source>
<target state="translated">Let 句</target>
<note>{Locked="Let"} "Let" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_clause">
<source>Join clause</source>
<target state="translated">Join 句</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_Join_clause">
<source>Group Join clause</source>
<target state="translated">Group Join 句</target>
<note>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_By_clause">
<source>Group By clause</source>
<target state="translated">Group By 句</target>
<note>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Function_aggregation">
<source>Function aggregation</source>
<target state="translated">関数集約</target>
<note />
</trans-unit>
<trans-unit id="Take_While_clause">
<source>Take While clause</source>
<target state="translated">Take While 句</target>
<note>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Skip_While_clause">
<source>Skip While clause</source>
<target state="translated">Skip While 句</target>
<note>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Ordering_clause">
<source>Ordering clause</source>
<target state="translated">Ordering 句</target>
<note>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_condition">
<source>Join condition</source>
<target state="translated">Join 条件</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="WithEvents_field">
<source>WithEvents field</source>
<target state="translated">WithEvents フィールド</target>
<note>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="as_clause">
<source>as clause</source>
<target state="translated">as 句</target>
<note>{Locked="as"} "as" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="type_parameters">
<source>type parameters</source>
<target state="translated">型パラメーター</target>
<note />
</trans-unit>
<trans-unit id="parameters">
<source>parameters</source>
<target state="translated">パラメーター</target>
<note />
</trans-unit>
<trans-unit id="attributes">
<source>attributes</source>
<target state="translated">属性</target>
<note />
</trans-unit>
<trans-unit id="Too_many_arguments_to_0">
<source>Too many arguments to '{0}'.</source>
<target state="translated">'{0}' の引数が多すぎます。</target>
<note />
</trans-unit>
<trans-unit id="Type_0_is_not_defined">
<source>Type '{0}' is not defined.</source>
<target state="translated">型 '{0}' は定義されていません。</target>
<note />
</trans-unit>
<trans-unit id="Add_Overloads">
<source>Add 'Overloads'</source>
<target state="translated">'Overloads' の追加</target>
<note>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll">
<source>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</source>
<target state="translated">指定されたアセンブリとそのすべての依存関係へのメタデータ参照を追加します (例: #r "myLib.dll")。</target>
<note />
</trans-unit>
<trans-unit id="Properties">
<source>Properties</source>
<target state="translated">プロパティ</target>
<note />
</trans-unit>
<trans-unit id="namespace_name">
<source><namespace name></source>
<target state="translated"><名前空間名></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_namespace">
<source>Type a name here to declare a namespace.</source>
<target state="translated">名前空間を宣言するには、ここに名前を入力してください。</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_class">
<source>Type a name here to declare a partial class.</source>
<target state="translated">部分クラスを宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="class_name">
<source><class name></source>
<target state="translated"><クラス名></target>
<note />
</trans-unit>
<trans-unit id="interface_name">
<source><interface name></source>
<target state="translated"><インターフェイス名></target>
<note />
</trans-unit>
<trans-unit id="module_name">
<source><module name></source>
<target state="translated"><モジュール名></target>
<note />
</trans-unit>
<trans-unit id="structure_name">
<source><structure name></source>
<target state="translated"><構造体名></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_interface">
<source>Type a name here to declare a partial interface.</source>
<target state="translated">部分インターフェイスを宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_module">
<source>Type a name here to declare a partial module.</source>
<target state="translated">部分モジュールを宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_structure">
<source>Type a name here to declare a partial structure.</source>
<target state="translated">部分構造体を宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="Event_add_handler_name">
<source>{0}.add</source>
<target state="translated">{0}.add</target>
<note>The name of an event add handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Event_remove_handler_name">
<source>{0}.remove</source>
<target state="translated">{0}.remove</target>
<note>The name of an event remove handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Property_getter_name">
<source>{0}.get</source>
<target state="translated">{0}.get</target>
<note>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Property_setter_name">
<source>{0}.set</source>
<target state="translated">{0}.set</target>
<note>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Make_Async_Function">
<source>Make Async Function</source>
<target state="translated">Async Function を作成する</target>
<note />
</trans-unit>
<trans-unit id="Make_Async_Sub">
<source>Make Async Sub</source>
<target state="translated">Async Sub にする</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_Select_Case">
<source>Convert to 'Select Case'</source>
<target state="translated">'Select Case' に変換する</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For_Each">
<source>Convert to 'For Each'</source>
<target state="translated">'For Each' に変換する</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For">
<source>Convert to 'For'</source>
<target state="translated">'For' に変換する</target>
<note />
</trans-unit>
<trans-unit id="Invert_If">
<source>Invert If</source>
<target state="translated">if を反転する</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="ja" original="../VBFeaturesResources.resx">
<body>
<trans-unit id="Add_Await">
<source>Add Await</source>
<target state="translated">Await の追加</target>
<note />
</trans-unit>
<trans-unit id="Add_Await_and_ConfigureAwaitFalse">
<source>Add Await and 'ConfigureAwait(false)'</source>
<target state="translated">Await と 'ConfigureAwait(false)' の追加</target>
<note />
</trans-unit>
<trans-unit id="Add_Obsolete">
<source>Add <Obsolete></source>
<target state="translated"><Obsolete> の追加</target>
<note />
</trans-unit>
<trans-unit id="Add_missing_Imports">
<source>Add missing Imports</source>
<target state="translated">欠落している Import の追加</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Add_Shadows">
<source>Add 'Shadows'</source>
<target state="translated">'Shadows' の追加</target>
<note>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Imports_directive_placement_preferences">
<source>Apply Imports directive placement preferences</source>
<target state="translated">Import ディレクティブの配置設定を適用する</target>
<note>{Locked="Import"} "Import" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Me_qualification_preferences">
<source>Apply Me qualification preferences</source>
<target state="translated">Me 修飾設定を適用する</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Change_to_DirectCast">
<source>Change to 'DirectCast'</source>
<target state="translated">'DirectCast' に変更</target>
<note />
</trans-unit>
<trans-unit id="Change_to_TryCast">
<source>Change to 'TryCast'</source>
<target state="translated">'TryCast' に変更</target>
<note />
</trans-unit>
<trans-unit id="Insert_0">
<source>Insert '{0}'.</source>
<target state="translated">{0} の挿入</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement1">
<source>Delete the '{0}' statement.</source>
<target state="translated">'{0}' ステートメントを削除します。</target>
<note />
</trans-unit>
<trans-unit id="Create_event_0_in_1">
<source>Create event {0} in {1}</source>
<target state="translated">イベント {0} を {1} に作成する</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_End_Property_statement">
<source>Insert the missing 'End Property' statement.</source>
<target state="translated">不足している ' End Property' ステートメントを挿入します。</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_0">
<source>Insert the missing '{0}'.</source>
<target state="translated">不足している '{0}' を挿入します。</target>
<note />
</trans-unit>
<trans-unit id="Inline_temporary_variable">
<source>Inline temporary variable</source>
<target state="translated">インラインの一時変数</target>
<note />
</trans-unit>
<trans-unit id="Conflict_s_detected">
<source>Conflict(s) detected.</source>
<target state="translated">競合が検出されました。</target>
<note />
</trans-unit>
<trans-unit id="Introduce_Using_statement">
<source>Introduce 'Using' statement</source>
<target state="translated">’Using’ ステートメントの導入</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Make_0_inheritable">
<source>Make '{0}' inheritable</source>
<target state="translated">'{0}' を継承可能にします</target>
<note />
</trans-unit>
<trans-unit id="Make_private_field_ReadOnly_when_possible">
<source>Make private field ReadOnly when possible</source>
<target state="translated">可能な場合、プライベート フィールドを ReadOnly にする</target>
<note>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Move_the_0_statement_to_line_1">
<source>Move the '{0}' statement to line {1}.</source>
<target state="translated">'{0}' ステートメントを行 {1} に移動します。</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement2">
<source>Delete the '{0}' statement.</source>
<target state="translated">'{0}' ステートメントを削除します。</target>
<note />
</trans-unit>
<trans-unit id="Multiple_Types">
<source><Multiple Types></source>
<target state="translated"><複数の種類></target>
<note />
</trans-unit>
<trans-unit id="Organize_Imports">
<source>Organize Imports</source>
<target state="translated">Import の整理</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Remove_shared_keyword_from_module_member">
<source>Remove 'Shared' keyword from Module member</source>
<target state="translated">モジュール メンバーから 'Shared' キーワードを削除</target>
<note>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Shared_constructor">
<source>Shared constructor</source>
<target state="translated">共有コンストラクター</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_new_field">
<source>Type a name here to declare a new field.</source>
<target state="translated">新しいフィールドを宣言するには、ここに名前を入力します。</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">注: 潜在的な干渉を避けるため、スペースの補完は無効になっています。リストから名前を挿入するには、タブを使用します。</target>
<note />
</trans-unit>
<trans-unit id="_0_Events">
<source>({0} Events)</source>
<target state="translated">({0} イベント)</target>
<note />
</trans-unit>
<trans-unit id="new_field">
<source><new field></source>
<target state="translated"><新しいフィールド></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value">
<source>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</source>
<target state="translated">パラメーターを宣言するには、ここに名前を入力します。先行するキーワードが使用されない場合は、'ByVal' と見なされ、引数が値によって渡されます。</target>
<note />
</trans-unit>
<trans-unit id="parameter_name">
<source><parameter name></source>
<target state="translated"><パラメーター名></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used">
<source>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</source>
<target state="translated">列の新しい名前 (名前の後に '=' が続く) を入力します。これを入力しない場合、元の列名が使用されます。</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name">
<source>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</source>
<target state="translated">注: タブを使用すると自動補完されます。新しい名前への干渉を避けるために、スペースの補完は無効になっています。</target>
<note />
</trans-unit>
<trans-unit id="result_alias">
<source><result alias></source>
<target state="translated"><結果のエイリアス></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_variable_name">
<source>Type a new variable name</source>
<target state="translated">新しい変数の名前を入力します</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">注: 潜在的な干渉を避けるため、スペースと '=' の補完は無効になっています。リストから名前を挿入するには、タブを使用します。</target>
<note />
</trans-unit>
<trans-unit id="new_resource">
<source><new resource></source>
<target state="translated"><新しいリソース></target>
<note />
</trans-unit>
<trans-unit id="AddHandler_statement">
<source>AddHandler statement</source>
<target state="translated">AddHandler ステートメント</target>
<note />
</trans-unit>
<trans-unit id="RemoveHandler_statement">
<source>RemoveHandler statement</source>
<target state="translated">RemoveHandler ステートメント</target>
<note />
</trans-unit>
<trans-unit id="_0_function">
<source>{0} function</source>
<target state="translated">{0} 関数</target>
<note />
</trans-unit>
<trans-unit id="CType_function">
<source>CType function</source>
<target state="translated">CType 関数</target>
<note />
</trans-unit>
<trans-unit id="DirectCast_function">
<source>DirectCast function</source>
<target state="translated">DirectCast 関数</target>
<note />
</trans-unit>
<trans-unit id="TryCast_function">
<source>TryCast function</source>
<target state="translated">TryCast 関数</target>
<note />
</trans-unit>
<trans-unit id="GetType_function">
<source>GetType function</source>
<target state="translated">GetType 関数</target>
<note />
</trans-unit>
<trans-unit id="GetXmlNamespace_function">
<source>GetXmlNamespace function</source>
<target state="translated">GetXmlNamespace 関数</target>
<note />
</trans-unit>
<trans-unit id="Mid_statement">
<source>Mid statement</source>
<target state="translated">Mid ステートメント</target>
<note />
</trans-unit>
<trans-unit id="Fix_Incorrect_Function_Return_Type">
<source>Fix Incorrect Function Return Type</source>
<target state="translated">無効な関数の戻り値の型を修正する</target>
<note />
</trans-unit>
<trans-unit id="Simplify_name_0">
<source>Simplify name '{0}'</source>
<target state="translated">名前 '{0}' の単純化</target>
<note />
</trans-unit>
<trans-unit id="Simplify_member_access_0">
<source>Simplify member access '{0}'</source>
<target state="translated">メンバーのアクセス '{0}' を単純化します</target>
<note />
</trans-unit>
<trans-unit id="Remove_Me_qualification">
<source>Remove 'Me' qualification</source>
<target state="translated">修飾子 'Me' を削除します</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified</source>
<target state="translated">名前を簡素化できます</target>
<note />
</trans-unit>
<trans-unit id="can_t_determine_valid_range_of_statements_to_extract_out">
<source>can't determine valid range of statements to extract out</source>
<target state="translated">抽出するステートメントの有効な範囲を決定できません</target>
<note />
</trans-unit>
<trans-unit id="Not_all_code_paths_return">
<source>Not all code paths return</source>
<target state="translated">返されないコード パスがあります</target>
<note />
</trans-unit>
<trans-unit id="contains_invalid_selection">
<source>contains invalid selection</source>
<target state="translated">無効な選択が含まれています</target>
<note />
</trans-unit>
<trans-unit id="the_selection_contains_syntactic_errors">
<source>the selection contains syntactic errors</source>
<target state="translated">選択範囲に構文エラーが含まれています</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_crossed_over_preprocessors">
<source>Selection can't be crossed over preprocessors</source>
<target state="translated">選択範囲はプリプロセッサと交差することはできません</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_contain_throw_without_enclosing_catch_block">
<source>Selection can't contain throw without enclosing catch block</source>
<target state="translated">選択範囲に外側の catch ブロックのない throw を含めることはできません</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_parts_of_constant_initializer_expression">
<source>Selection can't be parts of constant initializer expression</source>
<target state="translated">選択範囲は定数の初期化子式の一部にすることはできません</target>
<note />
</trans-unit>
<trans-unit id="Argument_used_for_ByRef_parameter_can_t_be_extracted_out">
<source>Argument used for ByRef parameter can't be extracted out</source>
<target state="translated">ByRef パラメーターに対して使用される引数は抽出できません</target>
<note />
</trans-unit>
<trans-unit id="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection">
<source>all static local usages defined in the selection must be included in the selection</source>
<target state="translated">選択範囲で定義されているすべてのスタティック ローカルの使用法は、選択範囲に含める必要があります</target>
<note />
</trans-unit>
<trans-unit id="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement">
<source>Implicit member access can't be included in the selection without containing statement</source>
<target state="translated">暗黙的なメンバー アクセスは、ステートメントを含まずに選択に入れることはできません</target>
<note />
</trans-unit>
<trans-unit id="Selection_must_be_part_of_executable_statements">
<source>Selection must be part of executable statements</source>
<target state="translated">選択範囲は実行可能なステートメントの一部にする必要があります</target>
<note />
</trans-unit>
<trans-unit id="next_statement_control_variable_doesn_t_have_matching_declaration_statement">
<source>next statement control variable doesn't have matching declaration statement</source>
<target state="translated">次のステートメントの制御変数に一致する宣言ステートメントがありません</target>
<note />
</trans-unit>
<trans-unit id="Selection_doesn_t_contain_any_valid_node">
<source>Selection doesn't contain any valid node</source>
<target state="translated">選択範囲に有効なノードが含まれていません</target>
<note />
</trans-unit>
<trans-unit id="no_valid_statement_range_to_extract_out">
<source>no valid statement range to extract out</source>
<target state="translated">抽出する有効なステートメントの範囲がありません</target>
<note />
</trans-unit>
<trans-unit id="Invalid_selection">
<source>Invalid selection</source>
<target state="translated">無効な選択</target>
<note />
</trans-unit>
<trans-unit id="Deprecated">
<source>Deprecated</source>
<target state="translated">非推奨</target>
<note />
</trans-unit>
<trans-unit id="Extension">
<source>Extension</source>
<target state="translated">拡張</target>
<note />
</trans-unit>
<trans-unit id="Awaitable">
<source>Awaitable</source>
<target state="translated">待機可能</target>
<note />
</trans-unit>
<trans-unit id="Awaitable_Extension">
<source>Awaitable, Extension</source>
<target state="translated">待機可能、拡張子</target>
<note />
</trans-unit>
<trans-unit id="new_variable">
<source><new variable></source>
<target state="translated"><新しい変数></target>
<note />
</trans-unit>
<trans-unit id="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName">
<source>Creates a delegate procedure instance that references the specified procedure.
AddressOf <procedureName></source>
<target state="translated">指定されたプロシージャを参照するデリゲート プロシージャ インスタンスを作成します。
AddressOf <procedureName></target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_an_external_procedure_has_another_name_in_its_DLL">
<source>Indicates that an external procedure has another name in its DLL.</source>
<target state="translated">外部プロシージャが DLL の中では別の名前を持つことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2">
<source>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated.
<result> = <expression1> AndAlso <expression2></source>
<target state="translated">2 つの式のショートサーキット論理積を求めます。両方のオペランドが True と評価された場合は True を返します。最初の式が False と評価された場合、2 番目の式は評価されません。
<result> = <expression1> AndAlso <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2">
<source>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated.
<result> = <expression1> And <expression2></source>
<target state="translated">2 つのブール式の場合は論理積、2 つの数値式の場合はビットごとの積を求めます。ブール式の場合、両方の式が True と評価されたときは True を返します。常に両方の式が評価されます。
<result> = <expression1> And <expression2></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default">
<source>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</source>
<target state="translated">Declare ステートメントで使用されます。Ansi 修飾子は Visual Basic がすべての文字列を ANSI 値にマーシャリングし、検索中にその名前を変更せずにプロシージャを調べることを指定します。文字が指定されていない場合の既定値は、ANSI です。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_data_type_in_a_declaration_statement">
<source>Specifies a data type in a declaration statement.</source>
<target state="translated">宣言ステートメントのデータ型を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">ソース ファイルの冒頭にある属性がアセンブリ全体に適用されることを示します。これを示さない場合、属性はクラスやプロパティなどの個別のプログラミング要素にのみ適用されます。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_asynchronous_method_that_can_use_the_Await_operator">
<source>Indicates an asynchronous method that can use the Await operator.</source>
<target state="translated">Await 演算子を使用できる非同期メソッドを示します。</target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails">
<source>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</source>
<target state="translated">Declare ステートメントで使用されます。Auto 修飾子は Visual Basic が .NET Framework の規則に従って文字列をマーシャリングし、実行時プラットフォームの基本文字セットを決定して、最初の検索が失敗した場合には外部プロシージャ名を変更することを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</source>
<target state="translated">呼び出されたプロシージャが、呼び出しコードの引数の基になる値を変更できるように引数を渡すことを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</source>
<target state="translated">呼び出されたプロシージャまたはプロパティが、呼び出しコードの引数の基になる値を変更できないように引数を渡すことを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class">
<source>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</source>
<target state="translated">クラスの名前を宣言し、そのクラスを構成する変数、プロパティ、メソッドの定義を示します。</target>
<note />
</trans-unit>
<trans-unit id="Generates_a_string_concatenation_of_two_expressions">
<source>Generates a string concatenation of two expressions.</source>
<target state="translated">2 つの式の文字列連結を生成します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_defines_one_or_more_constants">
<source>Declares and defines one or more constants.</source>
<target state="translated">1 つ以上の定数を宣言して定義します。</target>
<note />
</trans-unit>
<trans-unit id="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions">
<source>Use 'In' for a type that will only be used for ByVal arguments to functions.</source>
<target state="translated">関数への引数 ByVal としてのみ使用される型には 'In' を使用します。</target>
<note />
</trans-unit>
<trans-unit id="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions">
<source>Use 'Out' for a type that will only be used as a return from functions.</source>
<target state="translated">関数の戻り値としてのみ使用される型には 'Out' を使用します。</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type">
<source>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.
CType(Object As Expression, Object As Type) As Type</source>
<target state="translated">指定されたデータ型、オブジェクト、構造体、クラス、またはインターフェイスに式を明示的に変換した結果を返します。
CType(Object As Expression, Object As Type) As Type</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events">
<source>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</source>
<target state="translated">イベントに対してハンドラーの追加、ハンドラーの削除、イベントの発生に関する追加の特定コードが記述されていることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_reference_to_a_procedure_implemented_in_an_external_file">
<source>Declares a reference to a procedure implemented in an external file.</source>
<target state="translated">外部ファイルに実装されているプロシージャへの参照を宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface">
<source>Identifies a property as the default property of its class, structure, or interface.</source>
<target state="translated">クラス、構造体、またはインターフェイスの既定のプロパティとしてプロパティを識別します。</target>
<note />
</trans-unit>
<trans-unit id="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class">
<source>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</source>
<target state="translated">デリゲートの宣言に使用します。デリゲートとは、型の共有メソッドまたはオブジェクトのインスタンス メソッドを参照する参照型です。変換可能なプロシージャ、またはパラメーターの型と戻り値の型が一致するプロシージャを使用して、このデリゲート クラスのインスタンスを作成できます。</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket">
<source>Declares and allocates storage space for one or more variables.
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</source>
<target state="translated">記憶域を宣言し、1 つ以上の変数に割り当てます。
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_a_floating_point_result">
<source>Divides two numbers and returns a floating-point result.</source>
<target state="translated">2 つの数値を除算して、浮動小数点の結果を返します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_0_block">
<source>Terminates a {0} block.</source>
<target state="translated">{0} ブロックを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_an_0_block">
<source>Terminates an {0} block.</source>
<target state="translated">{0} ブロックを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_a_0_statement">
<source>Terminates the definition of a {0} statement.</source>
<target state="translated">{0} ステートメントの定義を終了します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_0_statement">
<source>Terminates the definition of an {0} statement.</source>
<target state="translated">{0} ステートメントの定義を終了します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_an_enumeration_and_defines_the_values_of_its_members">
<source>Declares an enumeration and defines the values of its members.</source>
<target state="translated">列挙体を宣言し、そのメンバーの値を定義します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are equal. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、両者が等しい場合は True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements">
<source>Used to release array variables and deallocate the memory used for their elements.</source>
<target state="translated">配列変数を解放し、それらの要素に使用されるメモリの割り当てを解除します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_user_defined_event">
<source>Declares a user-defined event.</source>
<target state="translated">ユーザー定義イベントを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure">
<source>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</source>
<target state="translated">Sub プロシージャを終了し、その実行を Sub プロシージャへの呼び出しに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Raises_a_number_to_the_power_of_another_number">
<source>Raises a number to the power of another number.</source>
<target state="translated">数値を別の数値のべき乗値に指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function">
<source>Specifies that the external procedure being referenced in the Declare statement is a Function.</source>
<target state="translated">Declare ステートメントで参照されている外部プロシージャが Function であることを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub">
<source>Specifies that the external procedure being referenced in the Declare statement is a Sub.</source>
<target state="translated">Declare ステートメントで参照されている外部プロシージャを Sub として指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration">
<source>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素が、その宣言を含むアセンブリ内からのみアクセス可能であることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_collection_and_a_range_variable_to_use_in_a_query">
<source>Specifies a collection and a range variable to use in a query.</source>
<target state="translated">クエリで使用するコレクションと範囲変数を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</source>
<target state="translated">Function プロシージャ (呼び出し元のコードに値を返すプロシージャ) を定義する名前、パラメーター、コードを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</source>
<target state="translated">参照型の型引数のみがジェネリック型パラメーターに渡されるように制約します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_constructor_constraint_on_a_generic_type_parameter">
<source>Specifies a constructor constraint on a generic type parameter.</source>
<target state="translated">ジェネリック型パラメーターにコンス トラクター制約を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a value type.</source>
<target state="translated">値型の型引数のみがジェネリック型パラメーターに渡されるように制約します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property">
<source>Declares a Get property procedure that is used to return the current value of a property.</source>
<target state="translated">プロパティの現在の値を返すために使用される Get プロパティ プロシージャを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目より大きい場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目以上の場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_that_a_procedure_handles_a_specified_event">
<source>Declares that a procedure handles a specified event.</source>
<target state="translated">プロシージャが指定されたイベントを処理することを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface">
<source>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</source>
<target state="translated">クラスまたは構造体のメンバーがインターフェイスで定義されているメンバーの実装を提供していることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears">
<source>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</source>
<target state="translated">Implements ステートメントが使用されるクラスまたは構造体の定義に実装する必要のある、1 つ以上のインターフェイス、またはインターフェイス メンバーを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Imports_all_or_specified_elements_of_a_namespace_into_a_file">
<source>Imports all or specified elements of a namespace into a file.</source>
<target state="translated">名前空間のすべてまたは指定された要素をファイルにインポートします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse">
<source>Specifies the group that the loop variable in a For Each statement is to traverse.</source>
<target state="translated">ループ変数が For Each ステートメント内で繰り返し処理するグループを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query">
<source>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</source>
<target state="translated">ループ変数が For Each ステートメントで繰り返し処理するグループを指定するか、クエリ内の範囲変数を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces">
<source>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</source>
<target state="translated">現在のクラスまたはインターフェイスが、属性、変数、プロパティ、プロシージャ、およびイベントを別のクラスまたは一連のインターフェイスから継承するようにします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query">
<source>Specifies the group that the range variable is to traverse in a query.</source>
<target state="translated">範囲変数がクエリでスキャンするグループを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_an_integer_result">
<source>Divides two numbers and returns an integer result.</source>
<target state="translated">2 つの数値を除算して、整数の結果を返します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface">
<source>Declares the name of an interface and the definitions of the members of the interface.</source>
<target state="translated">インターフェイスの名前と、インターフェイスのメンバーの定義を宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure">
<source>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</source>
<target state="translated">式が false であるかどうかを判断します。クラスまたは構造体のインスタンスが OrElse 句で使用される場合は、そのクラスまたは構造体で IsFalse を定義する必要があります。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2">
<source>Compares two object reference variables and returns True if the objects are equal.
<result> = <object1> Is <object2></source>
<target state="translated">2 つのオブジェクト参照変数を比較し、オブジェクトが等しい場合は True を返します
<result> = <object1> Is <object2></target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2">
<source>Compares two object reference variables and returns True if the objects are not equal.
<result> = <object1> IsNot <object2></source>
<target state="translated">2 つのオブジェクト参照変数を比較し、オブジェクトが等しくない場合は True を返します
<result> = <object1> IsNot <object2></target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure">
<source>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</source>
<target state="translated">式が true であるかどうかを判断します。クラスまたは構造体のインスタンスが OrElse 句で使用される場合は、そのクラスまたは構造体で IsTrue を定義する必要があります。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_iterator_method_that_can_use_the_Yield_statement">
<source>Indicates an iterator method that can use the Yield statement.</source>
<target state="translated">Yield ステートメントを使用できる反復子メソッドを示します。</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T">
<source>Defines an iterator lambda expression that can use the Yield statement.
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</source>
<target state="translated">Yield ステートメントを使用できる反復子ラムダ式を定義します。
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_left_shift_on_a_bit_pattern">
<source>Performs an arithmetic left shift on a bit pattern.</source>
<target state="translated">ビット パターンに対して算術左シフトを実行します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目より小さい場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、最初の式が 2 番目以下の場合は、True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure">
<source>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</source>
<target state="translated">外部プロシージャを含む外部ファイル (DLL またはコード リソース) を識別する句を導入します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern">
<source>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters.
<result> = <string> Like <pattern></source>
<target state="translated">文字列をパターンと比較します。利用できるワイルドカードには、1 文字に一致する ?、および 0 文字以上に一致する * があります。
<result> = <string> Like <pattern></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression">
<source>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</source>
<target state="translated">2 つの数値式の差、または数値式の負の値を返します。</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2">
<source>Divides two numbers and returns only the remainder.
<number1> Mod <number2></source>
<target state="translated">2つの数値を除算し、剰余のみを返します。
<数値1> Mod <数値2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">ソース ファイルの冒頭にある属性がモジュール全体に適用されることを示します。これを示さない場合、属性はクラスやプロパティなどの個別のプログラミング要素にのみ適用されます。</target>
<note />
</trans-unit>
<trans-unit id="Multiplies_two_numbers_and_returns_the_product">
<source>Multiplies two numbers and returns the product.</source>
<target state="translated">2 つの数値を乗算して積を返します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it">
<source>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</source>
<target state="translated">クラスが基本クラスとしてのみ使用でき、オブジェクトを直接作成できないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used">
<source>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</source>
<target state="translated">プロパティやプロシージャがこのクラスで実装されておらず、派生クラスでオーバーライドされないと使用できないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace">
<source>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</source>
<target state="translated">名前空間の名前を宣言し、宣言に続くソース コードがその名前空間内でコンパイルされるようにします。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</source>
<target state="translated">変換演算子 (CType) が、クラスまたは構造体を、元のクラスまたは構造体のいくつかの使用可能な値を保持できない可能性がある型に変換することを示します。</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</source>
<target state="translated">2 つの式を比較し、両者が等しくない場合は True を返します。それ以外の場合は False を返します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_cannot_be_used_as_a_base_class">
<source>Specifies that a class cannot be used as a base class.</source>
<target state="translated">クラスが基本クラスとして使用できないことを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression">
<source>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression.
<result> = Not <expression></source>
<target state="translated">ブール式で論理否定を実行するか、数値式でビット否定を実行します。
<result> = Not <expression></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class">
<source>Specifies that a property or procedure cannot be overridden in a derived class.</source>
<target state="translated">プロパティまたはプロシージャが派生クラスでオーバーライドできないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure">
<source>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</source>
<target state="translated">ジェネリック クラス、構造体、インターフェイス、デリゲート、またはプロシージャの型パラメーターを識別します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure">
<source>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</source>
<target state="translated">クラスまたは構造体に演算子プロシージャを定義する演算子記号、オペランド、およびコードを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called">
<source>Specifies that a procedure argument can be omitted when the procedure is called.</source>
<target state="translated">プロシージャが呼び出されるときにプロシージャ引数が省略可能であることを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file">
<source>Introduces a statement that specifies a compiler option that applies to the entire source file.</source>
<target state="translated">ソース ファイル全体に適用されるコンパイラ オプションを指定するステートメントを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2">
<source>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated.
<result> = <expression1> OrElse <expression2></source>
<target state="translated">2 つの式の包括的ショートサーキット論理和を求めます。少なくとも 1 つのオペランドが True と評価された場合は True を返します。最初の式が True と評価された場合、2 番目の式は評価されません。
<result> = <expression1> OrElse <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2">
<source>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Or <expression2></source>
<target state="translated">2 つのブール式の包括的論理和または 2 つの数値式のビットごとの和を求めます。ブール式の場合、少なくとも 1 つのオペランドが True と評価された場合は True を返します。常に両方のオペランドが評価されます。
<result> = <expression1> Or <expression2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name">
<source>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</source>
<target state="translated">プロパティまたはプロシージャが、同じ名前の 1 つ以上の既存のプロパティまたはプロシージャを再度宣言することを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class">
<source>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</source>
<target state="translated">プロパティまたはプロシージャが派生クラスで同じ名前のプロパティまたはプロシージャによってオーバーライドできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class">
<source>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</source>
<target state="translated">プロパティまたはプロシージャが基本クラスから継承された同じ名前のプロパティまたはプロシージャをオーバーライドすることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type">
<source>Specifies that a procedure parameter takes an optional array of elements of the specified type.</source>
<target state="translated">プロシージャのパラメーターが、指定された型の、省略可能な要素の配列を受け取ることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure">
<source>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</source>
<target state="translated">メソッド、クラス、または構造体の宣言が、メソッド、クラス、または構造体の部分定義であることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression">
<source>Returns the sum of two numbers, or the positive value of a numeric expression.</source>
<target state="translated">2 つの数値の合計、または数値式の正の値を返します。</target>
<note />
</trans-unit>
<trans-unit id="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed">
<source>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</source>
<target state="translated">配列の次元が変更されるときに配列の内容が消去されないようにします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure">
<source>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素が、モジュール内、クラス内、または構造体内からのみアクセスできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property">
<source>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</source>
<target state="translated">プロパティの名前、およびプロパティの値を格納して取得するために使用されるプロパティ プロシージャを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes">
<source>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</source>
<target state="translated">クラスの1 つ以上の宣言されたメンバーが同じアセンブリ、独自のクラス、および派生クラス内のいずれかからアクセスできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class">
<source>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素が、独自のクラス内または派生クラスからのみアクセスできることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions">
<source>Specifies that one or more declared programming elements have no access restrictions.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素にアクセス制限がないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to">
<source>Specifies that a variable or property can be read but not written to.</source>
<target state="translated">変数またはプロパティを読み込めるが、書き込みはできないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Reallocates_storage_space_for_an_array_variable">
<source>Reallocates storage space for an array variable.</source>
<target state="translated">配列変数の記憶域を再割り当てします。</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_right_shift_on_a_bit_pattern">
<source>Performs an arithmetic right shift on a bit pattern</source>
<target state="translated">ビット パターンに対して算術右シフトを実行します</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property">
<source>Declares a Set property procedure that is used to assign a value to a property.</source>
<target state="translated">値をプロパティに割り当てるのに使用する Set プロパティ プロシージャを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class">
<source>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</source>
<target state="translated">宣言されたプログラミング要素が、基本クラスにある、同じ名前を持つ要素を宣言し直して非表示にすることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure">
<source>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</source>
<target state="translated">1 つ以上の宣言されたプログラミング要素がクラスまたは構造体のすべてのインスタンスに関連付けられていることを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates">
<source>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</source>
<target state="translated">1 つ以上の宣言されているローカル変数が残存し、ローカル変数を宣言するプロシージャが終了した後もその最新の値が保持されるように指定します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure">
<source>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</source>
<target state="translated">構造体の名前を宣言し、その構造体を構成する変数、プロパティ、イベント、プロシージャの定義を示します。</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</source>
<target state="translated">Sub プロシージャ (呼び出しコードに値を返さないプロシージャ) を定義する名前、パラメーター、およびコードを宣言します。</target>
<note />
</trans-unit>
<trans-unit id="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range">
<source>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</source>
<target state="translated">ループ カウンター、配列の範囲、または値が一致する範囲の開始値と終了値を分割します。</target>
<note />
</trans-unit>
<trans-unit id="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName">
<source>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible.
<result> = TypeOf <objectExpression> Is <typeName></source>
<target state="translated">オブジェクト参照変数の実行時の型を判断して、データ型と比較します。2 つの型に互換性があるかどうかに応じて、True または False を返します。
<result> = TypeOf <objectExpression> Is <typeName></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name">
<source>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</source>
<target state="translated">Declare ステートメントで使用されます。Visual Basic が外部プロシージャ呼び出しのすべての文字列を Unicode 値にマーシャリングし、その名前を変更せずにプロシージャを検索することを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</source>
<target state="translated">変換演算子 (CType) が、クラスまたは構造体を、元のクラスまたは構造体のすべての使用可能な値を保持できる型に変換することを示します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events">
<source>Specifies that one or more declared member variables refer to an instance of a class that can raise events</source>
<target state="translated">1 つ以上の宣言されたメンバー変数が、イベントを発生させる可能性のあるクラスのインスタンスを参照していることを示します</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_can_be_written_to_but_not_read">
<source>Specifies that a property can be written to but not read.</source>
<target state="translated">プロパティに書き込みはできるが、読み込みはできないことを示します。</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2">
<source>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Xor <expression2></source>
<target state="translated">2 つのブール式の場合は排他的論理演算、2 つの数値式の場合はビットごとの排他を求めます。ブール式の場合、2 つの式のうち 1 つのみが True と評価されたときは True を返します。常に両方の式が評価されます。
<result> = <expression1> Xor <expression2></target>
<note />
</trans-unit>
<trans-unit id="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence">
<source>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</source>
<target state="translated">Sum、Average、Count などの集計関数をシーケンスに適用します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</source>
<target state="translated">クエリの Order By 句の並べ替え順序を指定します。最小の要素が最初に表示されます。</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order">
<source>Sets the string comparison method specified in Option Compare to a strict binary sort order.</source>
<target state="translated">Option Compare で指定する文字列の比較方法を、厳密なバイナリの並べ替え順序に設定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By">
<source>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</source>
<target state="translated">グループ化 (Group By) または並べ替え順序 (Order By) に対して使用される要素キーを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket">
<source>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure.
[Call] <procedureName> [(<argumentList>)]</source>
<target state="translated">Function、Sub、またはダイナミック リンク ライブラリ (DLL) プロシージャに実行を移します。
[Call] <procedureName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True">
<source>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</source>
<target state="translated">Select Case ステートメントの前述のケースのいずれも True を返さない場合に実行するステートメントを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True">
<source>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</source>
<target state="translated">後ろに比較演算子と式を付加すると、 Case Is 式と組み合わされた Select Case 式が True と評価された場合に実行されるステートメントを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression">
<source>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested.
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</source>
<target state="translated">Select Case ステートメントの式の値がテストされる値または値のセットを導入します。
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block">
<source>Introduces a statement block to be run if the specified exception occurs inside a Try block.</source>
<target state="translated">指定された例外が Try ブロックの内部で発生した場合に実行されるステートメント ブロックを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text">
<source>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order.
Option Compare {Binary | Text}</source>
<target state="translated">文字列のデータを比較するときに使用する、既定の比較方法を設定します。Text に設定する場合は、大文字と小文字を区別しないテキストの並べ替え順序を使用します。Binary に設定する場合は、厳密なバイナリ並べ替え順序を使用します。
Option Compare {Binary | Text}</target>
<note />
</trans-unit>
<trans-unit id="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals">
<source>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</source>
<target state="translated">条件付きコンパイラ定数を定義します。条件付きコンパイラ定数は、表示されるファイルに対しては常にプライベートです。初期化に使用される式には、条件付きコンパイラ定数とリテラルのみを含めることができます。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop">
<source>Transfers execution immediately to the next iteration of the Do loop.</source>
<target state="translated">実行を Do ループの次の反復処理に直ちに移します。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop">
<source>Transfers execution immediately to the next iteration of the For loop.</source>
<target state="translated">実行を For ループの次の反復処理に直ちに移します。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop">
<source>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</source>
<target state="translated">実行をループの次の反復処理に直ちに移します。Do ループ、For ループ、または While ループで使用できます。</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop">
<source>Transfers execution immediately to the next iteration of the While loop.</source>
<target state="translated">実行を While ループの次の反復処理に直ちに移します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</source>
<target state="translated">クエリの Order By 句の並べ替え順序を指定します。最大の要素が最初に表示されます。</target>
<note />
</trans-unit>
<trans-unit id="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values">
<source>Restricts the values of a query result to eliminate duplicate values.</source>
<target state="translated">重複した値がなくなるようにクエリ結果の値を制限します。</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition">
<source>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true.
Do...Loop {While | Until} <condition></source>
<target state="translated">ブール条件が true である間、または条件が true になるまで、ステートメント ブロックを繰り返します。
Do...Loop {While | Until} <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do Until <condition>...Loop</source>
<target state="translated">ブール条件が true になるまでステートメント ブロックを繰り返します。
Do Until <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop">
<source>Repeats a block of statements while a Boolean condition is true.
Do While <condition>...Loop</source>
<target state="translated">ブール条件が true である間、ステートメント ブロックを繰り返します。
Do While <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</source>
<target state="translated">前の条件が True として評価されていない場合にコンパイルされる #If ステートメントにステートメント グループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False">
<source>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</source>
<target state="translated">前の条件テストが False として評価されている場合にテストされる #If ステートメントの条件を導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails">
<source>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</source>
<target state="translated">前の条件テストが失敗した場合にテストされる If ステートメントの条件を導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</source>
<target state="translated">前の条件が True として評価されていない場合に実行される If ステートメントにステートメント グループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_SharpIf_block">
<source>Terminates the definition of an #If block.</source>
<target state="translated">#If ブロックの定義を終了します。</target>
<note />
</trans-unit>
<trans-unit id="Stops_execution_immediately">
<source>Stops execution immediately.</source>
<target state="translated">実行を直ちに停止します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_SharpRegion_block">
<source>Terminates a #Region block.</source>
<target state="translated">#Region ブロックを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation">
<source>Specifies the relationship between element keys to use as the basis of a join operation.</source>
<target state="translated">結合操作の基準として使用する要素キー間の関係を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Simulates_the_occurrence_of_an_error">
<source>Simulates the occurrence of an error.</source>
<target state="translated">エラーの発生をシミュレートします。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement">
<source>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</source>
<target state="translated">Do ループを終了し、その実行を Loop ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement">
<source>Exits a For loop and transfers execution immediately to the statement following the Next statement.</source>
<target state="translated">For ループを終了し、その実行を Next ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While">
<source>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition.
Exit {Do | For | Function | Property | Select | Sub | Try | While}</source>
<target state="translated">プロシージャまたはブロックを終了し、その実行をプロシージャ呼び出しまたはブロック定義に続くステートメントに直ちに転送します。
Exit {Do | For | Function | Property | Select | Sub | Try | While}</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement">
<source>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</source>
<target state="translated">Select ブロックを終了し、その実行を End Select ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement">
<source>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</source>
<target state="translated">Try ブロックを終了し、その実行を End Try ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement">
<source>Exits a While loop and transfers execution immediately to the statement following the End While statement.</source>
<target state="translated">While ループを終了し、その実行を End While ステートメントに続くステートメントに直ちに転送します。</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off">
<source>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement.
Option Explicit {On | Off}</source>
<target state="translated">On に設定されている場合は、Dim、Private、Public、または ReDim ステートメントを使用したすべての変数の明示的な宣言が必要です。
Option Explicit {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_fails_a_conditional_test">
<source>Represents a Boolean value that fails a conditional test.</source>
<target state="translated">条件テストを満たさないブール値を表します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure">
<source>Introduces a statement block to be run before exiting a Try structure.</source>
<target state="translated">Try 構造を終了する前に実行されるステートメント ブロックを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection">
<source>Introduces a loop that is repeated for each element in a collection.</source>
<target state="translated">コレクション内の要素ごとに繰り返されるループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_iterated_a_specified_number_of_times">
<source>Introduces a loop that is iterated a specified number of times.</source>
<target state="translated">指定された回数反復されるループを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_list_of_values_as_a_collection_initializer">
<source>Identifies a list of values as a collection initializer</source>
<target state="translated">コレクション初期化子として値一覧を識別します</target>
<note />
</trans-unit>
<trans-unit id="Branches_unconditionally_to_a_specified_line_in_a_procedure">
<source>Branches unconditionally to a specified line in a procedure.</source>
<target state="translated">プロシージャ内の指定した行に無条件に分岐します。</target>
<note />
</trans-unit>
<trans-unit id="Groups_elements_that_have_a_common_key">
<source>Groups elements that have a common key.</source>
<target state="translated">共通のキーを持つ要素をグループ化します。</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</source>
<target state="translated">2 つのシーケンスの要素を組み合わせて、結果をグループ化します。結合操作は一致するキーに基づきます。</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_0_should_be_created">
<source>Use 'Group' to specify that a group named '{0}' should be created.</source>
<target state="translated">Group' を使用して、'{0}' という名前のグループが作成されるように指定します。</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_Group_should_be_created">
<source>Use 'Group' to specify that a group named 'Group' should be created.</source>
<target state="translated">Group' を使用して、'Group' という名前のグループが作成されるように指定します。</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression">
<source>Conditionally compiles selected blocks of code, depending on the value of an expression.</source>
<target state="translated">式の値に応じて、選択したコード ブロックを条件付きでコンパイルします。</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression">
<source>Conditionally executes a group of statements, depending on the value of an expression.</source>
<target state="translated">式の値に応じて、ステートメント グループを条件付きで実行します。</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off">
<source>When set to On, allows the use of local type inference in declaring variables.
Option Infer {On | Off}</source>
<target state="translated">On に設定されている場合は、変数の宣言においてローカル型の推論を使用できます。
Option Infer {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression">
<source>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</source>
<target state="translated">結合またはグループ化サブ式の結果への参照として使用できる識別子を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences. The join operation is based on matching keys.</source>
<target state="translated">2 つのシーケンスの要素を組み合わせます。結合操作は一致するキーに基づきます。</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_key_field_in_an_anonymous_type_definition">
<source>Identifies a key field in an anonymous type definition.</source>
<target state="translated">匿名型の定義のキー フィールドを識別します。</target>
<note />
</trans-unit>
<trans-unit id="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable">
<source>Computes a value for each item in the query, and assigns the value to a new range variable.</source>
<target state="translated">クエリ内の各項目の値をコンピューティングし、新しい範囲変数に値を割り当てます。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_is_introduced_with_a_Do_statement">
<source>Terminates a loop that is introduced with a Do statement.</source>
<target state="translated">Do ステートメントで導入されるループを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do...Loop Until <condition></source>
<target state="translated">ブール条件が true になるまでステートメント ブロックを繰り返します。
Do...Loop Until <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition">
<source>Repeats a block of statements while a Boolean condition is true.
Do...Loop While <condition></source>
<target state="translated">ブール条件が true である間、ステートメント ブロックを繰り返します。
Do...Loop While <condition></target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running">
<source>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</source>
<target state="translated">クラスまたは構造体の現在の (コードが実行されている) インスタンスを参照する方法を提供します。</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods">
<source>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</source>
<target state="translated">現在のクラス インスタンスの基本クラスを参照する方法を提供します。MyBase を使用して、MustOverride 基本メソッドを呼び出すことはできません。</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides">
<source>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</source>
<target state="translated">最初に実装されたときの状態のクラスのインスタンス メンバーを参照する (派生クラスのオーバーライドをすべて無視する) 方法を提供します。</target>
<note />
</trans-unit>
<trans-unit id="Creates_a_new_object_instance">
<source>Creates a new object instance.</source>
<target state="translated">新しいオブジェクト インスタンスを作成します。</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable">
<source>Terminates a loop that iterates through the values of a loop variable.</source>
<target state="translated">ループ変数の値を反復処理するループを終了します。</target>
<note />
</trans-unit>
<trans-unit id="Represents_the_default_value_of_any_data_type">
<source>Represents the default value of any data type.</source>
<target state="translated">任意のデータ型の既定値を表します。</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_off">
<source>Turns a compiler option off.</source>
<target state="translated">コンパイラ オプションをオフにします。</target>
<note />
</trans-unit>
<trans-unit id="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket">
<source>Enables the error-handling routine that starts at the line specified in the line argument.
The specified line must be in the same procedure as the On Error statement.
On Error GoTo [<label> | 0 | -1]</source>
<target state="translated">行引数で指定された行から開始されるエラー処理ルーチンを有効にします。
指定された行は On Error ステートメントと同じプロシージャにする必要があります。
On Error GoTo [<label> | 0 | -1]</target>
<note />
</trans-unit>
<trans-unit id="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error">
<source>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</source>
<target state="translated">ランタイム エラーが発生すると、エラーが発生したステートメントまたはプロシージャ呼び出しに続くステートメントに実行が移ります。</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_on">
<source>Turns a compiler option on.</source>
<target state="translated">コンパイラ オプションをオンにします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation">
<source>Specifies the element keys used to correlate sequences for a join operation.</source>
<target state="translated">結合操作でシーケンスを関連付けるために使用される要素キーを指定します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used">
<source>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</source>
<target state="translated">クエリにおける列の並べ替え順序を指定します。Ascending キーワードまたは Descending キーワードの前に指定できます。いずれも指定されていない場合は、Ascending が使用されます。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent">
<source>Specifies the statements to run when the event is raised by the RaiseEvent statement.
RaiseEvent(<delegateSignature>)...End RaiseEvent</source>
<target state="translated">イベントを RaiseEvent ステートメントによって発生させる場合に実行するステートメントを指定します。
RaiseEvent(<delegateSignature>)...End RaiseEvent</target>
<note />
</trans-unit>
<trans-unit id="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket">
<source>Triggers an event declared at module level within a class, form, or document.
RaiseEvent <eventName> [(<argumentList>)]</source>
<target state="translated">モジュール レベルで宣言されたイベントをクラス、フォーム、またはドキュメントで発生させます。
RaiseEvent <eventName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Collapses_and_hides_sections_of_code_in_Visual_Basic_files">
<source>Collapses and hides sections of code in Visual Basic files.</source>
<target state="translated">Visual Basic ファイルのコードのセクションを折りたたんで非表示にします。</target>
<note />
</trans-unit>
<trans-unit id="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression">
<source>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure.
Return -or- Return <expression></source>
<target state="translated">Function、Sub、Get、Set、または Operator プロシージャを呼び出したコードに実行を戻します。
Return -or- Return <expression></target>
<note />
</trans-unit>
<trans-unit id="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression">
<source>Runs one of several groups of statements, depending on the value of an expression.</source>
<target state="translated">式の値に応じて、いくつかのステートメント グループのいずれかを実行します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_which_columns_to_include_in_the_result_of_a_query">
<source>Specifies which columns to include in the result of a query.</source>
<target state="translated">クエリの結果に含める列を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Skips_elements_up_to_a_specified_position_in_the_collection">
<source>Skips elements up to a specified position in the collection.</source>
<target state="translated">コレクション内の指定された位置までの要素をスキップします。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_how_much_to_increment_between_each_loop_iteration">
<source>Specifies how much to increment between each loop iteration.</source>
<target state="translated">ループの反復処理のたびにインクリメントする量を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Suspends_program_execution">
<source>Suspends program execution.</source>
<target state="translated">プログラムの実行を中断します。</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off">
<source>When set to On, restricts implicit data type conversions to only widening conversions.
Option Strict {On | Off}</source>
<target state="translated">On に設定されている場合は、 暗黙的なデータ型の変換を拡大変換のみに制限します。
Option Strict {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock">
<source>Ensures that multiple threads do not execute the statement block at the same time.
SyncLock <object>...End Synclock</source>
<target state="translated">複数のスレッドがステートメント ブロックを同時に実行しないようにします。
SyncLock <object>...End Synclock</target>
<note />
</trans-unit>
<trans-unit id="Includes_elements_up_to_a_specified_position_in_the_collection">
<source>Includes elements up to a specified position in the collection.</source>
<target state="translated">コレクション内の指定された位置までの要素が含まれます。</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive">
<source>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</source>
<target state="translated">Option Compare で指定する文字列の比較方法を、大文字と小文字を区別しないテキストの並べ替え順序に設定します。</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true">
<source>Introduces a statement block to be compiled or executed if a tested condition is true.</source>
<target state="translated">テストされた条件が True の場合にコンパイルまたは実行されるステートメント ブロックを導入します。</target>
<note />
</trans-unit>
<trans-unit id="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code">
<source>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</source>
<target state="translated">構造化例外処理コード、または非構造化例外処理コードで処理できるように、プロシージャ内で例外をスローします。</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_passes_a_conditional_test">
<source>Represents a Boolean value that passes a conditional test.</source>
<target state="translated">条件テストを満たすブール値を表します。</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try">
<source>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code.
Try...[Catch]...{Catch | Finally}...End Try</source>
<target state="translated">コードの実行中に、指定のコード ブロックで発生する可能性のあるエラーの一部またはすべてを処理する方法を提供します。
Try...[Catch]...{Catch | Finally}...End Try</target>
<note />
</trans-unit>
<trans-unit id="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using">
<source>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable.
Using <resource1>[, <resource2>]...End Using</source>
<target state="translated">Using ブロックは、リソース リストの変数を作成して初期化する、ブロックのコードを実行する、終了する前に変数を破棄する、という 3 つのことをします。Using ブロックで使用されるリソースは、System.IDisposable を実装する必要があります。
Using <resource1>[, <resource2>]...End Using</target>
<note />
</trans-unit>
<trans-unit id="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True">
<source>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</source>
<target state="translated">Catch ステートメントに条件テストを追加します。When キーワードの後に続く条件テストが True に評価されるときにのみ、その Catch ステートメントによって例外がキャッチされます。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_filtering_condition_for_a_range_variable_in_a_query">
<source>Specifies the filtering condition for a range variable in a query.</source>
<target state="translated">クエリで範囲変数のフィルター条件を指定します。</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true">
<source>Runs a series of statements as long as a given condition is true.</source>
<target state="translated">指定された条件が true である限り、一連のステートメントを実行します。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true">
<source>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</source>
<target state="translated">Skip および Take 操作の条件を指定します。条件が true である限り、要素はバイパスされるか含まれます。</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket">
<source>Specifies the declaration of property initializations in an object initializer.
New <typeName> With {[.<property> = <expression>][,...]}</source>
<target state="translated">オブジェクト初期化子のプロパティ初期化の宣言を指定します。
New <typeName> With {[.<property> = <expression>][,...]}</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With">
<source>Runs a series of statements that refer to a single object or structure.
With <object>...End With</source>
<target state="translated">1 つのオブジェクトまたは構造体を参照する一連のステートメントを実行します。
With <object>...End With</target>
<note />
</trans-unit>
<trans-unit id="Produces_an_element_of_an_IEnumerable_or_IEnumerator">
<source>Produces an element of an IEnumerable or IEnumerator.</source>
<target state="translated">IEnumerable または IEnumerator の要素を生成します。</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression">
<source>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected.
Async Sub/Function(<parameterList>) <expression></source>
<target state="translated">Await 演算子を使用できる非同期ラムダ式を定義します。デリゲート型が想定される場所であれば使用できます。
Async Sub/Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression">
<source>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected.
Function(<parameterList>) <expression></source>
<target state="translated">計算を行い、1 つの値を返すラムダ式を定義します。デリゲート型が想定される場所であれば使用できます。
Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement">
<source>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected.
Sub(<parameterList>) <statement></source>
<target state="translated">ステートメントを実行でき、値を返さないラムダ式を定義します。デリゲート型が想定される場所であれば使用できます。
Sub(<parameterList>) <statement></target>
<note />
</trans-unit>
<trans-unit id="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Disables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">現在の行以降のソース ファイルの部分で指定された警告のレポートを無効にします。</target>
<note />
</trans-unit>
<trans-unit id="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Enables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">現在の行以降のソース ファイルの部分で指定された警告のレポートを有効にします。</target>
<note />
</trans-unit>
<trans-unit id="Insert_Await">
<source>Insert 'Await'.</source>
<target state="translated">Await' を挿入します。</target>
<note />
</trans-unit>
<trans-unit id="Make_0_an_Async_Function">
<source>Make {0} an Async Function.</source>
<target state="translated">{0} を Async Function にします。</target>
<note />
</trans-unit>
<trans-unit id="Convert_0_to_Iterator">
<source>Convert {0} to Iterator</source>
<target state="translated">{0} を反復子に変換</target>
<note />
</trans-unit>
<trans-unit id="Replace_Return_with_Yield">
<source>Replace 'Return' with 'Yield</source>
<target state="translated">Return' を 'Yield' に置き換える</target>
<note />
</trans-unit>
<trans-unit id="Use_the_correct_control_variable">
<source>Use the correct control variable</source>
<target state="translated">正しい制御変数を使用する</target>
<note />
</trans-unit>
<trans-unit id="NameOf_function">
<source>NameOf function</source>
<target state="translated">NameOf 関数</target>
<note />
</trans-unit>
<trans-unit id="Generate_narrowing_conversion_in_0">
<source>Generate narrowing conversion in '{0}'</source>
<target state="translated">'{0}' で縮小変換を生成する</target>
<note />
</trans-unit>
<trans-unit id="Generate_widening_conversion_in_0">
<source>Generate widening conversion in '{0}'</source>
<target state="translated">'{0}' で拡大変換を生成する</target>
<note />
</trans-unit>
<trans-unit id="Try_block">
<source>Try block</source>
<target state="translated">Try ブロック</target>
<note>{Locked="Try"} "Try" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Catch_clause">
<source>Catch clause</source>
<target state="translated">Catch 句</target>
<note>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Finally_clause">
<source>Finally clause</source>
<target state="translated">Finally 句</target>
<note>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_statement">
<source>Using statement</source>
<target state="translated">Using ステートメント</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_block">
<source>Using block</source>
<target state="translated">Using ブロック</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_statement">
<source>With statement</source>
<target state="translated">With ステートメント</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_block">
<source>With block</source>
<target state="translated">With ブロック</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_statement">
<source>SyncLock statement</source>
<target state="translated">SyncLock ステートメント</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_block">
<source>SyncLock block</source>
<target state="translated">SyncLock ブロック</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_statement">
<source>For Each statement</source>
<target state="translated">For Each ステートメント</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_block">
<source>For Each block</source>
<target state="translated">For Each ブロック</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="On_Error_statement">
<source>On Error statement</source>
<target state="translated">On Error ステートメント</target>
<note>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Resume_statement">
<source>Resume statement</source>
<target state="translated">Resume ステートメント</target>
<note>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Yield_statement">
<source>Yield statement</source>
<target state="translated">Yield ステートメント</target>
<note>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Await_expression">
<source>Await expression</source>
<target state="translated">Await 式</target>
<note>{Locked="Await"} "Await" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Lambda">
<source>Lambda</source>
<target state="translated">ラムダ</target>
<note />
</trans-unit>
<trans-unit id="Where_clause">
<source>Where clause</source>
<target state="translated">Where 句</target>
<note>{Locked="Where"} "Where" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Select_clause">
<source>Select clause</source>
<target state="translated">Select 句</target>
<note>{Locked="Select"} "Select" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="From_clause">
<source>From clause</source>
<target state="translated">From 句</target>
<note>{Locked="From"} "From" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Aggregate_clause">
<source>Aggregate clause</source>
<target state="translated">Aggregate 句</target>
<note>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Let_clause">
<source>Let clause</source>
<target state="translated">Let 句</target>
<note>{Locked="Let"} "Let" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_clause">
<source>Join clause</source>
<target state="translated">Join 句</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_Join_clause">
<source>Group Join clause</source>
<target state="translated">Group Join 句</target>
<note>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_By_clause">
<source>Group By clause</source>
<target state="translated">Group By 句</target>
<note>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Function_aggregation">
<source>Function aggregation</source>
<target state="translated">関数集約</target>
<note />
</trans-unit>
<trans-unit id="Take_While_clause">
<source>Take While clause</source>
<target state="translated">Take While 句</target>
<note>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Skip_While_clause">
<source>Skip While clause</source>
<target state="translated">Skip While 句</target>
<note>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Ordering_clause">
<source>Ordering clause</source>
<target state="translated">Ordering 句</target>
<note>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_condition">
<source>Join condition</source>
<target state="translated">Join 条件</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="WithEvents_field">
<source>WithEvents field</source>
<target state="translated">WithEvents フィールド</target>
<note>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="as_clause">
<source>as clause</source>
<target state="translated">as 句</target>
<note>{Locked="as"} "as" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="type_parameters">
<source>type parameters</source>
<target state="translated">型パラメーター</target>
<note />
</trans-unit>
<trans-unit id="parameters">
<source>parameters</source>
<target state="translated">パラメーター</target>
<note />
</trans-unit>
<trans-unit id="attributes">
<source>attributes</source>
<target state="translated">属性</target>
<note />
</trans-unit>
<trans-unit id="Too_many_arguments_to_0">
<source>Too many arguments to '{0}'.</source>
<target state="translated">'{0}' の引数が多すぎます。</target>
<note />
</trans-unit>
<trans-unit id="Type_0_is_not_defined">
<source>Type '{0}' is not defined.</source>
<target state="translated">型 '{0}' は定義されていません。</target>
<note />
</trans-unit>
<trans-unit id="Add_Overloads">
<source>Add 'Overloads'</source>
<target state="translated">'Overloads' の追加</target>
<note>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll">
<source>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</source>
<target state="translated">指定されたアセンブリとそのすべての依存関係へのメタデータ参照を追加します (例: #r "myLib.dll")。</target>
<note />
</trans-unit>
<trans-unit id="Properties">
<source>Properties</source>
<target state="translated">プロパティ</target>
<note />
</trans-unit>
<trans-unit id="namespace_name">
<source><namespace name></source>
<target state="translated"><名前空間名></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_namespace">
<source>Type a name here to declare a namespace.</source>
<target state="translated">名前空間を宣言するには、ここに名前を入力してください。</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_class">
<source>Type a name here to declare a partial class.</source>
<target state="translated">部分クラスを宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="class_name">
<source><class name></source>
<target state="translated"><クラス名></target>
<note />
</trans-unit>
<trans-unit id="interface_name">
<source><interface name></source>
<target state="translated"><インターフェイス名></target>
<note />
</trans-unit>
<trans-unit id="module_name">
<source><module name></source>
<target state="translated"><モジュール名></target>
<note />
</trans-unit>
<trans-unit id="structure_name">
<source><structure name></source>
<target state="translated"><構造体名></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_interface">
<source>Type a name here to declare a partial interface.</source>
<target state="translated">部分インターフェイスを宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_module">
<source>Type a name here to declare a partial module.</source>
<target state="translated">部分モジュールを宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_structure">
<source>Type a name here to declare a partial structure.</source>
<target state="translated">部分構造体を宣言する名前をここに入力します。</target>
<note />
</trans-unit>
<trans-unit id="Event_add_handler_name">
<source>{0}.add</source>
<target state="translated">{0}.add</target>
<note>The name of an event add handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Event_remove_handler_name">
<source>{0}.remove</source>
<target state="translated">{0}.remove</target>
<note>The name of an event remove handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Property_getter_name">
<source>{0}.get</source>
<target state="translated">{0}.get</target>
<note>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Property_setter_name">
<source>{0}.set</source>
<target state="translated">{0}.set</target>
<note>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Make_Async_Function">
<source>Make Async Function</source>
<target state="translated">Async Function を作成する</target>
<note />
</trans-unit>
<trans-unit id="Make_Async_Sub">
<source>Make Async Sub</source>
<target state="translated">Async Sub にする</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_Select_Case">
<source>Convert to 'Select Case'</source>
<target state="translated">'Select Case' に変換する</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For_Each">
<source>Convert to 'For Each'</source>
<target state="translated">'For Each' に変換する</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For">
<source>Convert to 'For'</source>
<target state="translated">'For' に変換する</target>
<note />
</trans-unit>
<trans-unit id="Invert_If">
<source>Invert If</source>
<target state="translated">if を反転する</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/VisualBasicTest/ConvertForEachToFor/ConvertForEachToForTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForEachToFor
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForEachToFor
Partial Public Class ConvertForEachToForTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(
workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertForEachToForCodeRefactoringProvider()
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Body() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Console.WriteLine(a) : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function BlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For Each [||] a In array ' comment
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For {|Rename:i|} = 0 To array.Length - 1 ' comment
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment2() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment3() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next a ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next i ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment4() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3} ' test
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1 ' test
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment7() As Task
Dim initial = "
Class Test
Sub Method()
' test
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
' test
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestCommentsLiveBetweenForEachAndArrayDeclaration() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim Expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, Expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CommentNotSupportedCommentsAfterLineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _ ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function LineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _
In
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionStatement() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionConflict() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = 1
For Each [||] a In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = 1
Dim {|Rename:array1|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array1.Length - 1
Dim a = array1(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim a = array(i1)
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function VariableWritten() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
a = 1
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
{|Warning:Dim a = array(i)|}
a = 1
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
Public Async Function StructPropertyReadFromAndAssignedToLocal() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
Dim b = a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Dim b = a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function StructPropertyRead() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongCaretPosition() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {1, 2, 3}
[||]
Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestBefore() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[||] For Each a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestAfter() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each a In array [||]
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestSelection() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[|For Each a In array
Next|]
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Field() As Task
Dim initial = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For Each [||] a In list
Next
End Sub
End Class
"
Dim expected = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For {|Rename:i|} = 0 To list.Length - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function [Interface]() As Task
Dim initial = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For [||] Each a In list
Next
End Sub
End Class
"
Dim expected = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function ExplicitInterface() As Task
Dim initial = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
For [||] Each a In list
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Dim expected = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
Dim {|Rename:list1|} = DirectCast(list, IReadOnlyList(Of Integer))
For {|Rename:i|} = 0 To list1.Count - 1
Dim a = list1(i)
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each a [||] In New Integer() {}
For Each b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext2() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {}
For Each [||] b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {}
Console.WriteLine(a)
Next b
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function KeepNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next a
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next i
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict2() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] i In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim i = array(i1)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UseTypeAsUsedInForeach() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a As Integer In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a As Integer = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UniqueLocalName() As Task
Dim initial = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
For Each [||] a In New List(Of Integer)()
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
Dim {|Rename:list|} = New List(Of Integer)()
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, 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.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForEachToFor
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForEachToFor
Partial Public Class ConvertForEachToForTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(
workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertForEachToForCodeRefactoringProvider()
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Body() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Console.WriteLine(a) : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function BlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For Each [||] a In array ' comment
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For {|Rename:i|} = 0 To array.Length - 1 ' comment
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment2() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment3() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next a ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next i ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment4() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3} ' test
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1 ' test
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment7() As Task
Dim initial = "
Class Test
Sub Method()
' test
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
' test
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestCommentsLiveBetweenForEachAndArrayDeclaration() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim Expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, Expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CommentNotSupportedCommentsAfterLineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _ ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function LineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _
In
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionStatement() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionConflict() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = 1
For Each [||] a In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = 1
Dim {|Rename:array1|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array1.Length - 1
Dim a = array1(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim a = array(i1)
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function VariableWritten() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
a = 1
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
{|Warning:Dim a = array(i)|}
a = 1
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
Public Async Function StructPropertyReadFromAndAssignedToLocal() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
Dim b = a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Dim b = a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function StructPropertyRead() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongCaretPosition() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {1, 2, 3}
[||]
Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestBefore() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[||] For Each a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestAfter() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each a In array [||]
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestSelection() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[|For Each a In array
Next|]
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Field() As Task
Dim initial = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For Each [||] a In list
Next
End Sub
End Class
"
Dim expected = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For {|Rename:i|} = 0 To list.Length - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function [Interface]() As Task
Dim initial = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For [||] Each a In list
Next
End Sub
End Class
"
Dim expected = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function ExplicitInterface() As Task
Dim initial = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
For [||] Each a In list
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Dim expected = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
Dim {|Rename:list1|} = DirectCast(list, IReadOnlyList(Of Integer))
For {|Rename:i|} = 0 To list1.Count - 1
Dim a = list1(i)
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each a [||] In New Integer() {}
For Each b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext2() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {}
For Each [||] b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {}
Console.WriteLine(a)
Next b
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function KeepNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next a
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next i
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict2() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] i In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim i = array(i1)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UseTypeAsUsedInForeach() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a As Integer In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a As Integer = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UniqueLocalName() As Task
Dim initial = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
For Each [||] a In New List(Of Integer)()
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
Dim {|Rename:list|} = New List(Of Integer)()
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/TypeInferenceService/AbstractTypeInferenceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService
{
internal abstract partial class AbstractTypeInferenceService : ITypeInferenceService
{
protected abstract AbstractTypeInferrer CreateTypeInferrer(SemanticModel semanticModel, CancellationToken cancellationToken);
private static ImmutableArray<ITypeSymbol> InferTypeBasedOnNameIfEmpty(
SemanticModel semanticModel, ImmutableArray<ITypeSymbol> result, string nameOpt)
{
if (result.IsEmpty && nameOpt != null)
{
return InferTypeBasedOnName(semanticModel, nameOpt);
}
return result;
}
private static ImmutableArray<TypeInferenceInfo> InferTypeBasedOnNameIfEmpty(
SemanticModel semanticModel, ImmutableArray<TypeInferenceInfo> result, string nameOpt)
{
if (result.IsEmpty && nameOpt != null)
{
var types = InferTypeBasedOnName(semanticModel, nameOpt);
return types.SelectAsArray(t => new TypeInferenceInfo(t));
}
return result;
}
private static readonly ImmutableArray<string> s_booleanPrefixes =
ImmutableArray.Create("Is", "Has", "Contains", "Supports");
private static ImmutableArray<ITypeSymbol> InferTypeBasedOnName(
SemanticModel semanticModel, string name)
{
var matchesBoolean = MatchesBoolean(name);
return matchesBoolean
? ImmutableArray.Create<ITypeSymbol>(semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean))
: ImmutableArray<ITypeSymbol>.Empty;
}
private static bool MatchesBoolean(string name)
{
foreach (var prefix in s_booleanPrefixes)
{
if (Matches(name, prefix))
{
return true;
}
}
return false;
}
private static bool Matches(string name, string prefix)
{
if (name.StartsWith(prefix))
{
if (name.Length == prefix.Length)
{
return true;
}
var nextChar = name[prefix.Length];
return !char.IsLower(nextChar);
}
return false;
}
public ImmutableArray<ITypeSymbol> InferTypes(
SemanticModel semanticModel, int position,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken)
.InferTypes(position)
.Select(t => t.InferredType)
.ToImmutableArray();
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
public ImmutableArray<ITypeSymbol> InferTypes(
SemanticModel semanticModel, SyntaxNode expression,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken)
.InferTypes(expression)
.Select(info => info.InferredType)
.ToImmutableArray();
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(
SemanticModel semanticModel, int position,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(position);
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(
SemanticModel semanticModel, SyntaxNode expression,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(expression);
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService
{
internal abstract partial class AbstractTypeInferenceService : ITypeInferenceService
{
protected abstract AbstractTypeInferrer CreateTypeInferrer(SemanticModel semanticModel, CancellationToken cancellationToken);
private static ImmutableArray<ITypeSymbol> InferTypeBasedOnNameIfEmpty(
SemanticModel semanticModel, ImmutableArray<ITypeSymbol> result, string nameOpt)
{
if (result.IsEmpty && nameOpt != null)
{
return InferTypeBasedOnName(semanticModel, nameOpt);
}
return result;
}
private static ImmutableArray<TypeInferenceInfo> InferTypeBasedOnNameIfEmpty(
SemanticModel semanticModel, ImmutableArray<TypeInferenceInfo> result, string nameOpt)
{
if (result.IsEmpty && nameOpt != null)
{
var types = InferTypeBasedOnName(semanticModel, nameOpt);
return types.SelectAsArray(t => new TypeInferenceInfo(t));
}
return result;
}
private static readonly ImmutableArray<string> s_booleanPrefixes =
ImmutableArray.Create("Is", "Has", "Contains", "Supports");
private static ImmutableArray<ITypeSymbol> InferTypeBasedOnName(
SemanticModel semanticModel, string name)
{
var matchesBoolean = MatchesBoolean(name);
return matchesBoolean
? ImmutableArray.Create<ITypeSymbol>(semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean))
: ImmutableArray<ITypeSymbol>.Empty;
}
private static bool MatchesBoolean(string name)
{
foreach (var prefix in s_booleanPrefixes)
{
if (Matches(name, prefix))
{
return true;
}
}
return false;
}
private static bool Matches(string name, string prefix)
{
if (name.StartsWith(prefix))
{
if (name.Length == prefix.Length)
{
return true;
}
var nextChar = name[prefix.Length];
return !char.IsLower(nextChar);
}
return false;
}
public ImmutableArray<ITypeSymbol> InferTypes(
SemanticModel semanticModel, int position,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken)
.InferTypes(position)
.Select(t => t.InferredType)
.ToImmutableArray();
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
public ImmutableArray<ITypeSymbol> InferTypes(
SemanticModel semanticModel, SyntaxNode expression,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken)
.InferTypes(expression)
.Select(info => info.InferredType)
.ToImmutableArray();
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(
SemanticModel semanticModel, int position,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(position);
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(
SemanticModel semanticModel, SyntaxNode expression,
string nameOpt, CancellationToken cancellationToken)
{
var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(expression);
return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/Core/MSBuild/MSBuild/VisualBasic/VisualBasicProjectFile.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicProjectFile : ProjectFile
{
public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
: base(loader, loadedProject, buildManager, log)
{
}
protected override SourceCodeKind GetSourceCodeKind(string documentFileName)
=> SourceCodeKind.Regular;
public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
=> ".vb";
protected override IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject)
=> executedProject.GetItems(ItemNames.VbcCommandLineArgs);
protected override ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project)
=> VisualBasicCommandLineArgumentReader.Read(project);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.MSBuild.Build;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicProjectFile : ProjectFile
{
public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluation.Project? loadedProject, ProjectBuildManager buildManager, DiagnosticLog log)
: base(loader, loadedProject, buildManager, log)
{
}
protected override SourceCodeKind GetSourceCodeKind(string documentFileName)
=> SourceCodeKind.Regular;
public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
=> ".vb";
protected override IEnumerable<MSB.Framework.ITaskItem> GetCompilerCommandLineArgs(MSB.Execution.ProjectInstance executedProject)
=> executedProject.GetItems(ItemNames.VbcCommandLineArgs);
protected override ImmutableArray<string> ReadCommandLineArgs(MSB.Execution.ProjectInstance project)
=> VisualBasicCommandLineArgumentReader.Read(project);
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/Core/Portable/ChangeSignature/AbstractChangeSignatureService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync(
IMethodSymbol symbol, Document document, CancellationToken cancellationToken);
public abstract Task<SyntaxNode> ChangeSignatureAsync(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document);
protected abstract T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument) where T : SyntaxNode;
protected abstract SyntaxToken CommaTokenWithElasticSpace();
/// <summary>
/// For some Foo(int x, params int[] p), this helps convert the "1, 2, 3" in Foo(0, 1, 2, 3)
/// to "new int[] { 1, 2, 3 }" in Foo(0, new int[] { 1, 2, 3 });
/// </summary>
protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol);
protected abstract SyntaxNode AddNameToArgument(SyntaxNode argument, string name);
/// <summary>
/// Only some languages support:
/// - Optional parameters and params arrays simultaneously in declarations
/// - Passing the params array as a named argument
/// </summary>
protected abstract bool SupportsOptionalAndParamsArrayParametersSimultaneously();
protected abstract bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor);
/// <summary>
/// A temporarily hack that should be removed once/if https://github.com/dotnet/roslyn/issues/53092 is fixed.
/// </summary>
protected abstract ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol);
protected abstract SyntaxGenerator Generator { get; }
protected abstract ISyntaxFacts SyntaxFacts { get; }
public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetChangeSignatureContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext
? ImmutableArray.Create(new ChangeSignatureCodeAction(this, changeSignatureAnalyzedSucceedContext))
: ImmutableArray<ChangeSignatureCodeAction>.Empty;
}
internal async Task<ChangeSignatureAnalyzedContext> GetChangeSignatureContextAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var (symbol, selectedIndex) = await GetInvocationSymbolAsync(
document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-language symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol is IMethodSymbol method)
{
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol ev)
{
symbol = ev.Type;
}
if (symbol is INamedTypeSymbol typeSymbol)
{
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
else if (TryGetRecordPrimaryConstructor(typeSymbol, out var primaryConstructor))
{
symbol = primaryConstructor;
}
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
// This should be called after the metadata check above to avoid looking for nodes in metadata.
var declarationLocation = symbol.Locations.FirstOrDefault();
if (declarationLocation == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
var solution = document.Project.Solution;
var declarationDocument = solution.GetRequiredDocument(declarationLocation.SourceTree!);
var declarationChangeSignatureService = declarationDocument.GetRequiredLanguageService<AbstractChangeSignatureService>();
int positionForTypeBinding;
var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault();
if (reference != null)
{
var syntax = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
positionForTypeBinding = syntax.SpanStart;
}
else
{
// There may be no declaring syntax reference, for example delegate Invoke methods.
// The user may need to fully-qualify type names, including the type(s) defined in
// this document.
positionForTypeBinding = 0;
}
var parameterConfiguration = ParameterConfiguration.Create(
GetParameters(symbol).Select(p => new ExistingParameter(p)).ToImmutableArray<Parameter>(),
symbol.IsExtensionMethod(), selectedIndex);
return new ChangeSignatureAnalysisSucceededContext(
declarationDocument, positionForTypeBinding, symbol, parameterConfiguration);
}
internal async Task<ChangeSignatureResult> ChangeSignatureWithContextAsync(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
return context switch
{
ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext => await GetChangeSignatureResultAsync(changeSignatureAnalyzedSucceedContext, options, cancellationToken).ConfigureAwait(false),
CannotChangeSignatureAnalyzedContext cannotChangeSignatureAnalyzedContext => new ChangeSignatureResult(succeeded: false, changeSignatureFailureKind: cannotChangeSignatureAnalyzedContext.CannotChangeSignatureReason),
_ => throw ExceptionUtilities.Unreachable,
};
async Task<ChangeSignatureResult> GetChangeSignatureResultAsync(ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
if (options == null)
{
return new ChangeSignatureResult(succeeded: false);
}
var (updatedSolution, confirmationMessage) = await CreateUpdatedSolutionAsync(context, options, cancellationToken).ConfigureAwait(false);
return new ChangeSignatureResult(updatedSolution != null, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges, confirmationMessage: confirmationMessage);
}
}
/// <returns>Returns <c>null</c> if the operation is cancelled.</returns>
internal static ChangeSignatureOptionsResult? GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context)
{
if (context is not ChangeSignatureAnalysisSucceededContext succeededContext)
{
return null;
}
var changeSignatureOptionsService = succeededContext.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>();
return changeSignatureOptionsService.GetChangeSignatureOptions(
succeededContext.Document, succeededContext.PositionForTypeBinding, succeededContext.Symbol, succeededContext.ParameterConfiguration);
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
var streamingProgress = new StreamingProgressCollector();
var engine = new FindReferencesSearchEngine(
solution,
documents: null,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
streamingProgress,
FindReferencesSearchOptions.Default);
await engine.FindReferencesAsync(symbol, cancellationToken).ConfigureAwait(false);
return streamingProgress.GetReferencedSymbols();
}
}
#nullable enable
private async Task<(Solution updatedSolution, string? confirmationMessage)> CreateUpdatedSolutionAsync(
ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
var telemetryTimer = Stopwatch.StartNew();
var currentSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
string? confirmationMessage = null;
var symbols = await FindChangeSignatureReferencesAsync(
declaredSymbol, context.Solution, cancellationToken).ConfigureAwait(false);
var declaredSymbolParametersCount = GetParameters(declaredSymbol).Length;
var telemetryNumberOfDeclarationsToUpdate = 0;
var telemetryNumberOfReferencesToUpdate = 0;
foreach (var symbol in symbols)
{
var methodSymbol = symbol.Definition as IMethodSymbol;
if (methodSymbol != null &&
(methodSymbol.MethodKind == MethodKind.PropertyGet || methodSymbol.MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters is IEventSymbol eventSymbol)
{
if (eventSymbol.Type is INamedTypeSymbol type && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (methodSymbol != null)
{
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
// We update delegates which may have different signature.
// It seems it is enough for now to compare delegates by parameter count only.
if (methodSymbol.Parameters.Length != declaredSymbolParametersCount)
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
if (!TryGetNodeWithEditableSignatureOrAttributes(def, currentSolution, out var nodeToUpdate, out var documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
telemetryNumberOfDeclarationsToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, currentSolution, out var nodeToUpdate2, out var documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
telemetryNumberOfReferencesToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = currentSolution.GetRequiredDocument(docId);
var updater = doc.Project.LanguageServices.GetRequiredService<AbstractChangeSignatureService>();
var root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignatureAsync(
doc,
definitionToUse[originalNode],
potentiallyUpdatedNode,
originalNode,
UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(definitionToUse[originalNode], options.UpdatedSignature),
cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.Format(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: await doc.GetOptionsAsync(cancellationToken).ConfigureAwait(false),
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
var updatedDoc = currentSolution.GetRequiredDocument(docId).WithSyntaxRoot(updatedRoots[docId]);
var docWithImports = await ImportAdder.AddImportsFromSymbolAnnotationAsync(updatedDoc, cancellationToken: cancellationToken).ConfigureAwait(false);
var reducedDoc = await Simplifier.ReduceAsync(docWithImports, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
var formattedDoc = await Formatter.FormatAsync(reducedDoc, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);
currentSolution = currentSolution.WithDocumentSyntaxRoot(docId, (await formattedDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false))!);
}
telemetryTimer.Stop();
ChangeSignatureLogger.LogCommitInformation(telemetryNumberOfDeclarationsToUpdate, telemetryNumberOfReferencesToUpdate, (int)telemetryTimer.ElapsedMilliseconds);
return (currentSolution, confirmationMessage);
}
#nullable disable
private static void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private static bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
var node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.GetLanguageService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected ImmutableArray<IUnifiedArgumentSyntax> PermuteArguments(
ISymbol declarationSymbol,
ImmutableArray<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = GetParameters(declarationSymbol);
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Length).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (var i = 0; i < declarationParametersToPermute.Length; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex ?? -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = ArrayBuilder<IUnifiedArgumentSyntax>.GetInstance();
var expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
var seenNamedArgument = false;
// Holds the params array argument so it can be
// added at the end.
IUnifiedArgumentSyntax paramsArrayArgument = null;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if (!param.IsParams)
{
// If seen a named argument before, add names for subsequent ones.
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
}
else
{
paramsArrayArgument = argument;
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the params argument with the first value:
if (paramsArrayArgument != null)
{
var param = argumentToParameterMap[paramsArrayArgument];
if (seenNamedArgument && !paramsArrayArgument.IsNamed)
{
newArguments.Add(paramsArrayArgument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(paramsArrayArgument);
}
}
// 6. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
var removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (var i = declarationParametersToPermute.Length; i < arguments.Length; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Length)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments.ToImmutableAndFree();
}
/// <summary>
/// Sometimes signature changes can cascade from a declaration with m parameters to one with n > m parameters, such as
/// delegate Invoke methods (m) and delegate BeginInvoke methods (n = m + 2). This method adds on those extra parameters
/// to the base <see cref="SignatureChange"/>.
/// </summary>
private SignatureChange UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
var realParameters = GetParameters(declarationSymbol);
if (realParameters.Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Length)
{
var originalConfigurationParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var updatedConfigurationParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var bonusParameters = realParameters.Skip(originalConfigurationParameters.Length);
var originalConfigurationParametersWithExtraParameters = originalConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
var updatedConfigurationParametersWithExtraParameters = updatedConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
updatedSignature = new SignatureChange(
ParameterConfiguration.Create(originalConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0),
ParameterConfiguration.Create(updatedConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0));
}
return updatedSignature;
}
private static ImmutableArray<IParameterSymbol> GetParametersToPermute(
ImmutableArray<IUnifiedArgumentSyntax> arguments,
ImmutableArray<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
var position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = ArrayBuilder<IParameterSymbol>.GetInstance();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Length)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute.ToImmutableAndFree();
}
/// <summary>
/// Given the cursor position, find which parameter is selected.
/// Returns 0 as the default value. Note that the ChangeSignature dialog adjusts the selection for
/// the `this` parameter in extension methods (the selected index won't remain 0).
/// </summary>
protected static int GetParameterIndex<TNode>(SeparatedSyntaxList<TNode> parameters, int position)
where TNode : SyntaxNode
{
if (parameters.Count == 0)
{
return 0;
}
if (position < parameters.Span.Start)
{
return 0;
}
if (position > parameters.Span.End)
{
return 0;
}
for (var i = 0; i < parameters.Count - 1; i++)
{
// `$$,` points to the argument before the separator
// but `,$$` points to the argument following the separator
if (position <= parameters.GetSeparator(i).Span.Start)
{
return i;
}
}
return parameters.Count - 1;
}
protected (ImmutableArray<T> parameters, ImmutableArray<SyntaxToken> separators) UpdateDeclarationBase<T>(
SeparatedSyntaxList<T> list,
SignatureChange updatedSignature,
Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode
{
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var numAddedParameters = 0;
// Iterate through the list of new parameters and combine any
// preexisting parameters with added parameters to construct
// the full updated list.
var newParameters = ImmutableArray.CreateBuilder<T>();
for (var index = 0; index < reorderedParameters.Length; index++)
{
var newParam = reorderedParameters[index];
if (newParam is ExistingParameter existingParameter)
{
var pos = originalParameters.IndexOf(p => p is ExistingParameter ep && ep.Symbol.Equals(existingParameter.Symbol));
var param = list[pos];
if (index < list.Count)
{
param = TransferLeadingWhitespaceTrivia(param, list[index]);
}
else
{
param = param.WithLeadingTrivia();
}
newParameters.Add(param);
}
else
{
// Added parameter
var newParameter = createNewParameterMethod((AddedParameter)newParam);
if (index < list.Count)
{
newParameter = TransferLeadingWhitespaceTrivia(newParameter, list[index]);
}
else
{
newParameter = newParameter.WithLeadingTrivia();
}
newParameters.Add(newParameter);
numAddedParameters++;
}
}
// (a,b,c)
// Adding X parameters, need to add X separators.
var numSeparatorsToSkip = originalParameters.Length - reorderedParameters.Length;
if (originalParameters.Length == 0)
{
// ()
// Adding X parameters, need to add X-1 separators.
numSeparatorsToSkip++;
}
return (newParameters.ToImmutable(), GetSeparators(list, numSeparatorsToSkip));
}
protected ImmutableArray<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip) where T : SyntaxNode
{
var separators = ImmutableArray.CreateBuilder<SyntaxToken>();
for (var i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++)
{
separators.Add(i < arguments.SeparatorCount
? arguments.GetSeparator(i)
: CommaTokenWithElasticSpace());
}
return separators.ToImmutable();
}
protected virtual async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync(
ISymbol declarationSymbol,
SeparatedSyntaxList<SyntaxNode> newArguments,
SignatureChange signaturePermutation,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
bool generateAttributeArguments,
Document document,
int position,
CancellationToken cancellationToken)
{
var fullList = ArrayBuilder<SyntaxNode>.GetInstance();
var separators = ArrayBuilder<SyntaxToken>.GetInstance();
var updatedParameters = signaturePermutation.UpdatedConfiguration.ToListOfParameters();
var indexInListOfPreexistingArguments = 0;
var seenNamedArguments = false;
var seenOmitted = false;
var paramsHandled = false;
for (var i = 0; i < updatedParameters.Length; i++)
{
// Skip this parameter in list of arguments for extension method calls but not for reduced ones.
if (updatedParameters[i] != signaturePermutation.UpdatedConfiguration.ThisParameter
|| !isReducedExtensionMethod)
{
var parameters = GetParameters(declarationSymbol);
if (updatedParameters[i] is AddedParameter addedParameter)
{
// Omitting an argument only works in some languages, depending on whether
// there is a params array. We sometimes need to reinterpret an requested
// omitted parameter as one with a TODO requested.
var forcedCallsiteErrorDueToParamsArray = addedParameter.CallSiteKind == CallSiteKind.Omitted &&
parameters.LastOrDefault()?.IsParams == true &&
!SupportsOptionalAndParamsArrayParametersSimultaneously();
var isCallsiteActuallyOmitted = addedParameter.CallSiteKind == CallSiteKind.Omitted && !forcedCallsiteErrorDueToParamsArray;
var isCallsiteActuallyTODO = addedParameter.CallSiteKind == CallSiteKind.Todo || forcedCallsiteErrorDueToParamsArray;
if (isCallsiteActuallyOmitted)
{
seenOmitted = true;
seenNamedArguments = true;
continue;
}
var expression = await GenerateInferredCallsiteExpressionAsync(
document,
position,
addedParameter,
cancellationToken).ConfigureAwait(false);
if (expression == null)
{
// If we tried to infer the expression but failed, use a TODO instead.
isCallsiteActuallyTODO |= addedParameter.CallSiteKind == CallSiteKind.Inferred;
expression = Generator.ParseExpression(isCallsiteActuallyTODO ? "TODO" : addedParameter.CallSiteValue);
}
// TODO: Need to be able to specify which kind of attribute argument it is to the SyntaxGenerator.
// https://github.com/dotnet/roslyn/issues/43354
var argument = generateAttributeArguments ?
Generator.AttributeArgument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
expression: expression) :
Generator.Argument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
refKind: RefKind.None,
expression: expression);
fullList.Add(argument);
separators.Add(CommaTokenWithElasticSpace());
}
else
{
if (indexInListOfPreexistingArguments == parameters.Length - 1 &&
parameters[indexInListOfPreexistingArguments].IsParams)
{
// Handling params array
if (seenOmitted)
{
// Need to ensure the params array is an actual array, and that the argument is named.
if (isParamsArrayExpanded)
{
var newArgument = CreateExplicitParamsArrayFromIndividualArguments(newArguments, indexInListOfPreexistingArguments, parameters[indexInListOfPreexistingArguments]);
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
var newArgument = newArguments[indexInListOfPreexistingArguments];
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
paramsHandled = true;
}
else
{
// Normal case. Handled later.
}
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
if (SyntaxFacts.IsNamedArgument(newArguments[indexInListOfPreexistingArguments]))
{
seenNamedArguments = true;
}
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
var newArgument = newArguments[indexInListOfPreexistingArguments];
if (seenNamedArguments && !SyntaxFacts.IsNamedArgument(newArgument))
{
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
}
fullList.Add(newArgument);
indexInListOfPreexistingArguments++;
}
}
}
}
if (!paramsHandled)
{
// Add the rest of existing parameters, e.g. from the params argument.
while (indexInListOfPreexistingArguments < newArguments.Count)
{
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
fullList.Add(newArguments[indexInListOfPreexistingArguments++]);
}
}
if (fullList.Count == separators.Count && separators.Count != 0)
{
separators.Remove(separators.Last());
}
return Generator.SeparatedList(fullList.ToImmutableAndFree(), separators.ToImmutableAndFree());
}
private async Task<SyntaxNode> GenerateInferredCallsiteExpressionAsync(
Document document,
int position,
AddedParameter addedParameter,
CancellationToken cancellationToken)
{
if (addedParameter.CallSiteKind != CallSiteKind.Inferred || !addedParameter.TypeBinds)
{
return null;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var recommendations = await Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, position, document.Project.Solution.Workspace, options: null, cancellationToken).ConfigureAwait(false);
var sourceSymbols = recommendations.Where(r => r.IsNonImplicitAndFromSource());
// For locals, prefer the one with the closest declaration. Because we used the Recommender,
// we do not have to worry about filtering out inaccessible locals.
// TODO: Support range variables here as well: https://github.com/dotnet/roslyn/issues/44689
var orderedLocalAndParameterSymbols = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Local) || s.IsKind(SymbolKind.Parameter))
.OrderByDescending(s => s.Locations.First().SourceSpan.Start);
// No particular ordering preference for properties/fields.
var orderedPropertiesAndFields = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Property) || s.IsKind(SymbolKind.Field));
var fullyOrderedSymbols = orderedLocalAndParameterSymbols.Concat(orderedPropertiesAndFields);
foreach (var symbol in fullyOrderedSymbols)
{
var symbolType = symbol.GetSymbolType();
if (symbolType == null)
{
continue;
}
if (semanticModel.Compilation.ClassifyCommonConversion(symbolType, addedParameter.Type).IsImplicit)
{
return Generator.IdentifierName(symbol.Name);
}
}
return null;
}
protected ImmutableArray<SyntaxTrivia> GetPermutedDocCommentTrivia(Document document, SyntaxNode node, ImmutableArray<SyntaxNode> permutedParamNodes)
{
var updatedLeadingTrivia = ImmutableArray.CreateBuilder<SyntaxTrivia>();
var index = 0;
SyntaxTrivia lastWhiteSpaceTrivia = default;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
foreach (var trivia in node.GetLeadingTrivia())
{
if (!trivia.HasStructure)
{
if (syntaxFacts.IsWhitespaceTrivia(trivia))
{
lastWhiteSpaceTrivia = trivia;
}
updatedLeadingTrivia.Add(trivia);
continue;
}
var structuredTrivia = trivia.GetStructure();
if (!syntaxFacts.IsDocumentationComment(structuredTrivia))
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var updatedNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
var structuredContent = syntaxFacts.GetContentFromDocumentationCommentTriviaSyntax(trivia);
for (var i = 0; i < structuredContent.Count; i++)
{
var content = structuredContent[i];
if (!syntaxFacts.IsParameterNameXmlElementSyntax(content))
{
updatedNodeList.Add(content);
continue;
}
// Found a param tag, so insert the next one from the reordered list
if (index < permutedParamNodes.Length)
{
updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia()));
index++;
}
else
{
// Inspecting a param element that we are deleting but not replacing.
}
}
var newDocComments = Generator.DocumentationCommentTriviaWithUpdatedContent(trivia, updatedNodeList.ToImmutableAndFree());
newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia());
var newTrivia = Generator.Trivia(newDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
var extraNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
while (index < permutedParamNodes.Length)
{
extraNodeList.Add(permutedParamNodes[index]);
index++;
}
if (extraNodeList.Any())
{
var extraDocComments = Generator.DocumentationCommentTrivia(
extraNodeList,
node.GetTrailingTrivia(),
lastWhiteSpaceTrivia,
document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language));
var newTrivia = Generator.Trivia(extraDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
extraNodeList.Free();
return updatedLeadingTrivia.ToImmutable();
}
protected static bool IsParamsArrayExpandedHelper(ISymbol symbol, int argumentCount, bool lastArgumentIsNamed, SemanticModel semanticModel, SyntaxNode lastArgumentExpression, CancellationToken cancellationToken)
{
if (symbol is IMethodSymbol methodSymbol && methodSymbol.Parameters.LastOrDefault()?.IsParams == true)
{
if (argumentCount > methodSymbol.Parameters.Length)
{
return true;
}
if (argumentCount == methodSymbol.Parameters.Length)
{
if (lastArgumentIsNamed)
{
// If the last argument is named, then it cannot be part of an expanded params array.
return false;
}
else
{
var fromType = semanticModel.GetTypeInfo(lastArgumentExpression, cancellationToken);
var toType = methodSymbol.Parameters.Last().Type;
return !semanticModel.Compilation.HasImplicitConversion(fromType.Type, toType);
}
}
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync(
IMethodSymbol symbol, Document document, CancellationToken cancellationToken);
public abstract Task<SyntaxNode> ChangeSignatureAsync(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document);
protected abstract T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument) where T : SyntaxNode;
protected abstract SyntaxToken CommaTokenWithElasticSpace();
/// <summary>
/// For some Foo(int x, params int[] p), this helps convert the "1, 2, 3" in Foo(0, 1, 2, 3)
/// to "new int[] { 1, 2, 3 }" in Foo(0, new int[] { 1, 2, 3 });
/// </summary>
protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol);
protected abstract SyntaxNode AddNameToArgument(SyntaxNode argument, string name);
/// <summary>
/// Only some languages support:
/// - Optional parameters and params arrays simultaneously in declarations
/// - Passing the params array as a named argument
/// </summary>
protected abstract bool SupportsOptionalAndParamsArrayParametersSimultaneously();
protected abstract bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor);
/// <summary>
/// A temporarily hack that should be removed once/if https://github.com/dotnet/roslyn/issues/53092 is fixed.
/// </summary>
protected abstract ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol);
protected abstract SyntaxGenerator Generator { get; }
protected abstract ISyntaxFacts SyntaxFacts { get; }
public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetChangeSignatureContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext
? ImmutableArray.Create(new ChangeSignatureCodeAction(this, changeSignatureAnalyzedSucceedContext))
: ImmutableArray<ChangeSignatureCodeAction>.Empty;
}
internal async Task<ChangeSignatureAnalyzedContext> GetChangeSignatureContextAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var (symbol, selectedIndex) = await GetInvocationSymbolAsync(
document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false);
// Cross-language symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol is IMethodSymbol method)
{
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol ev)
{
symbol = ev.Type;
}
if (symbol is INamedTypeSymbol typeSymbol)
{
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
else if (TryGetRecordPrimaryConstructor(typeSymbol, out var primaryConstructor))
{
symbol = primaryConstructor;
}
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind);
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
// This should be called after the metadata check above to avoid looking for nodes in metadata.
var declarationLocation = symbol.Locations.FirstOrDefault();
if (declarationLocation == null)
{
return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata);
}
var solution = document.Project.Solution;
var declarationDocument = solution.GetRequiredDocument(declarationLocation.SourceTree!);
var declarationChangeSignatureService = declarationDocument.GetRequiredLanguageService<AbstractChangeSignatureService>();
int positionForTypeBinding;
var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault();
if (reference != null)
{
var syntax = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
positionForTypeBinding = syntax.SpanStart;
}
else
{
// There may be no declaring syntax reference, for example delegate Invoke methods.
// The user may need to fully-qualify type names, including the type(s) defined in
// this document.
positionForTypeBinding = 0;
}
var parameterConfiguration = ParameterConfiguration.Create(
GetParameters(symbol).Select(p => new ExistingParameter(p)).ToImmutableArray<Parameter>(),
symbol.IsExtensionMethod(), selectedIndex);
return new ChangeSignatureAnalysisSucceededContext(
declarationDocument, positionForTypeBinding, symbol, parameterConfiguration);
}
internal async Task<ChangeSignatureResult> ChangeSignatureWithContextAsync(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
return context switch
{
ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext => await GetChangeSignatureResultAsync(changeSignatureAnalyzedSucceedContext, options, cancellationToken).ConfigureAwait(false),
CannotChangeSignatureAnalyzedContext cannotChangeSignatureAnalyzedContext => new ChangeSignatureResult(succeeded: false, changeSignatureFailureKind: cannotChangeSignatureAnalyzedContext.CannotChangeSignatureReason),
_ => throw ExceptionUtilities.Unreachable,
};
async Task<ChangeSignatureResult> GetChangeSignatureResultAsync(ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken)
{
if (options == null)
{
return new ChangeSignatureResult(succeeded: false);
}
var (updatedSolution, confirmationMessage) = await CreateUpdatedSolutionAsync(context, options, cancellationToken).ConfigureAwait(false);
return new ChangeSignatureResult(updatedSolution != null, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges, confirmationMessage: confirmationMessage);
}
}
/// <returns>Returns <c>null</c> if the operation is cancelled.</returns>
internal static ChangeSignatureOptionsResult? GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context)
{
if (context is not ChangeSignatureAnalysisSucceededContext succeededContext)
{
return null;
}
var changeSignatureOptionsService = succeededContext.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>();
return changeSignatureOptionsService.GetChangeSignatureOptions(
succeededContext.Document, succeededContext.PositionForTypeBinding, succeededContext.Symbol, succeededContext.ParameterConfiguration);
}
private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
var streamingProgress = new StreamingProgressCollector();
var engine = new FindReferencesSearchEngine(
solution,
documents: null,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
streamingProgress,
FindReferencesSearchOptions.Default);
await engine.FindReferencesAsync(symbol, cancellationToken).ConfigureAwait(false);
return streamingProgress.GetReferencedSymbols();
}
}
#nullable enable
private async Task<(Solution updatedSolution, string? confirmationMessage)> CreateUpdatedSolutionAsync(
ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
var telemetryTimer = Stopwatch.StartNew();
var currentSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
string? confirmationMessage = null;
var symbols = await FindChangeSignatureReferencesAsync(
declaredSymbol, context.Solution, cancellationToken).ConfigureAwait(false);
var declaredSymbolParametersCount = GetParameters(declaredSymbol).Length;
var telemetryNumberOfDeclarationsToUpdate = 0;
var telemetryNumberOfReferencesToUpdate = 0;
foreach (var symbol in symbols)
{
var methodSymbol = symbol.Definition as IMethodSymbol;
if (methodSymbol != null &&
(methodSymbol.MethodKind == MethodKind.PropertyGet || methodSymbol.MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters is IEventSymbol eventSymbol)
{
if (eventSymbol.Type is INamedTypeSymbol type && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (methodSymbol != null)
{
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
// We update delegates which may have different signature.
// It seems it is enough for now to compare delegates by parameter count only.
if (methodSymbol.Parameters.Length != declaredSymbolParametersCount)
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
if (!TryGetNodeWithEditableSignatureOrAttributes(def, currentSolution, out var nodeToUpdate, out var documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
telemetryNumberOfDeclarationsToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue;
continue;
}
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, currentSolution, out var nodeToUpdate2, out var documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
telemetryNumberOfReferencesToUpdate++;
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = currentSolution.GetRequiredDocument(docId);
var updater = doc.Project.LanguageServices.GetRequiredService<AbstractChangeSignatureService>();
var root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignatureAsync(
doc,
definitionToUse[originalNode],
potentiallyUpdatedNode,
originalNode,
UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(definitionToUse[originalNode], options.UpdatedSignature),
cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.Format(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: await doc.GetOptionsAsync(cancellationToken).ConfigureAwait(false),
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
var updatedDoc = currentSolution.GetRequiredDocument(docId).WithSyntaxRoot(updatedRoots[docId]);
var docWithImports = await ImportAdder.AddImportsFromSymbolAnnotationAsync(updatedDoc, cancellationToken: cancellationToken).ConfigureAwait(false);
var reducedDoc = await Simplifier.ReduceAsync(docWithImports, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
var formattedDoc = await Formatter.FormatAsync(reducedDoc, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);
currentSolution = currentSolution.WithDocumentSyntaxRoot(docId, (await formattedDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false))!);
}
telemetryTimer.Stop();
ChangeSignatureLogger.LogCommitInformation(telemetryNumberOfDeclarationsToUpdate, telemetryNumberOfReferencesToUpdate, (int)telemetryTimer.ElapsedMilliseconds);
return (currentSolution, confirmationMessage);
}
#nullable disable
private static void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private static bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
var node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.GetLanguageService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected ImmutableArray<IUnifiedArgumentSyntax> PermuteArguments(
ISymbol declarationSymbol,
ImmutableArray<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = GetParameters(declarationSymbol);
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Length).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (var i = 0; i < declarationParametersToPermute.Length; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex ?? -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = ArrayBuilder<IUnifiedArgumentSyntax>.GetInstance();
var expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
var seenNamedArgument = false;
// Holds the params array argument so it can be
// added at the end.
IUnifiedArgumentSyntax paramsArrayArgument = null;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if (!param.IsParams)
{
// If seen a named argument before, add names for subsequent ones.
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
}
else
{
paramsArrayArgument = argument;
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the params argument with the first value:
if (paramsArrayArgument != null)
{
var param = argumentToParameterMap[paramsArrayArgument];
if (seenNamedArgument && !paramsArrayArgument.IsNamed)
{
newArguments.Add(paramsArrayArgument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(paramsArrayArgument);
}
}
// 6. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
var removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (var i = declarationParametersToPermute.Length; i < arguments.Length; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Length)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments.ToImmutableAndFree();
}
/// <summary>
/// Sometimes signature changes can cascade from a declaration with m parameters to one with n > m parameters, such as
/// delegate Invoke methods (m) and delegate BeginInvoke methods (n = m + 2). This method adds on those extra parameters
/// to the base <see cref="SignatureChange"/>.
/// </summary>
private SignatureChange UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
var realParameters = GetParameters(declarationSymbol);
if (realParameters.Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Length)
{
var originalConfigurationParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var updatedConfigurationParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var bonusParameters = realParameters.Skip(originalConfigurationParameters.Length);
var originalConfigurationParametersWithExtraParameters = originalConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
var updatedConfigurationParametersWithExtraParameters = updatedConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p)));
updatedSignature = new SignatureChange(
ParameterConfiguration.Create(originalConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0),
ParameterConfiguration.Create(updatedConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0));
}
return updatedSignature;
}
private static ImmutableArray<IParameterSymbol> GetParametersToPermute(
ImmutableArray<IUnifiedArgumentSyntax> arguments,
ImmutableArray<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
var position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = ArrayBuilder<IParameterSymbol>.GetInstance();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Length)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute.ToImmutableAndFree();
}
/// <summary>
/// Given the cursor position, find which parameter is selected.
/// Returns 0 as the default value. Note that the ChangeSignature dialog adjusts the selection for
/// the `this` parameter in extension methods (the selected index won't remain 0).
/// </summary>
protected static int GetParameterIndex<TNode>(SeparatedSyntaxList<TNode> parameters, int position)
where TNode : SyntaxNode
{
if (parameters.Count == 0)
{
return 0;
}
if (position < parameters.Span.Start)
{
return 0;
}
if (position > parameters.Span.End)
{
return 0;
}
for (var i = 0; i < parameters.Count - 1; i++)
{
// `$$,` points to the argument before the separator
// but `,$$` points to the argument following the separator
if (position <= parameters.GetSeparator(i).Span.Start)
{
return i;
}
}
return parameters.Count - 1;
}
protected (ImmutableArray<T> parameters, ImmutableArray<SyntaxToken> separators) UpdateDeclarationBase<T>(
SeparatedSyntaxList<T> list,
SignatureChange updatedSignature,
Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode
{
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var numAddedParameters = 0;
// Iterate through the list of new parameters and combine any
// preexisting parameters with added parameters to construct
// the full updated list.
var newParameters = ImmutableArray.CreateBuilder<T>();
for (var index = 0; index < reorderedParameters.Length; index++)
{
var newParam = reorderedParameters[index];
if (newParam is ExistingParameter existingParameter)
{
var pos = originalParameters.IndexOf(p => p is ExistingParameter ep && ep.Symbol.Equals(existingParameter.Symbol));
var param = list[pos];
if (index < list.Count)
{
param = TransferLeadingWhitespaceTrivia(param, list[index]);
}
else
{
param = param.WithLeadingTrivia();
}
newParameters.Add(param);
}
else
{
// Added parameter
var newParameter = createNewParameterMethod((AddedParameter)newParam);
if (index < list.Count)
{
newParameter = TransferLeadingWhitespaceTrivia(newParameter, list[index]);
}
else
{
newParameter = newParameter.WithLeadingTrivia();
}
newParameters.Add(newParameter);
numAddedParameters++;
}
}
// (a,b,c)
// Adding X parameters, need to add X separators.
var numSeparatorsToSkip = originalParameters.Length - reorderedParameters.Length;
if (originalParameters.Length == 0)
{
// ()
// Adding X parameters, need to add X-1 separators.
numSeparatorsToSkip++;
}
return (newParameters.ToImmutable(), GetSeparators(list, numSeparatorsToSkip));
}
protected ImmutableArray<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip) where T : SyntaxNode
{
var separators = ImmutableArray.CreateBuilder<SyntaxToken>();
for (var i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++)
{
separators.Add(i < arguments.SeparatorCount
? arguments.GetSeparator(i)
: CommaTokenWithElasticSpace());
}
return separators.ToImmutable();
}
protected virtual async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync(
ISymbol declarationSymbol,
SeparatedSyntaxList<SyntaxNode> newArguments,
SignatureChange signaturePermutation,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
bool generateAttributeArguments,
Document document,
int position,
CancellationToken cancellationToken)
{
var fullList = ArrayBuilder<SyntaxNode>.GetInstance();
var separators = ArrayBuilder<SyntaxToken>.GetInstance();
var updatedParameters = signaturePermutation.UpdatedConfiguration.ToListOfParameters();
var indexInListOfPreexistingArguments = 0;
var seenNamedArguments = false;
var seenOmitted = false;
var paramsHandled = false;
for (var i = 0; i < updatedParameters.Length; i++)
{
// Skip this parameter in list of arguments for extension method calls but not for reduced ones.
if (updatedParameters[i] != signaturePermutation.UpdatedConfiguration.ThisParameter
|| !isReducedExtensionMethod)
{
var parameters = GetParameters(declarationSymbol);
if (updatedParameters[i] is AddedParameter addedParameter)
{
// Omitting an argument only works in some languages, depending on whether
// there is a params array. We sometimes need to reinterpret an requested
// omitted parameter as one with a TODO requested.
var forcedCallsiteErrorDueToParamsArray = addedParameter.CallSiteKind == CallSiteKind.Omitted &&
parameters.LastOrDefault()?.IsParams == true &&
!SupportsOptionalAndParamsArrayParametersSimultaneously();
var isCallsiteActuallyOmitted = addedParameter.CallSiteKind == CallSiteKind.Omitted && !forcedCallsiteErrorDueToParamsArray;
var isCallsiteActuallyTODO = addedParameter.CallSiteKind == CallSiteKind.Todo || forcedCallsiteErrorDueToParamsArray;
if (isCallsiteActuallyOmitted)
{
seenOmitted = true;
seenNamedArguments = true;
continue;
}
var expression = await GenerateInferredCallsiteExpressionAsync(
document,
position,
addedParameter,
cancellationToken).ConfigureAwait(false);
if (expression == null)
{
// If we tried to infer the expression but failed, use a TODO instead.
isCallsiteActuallyTODO |= addedParameter.CallSiteKind == CallSiteKind.Inferred;
expression = Generator.ParseExpression(isCallsiteActuallyTODO ? "TODO" : addedParameter.CallSiteValue);
}
// TODO: Need to be able to specify which kind of attribute argument it is to the SyntaxGenerator.
// https://github.com/dotnet/roslyn/issues/43354
var argument = generateAttributeArguments ?
Generator.AttributeArgument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
expression: expression) :
Generator.Argument(
name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null,
refKind: RefKind.None,
expression: expression);
fullList.Add(argument);
separators.Add(CommaTokenWithElasticSpace());
}
else
{
if (indexInListOfPreexistingArguments == parameters.Length - 1 &&
parameters[indexInListOfPreexistingArguments].IsParams)
{
// Handling params array
if (seenOmitted)
{
// Need to ensure the params array is an actual array, and that the argument is named.
if (isParamsArrayExpanded)
{
var newArgument = CreateExplicitParamsArrayFromIndividualArguments(newArguments, indexInListOfPreexistingArguments, parameters[indexInListOfPreexistingArguments]);
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
var newArgument = newArguments[indexInListOfPreexistingArguments];
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
fullList.Add(newArgument);
}
paramsHandled = true;
}
else
{
// Normal case. Handled later.
}
}
else if (indexInListOfPreexistingArguments < newArguments.Count)
{
if (SyntaxFacts.IsNamedArgument(newArguments[indexInListOfPreexistingArguments]))
{
seenNamedArguments = true;
}
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
var newArgument = newArguments[indexInListOfPreexistingArguments];
if (seenNamedArguments && !SyntaxFacts.IsNamedArgument(newArgument))
{
newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name);
}
fullList.Add(newArgument);
indexInListOfPreexistingArguments++;
}
}
}
}
if (!paramsHandled)
{
// Add the rest of existing parameters, e.g. from the params argument.
while (indexInListOfPreexistingArguments < newArguments.Count)
{
if (indexInListOfPreexistingArguments < newArguments.SeparatorCount)
{
separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments));
}
fullList.Add(newArguments[indexInListOfPreexistingArguments++]);
}
}
if (fullList.Count == separators.Count && separators.Count != 0)
{
separators.Remove(separators.Last());
}
return Generator.SeparatedList(fullList.ToImmutableAndFree(), separators.ToImmutableAndFree());
}
private async Task<SyntaxNode> GenerateInferredCallsiteExpressionAsync(
Document document,
int position,
AddedParameter addedParameter,
CancellationToken cancellationToken)
{
if (addedParameter.CallSiteKind != CallSiteKind.Inferred || !addedParameter.TypeBinds)
{
return null;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var recommendations = await Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, position, document.Project.Solution.Workspace, options: null, cancellationToken).ConfigureAwait(false);
var sourceSymbols = recommendations.Where(r => r.IsNonImplicitAndFromSource());
// For locals, prefer the one with the closest declaration. Because we used the Recommender,
// we do not have to worry about filtering out inaccessible locals.
// TODO: Support range variables here as well: https://github.com/dotnet/roslyn/issues/44689
var orderedLocalAndParameterSymbols = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Local) || s.IsKind(SymbolKind.Parameter))
.OrderByDescending(s => s.Locations.First().SourceSpan.Start);
// No particular ordering preference for properties/fields.
var orderedPropertiesAndFields = sourceSymbols
.Where(s => s.IsKind(SymbolKind.Property) || s.IsKind(SymbolKind.Field));
var fullyOrderedSymbols = orderedLocalAndParameterSymbols.Concat(orderedPropertiesAndFields);
foreach (var symbol in fullyOrderedSymbols)
{
var symbolType = symbol.GetSymbolType();
if (symbolType == null)
{
continue;
}
if (semanticModel.Compilation.ClassifyCommonConversion(symbolType, addedParameter.Type).IsImplicit)
{
return Generator.IdentifierName(symbol.Name);
}
}
return null;
}
protected ImmutableArray<SyntaxTrivia> GetPermutedDocCommentTrivia(Document document, SyntaxNode node, ImmutableArray<SyntaxNode> permutedParamNodes)
{
var updatedLeadingTrivia = ImmutableArray.CreateBuilder<SyntaxTrivia>();
var index = 0;
SyntaxTrivia lastWhiteSpaceTrivia = default;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
foreach (var trivia in node.GetLeadingTrivia())
{
if (!trivia.HasStructure)
{
if (syntaxFacts.IsWhitespaceTrivia(trivia))
{
lastWhiteSpaceTrivia = trivia;
}
updatedLeadingTrivia.Add(trivia);
continue;
}
var structuredTrivia = trivia.GetStructure();
if (!syntaxFacts.IsDocumentationComment(structuredTrivia))
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var updatedNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
var structuredContent = syntaxFacts.GetContentFromDocumentationCommentTriviaSyntax(trivia);
for (var i = 0; i < structuredContent.Count; i++)
{
var content = structuredContent[i];
if (!syntaxFacts.IsParameterNameXmlElementSyntax(content))
{
updatedNodeList.Add(content);
continue;
}
// Found a param tag, so insert the next one from the reordered list
if (index < permutedParamNodes.Length)
{
updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia()));
index++;
}
else
{
// Inspecting a param element that we are deleting but not replacing.
}
}
var newDocComments = Generator.DocumentationCommentTriviaWithUpdatedContent(trivia, updatedNodeList.ToImmutableAndFree());
newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia());
var newTrivia = Generator.Trivia(newDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
var extraNodeList = ArrayBuilder<SyntaxNode>.GetInstance();
while (index < permutedParamNodes.Length)
{
extraNodeList.Add(permutedParamNodes[index]);
index++;
}
if (extraNodeList.Any())
{
var extraDocComments = Generator.DocumentationCommentTrivia(
extraNodeList,
node.GetTrailingTrivia(),
lastWhiteSpaceTrivia,
document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language));
var newTrivia = Generator.Trivia(extraDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
extraNodeList.Free();
return updatedLeadingTrivia.ToImmutable();
}
protected static bool IsParamsArrayExpandedHelper(ISymbol symbol, int argumentCount, bool lastArgumentIsNamed, SemanticModel semanticModel, SyntaxNode lastArgumentExpression, CancellationToken cancellationToken)
{
if (symbol is IMethodSymbol methodSymbol && methodSymbol.Parameters.LastOrDefault()?.IsParams == true)
{
if (argumentCount > methodSymbol.Parameters.Length)
{
return true;
}
if (argumentCount == methodSymbol.Parameters.Length)
{
if (lastArgumentIsNamed)
{
// If the last argument is named, then it cannot be part of an expanded params array.
return false;
}
else
{
var fromType = semanticModel.GetTypeInfo(lastArgumentExpression, cancellationToken);
var toType = methodSymbol.Parameters.Last().Type;
return !semanticModel.Compilation.HasImplicitConversion(fromType.Type, toType);
}
}
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/Core/Portable/Collections/OrderedSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Collections
{
internal sealed class OrderedSet<T> : IEnumerable<T>, IReadOnlySet<T>, IReadOnlyList<T>, IOrderedReadOnlySet<T>
{
private readonly HashSet<T> _set;
private readonly ArrayBuilder<T> _list;
public OrderedSet()
{
_set = new HashSet<T>();
_list = new ArrayBuilder<T>();
}
public OrderedSet(IEnumerable<T> items)
: this()
{
AddRange(items);
}
public void AddRange(IEnumerable<T> items)
{
foreach (var item in items)
{
Add(item);
}
}
public bool Add(T item)
{
if (_set.Add(item))
{
_list.Add(item);
return true;
}
return false;
}
public int Count
{
get
{
return _list.Count;
}
}
public T this[int index]
{
get
{
return _list[index];
}
}
public bool Contains(T item)
{
return _set.Contains(item);
}
public ArrayBuilder<T>.Enumerator GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return ((IEnumerable<T>)_list).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_list).GetEnumerator();
}
public void Clear()
{
_set.Clear();
_list.Clear();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Collections
{
internal sealed class OrderedSet<T> : IEnumerable<T>, IReadOnlySet<T>, IReadOnlyList<T>, IOrderedReadOnlySet<T>
{
private readonly HashSet<T> _set;
private readonly ArrayBuilder<T> _list;
public OrderedSet()
{
_set = new HashSet<T>();
_list = new ArrayBuilder<T>();
}
public OrderedSet(IEnumerable<T> items)
: this()
{
AddRange(items);
}
public void AddRange(IEnumerable<T> items)
{
foreach (var item in items)
{
Add(item);
}
}
public bool Add(T item)
{
if (_set.Add(item))
{
_list.Add(item);
return true;
}
return false;
}
public int Count
{
get
{
return _list.Count;
}
}
public T this[int index]
{
get
{
return _list[index];
}
}
public bool Contains(T item)
{
return _set.Contains(item);
}
public ArrayBuilder<T>.Enumerator GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return ((IEnumerable<T>)_list).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_list).GetEnumerator();
}
public void Clear()
{
_set.Clear();
_list.Clear();
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptLanguageDebugInfoService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Debugging;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[Shared]
[ExportLanguageService(typeof(ILanguageDebugInfoService), InternalLanguageNames.TypeScript)]
internal sealed class VSTypeScriptLanguageDebugInfoService : ILanguageDebugInfoService
{
private readonly IVSTypeScriptLanguageDebugInfoServiceImplementation _implementation;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VSTypeScriptLanguageDebugInfoService(IVSTypeScriptLanguageDebugInfoServiceImplementation implementation)
=> _implementation = implementation;
public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken)
=> (await _implementation.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject;
public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken)
=> (await _implementation.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Debugging;
using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[Shared]
[ExportLanguageService(typeof(ILanguageDebugInfoService), InternalLanguageNames.TypeScript)]
internal sealed class VSTypeScriptLanguageDebugInfoService : ILanguageDebugInfoService
{
private readonly IVSTypeScriptLanguageDebugInfoServiceImplementation _implementation;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VSTypeScriptLanguageDebugInfoService(IVSTypeScriptLanguageDebugInfoServiceImplementation implementation)
=> _implementation = implementation;
public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken)
=> (await _implementation.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject;
public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken)
=> (await _implementation.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject;
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/CSharp/Portable/FlowAnalysis/DefinitelyAssignedWalker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#if DEBUG
// See comment in DefiniteAssignment.
#define REFERENCE_STATE
#endif
using System;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A region analysis walker that computes the set of variables that are definitely assigned
/// when a region is entered or exited.
/// </summary>
internal sealed class DefinitelyAssignedWalker : AbstractRegionDataFlowPass
{
private readonly HashSet<Symbol> _definitelyAssignedOnEntry = new HashSet<Symbol>();
private readonly HashSet<Symbol> _definitelyAssignedOnExit = new HashSet<Symbol>();
private DefinitelyAssignedWalker(
CSharpCompilation compilation,
Symbol member,
BoundNode node,
BoundNode firstInRegion,
BoundNode lastInRegion)
: base(compilation, member, node, firstInRegion, lastInRegion)
{
}
internal static (HashSet<Symbol> entry, HashSet<Symbol> exit) Analyze(
CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
{
var walker = new DefinitelyAssignedWalker(compilation, member, node, firstInRegion, lastInRegion);
try
{
bool badRegion = false;
walker.Analyze(ref badRegion, diagnostics: null);
return badRegion
? (new HashSet<Symbol>(), new HashSet<Symbol>())
: (walker._definitelyAssignedOnEntry, walker._definitelyAssignedOnExit);
}
finally
{
walker.Free();
}
}
protected override void EnterRegion()
{
ProcessRegion(_definitelyAssignedOnEntry);
base.EnterRegion();
}
protected override void LeaveRegion()
{
ProcessRegion(_definitelyAssignedOnExit);
base.LeaveRegion();
}
private void ProcessRegion(HashSet<Symbol> definitelyAssigned)
{
// this can happen multiple times as flow analysis is multi-pass. Always
// take the latest data and use that to determine our result.
definitelyAssigned.Clear();
if (this.IsConditionalState)
{
// We're in a state where there are different flow paths (i.e. when-true and when-false).
// In that case, a variable is only definitely assigned if it's definitely assigned through
// both paths.
this.ProcessState(definitelyAssigned, this.StateWhenTrue, this.StateWhenFalse);
}
else
{
this.ProcessState(definitelyAssigned, this.State, state2opt: null);
}
}
#if REFERENCE_STATE
private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState state2opt)
#else
private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState? state2opt)
#endif
{
foreach (var slot in state1.Assigned.TrueBits())
{
if (slot < variableBySlot.Count &&
state2opt?.IsAssigned(slot) != false &&
variableBySlot[slot].Symbol is { } symbol &&
symbol.Kind != SymbolKind.Field)
{
definitelyAssigned.Add(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
#if DEBUG
// See comment in DefiniteAssignment.
#define REFERENCE_STATE
#endif
using System;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A region analysis walker that computes the set of variables that are definitely assigned
/// when a region is entered or exited.
/// </summary>
internal sealed class DefinitelyAssignedWalker : AbstractRegionDataFlowPass
{
private readonly HashSet<Symbol> _definitelyAssignedOnEntry = new HashSet<Symbol>();
private readonly HashSet<Symbol> _definitelyAssignedOnExit = new HashSet<Symbol>();
private DefinitelyAssignedWalker(
CSharpCompilation compilation,
Symbol member,
BoundNode node,
BoundNode firstInRegion,
BoundNode lastInRegion)
: base(compilation, member, node, firstInRegion, lastInRegion)
{
}
internal static (HashSet<Symbol> entry, HashSet<Symbol> exit) Analyze(
CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
{
var walker = new DefinitelyAssignedWalker(compilation, member, node, firstInRegion, lastInRegion);
try
{
bool badRegion = false;
walker.Analyze(ref badRegion, diagnostics: null);
return badRegion
? (new HashSet<Symbol>(), new HashSet<Symbol>())
: (walker._definitelyAssignedOnEntry, walker._definitelyAssignedOnExit);
}
finally
{
walker.Free();
}
}
protected override void EnterRegion()
{
ProcessRegion(_definitelyAssignedOnEntry);
base.EnterRegion();
}
protected override void LeaveRegion()
{
ProcessRegion(_definitelyAssignedOnExit);
base.LeaveRegion();
}
private void ProcessRegion(HashSet<Symbol> definitelyAssigned)
{
// this can happen multiple times as flow analysis is multi-pass. Always
// take the latest data and use that to determine our result.
definitelyAssigned.Clear();
if (this.IsConditionalState)
{
// We're in a state where there are different flow paths (i.e. when-true and when-false).
// In that case, a variable is only definitely assigned if it's definitely assigned through
// both paths.
this.ProcessState(definitelyAssigned, this.StateWhenTrue, this.StateWhenFalse);
}
else
{
this.ProcessState(definitelyAssigned, this.State, state2opt: null);
}
}
#if REFERENCE_STATE
private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState state2opt)
#else
private void ProcessState(HashSet<Symbol> definitelyAssigned, LocalState state1, LocalState? state2opt)
#endif
{
foreach (var slot in state1.Assigned.TrueBits())
{
if (slot < variableBySlot.Count &&
state2opt?.IsAssigned(slot) != false &&
variableBySlot[slot].Symbol is { } symbol &&
symbol.Kind != SymbolKind.Field)
{
definitelyAssigned.Add(symbol);
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/CoreTest/GeneratedCodeRecognitionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class GeneratedCodeRecognitionTests
{
[Fact]
public void TestFileNamesNotGenerated()
{
TestFileNames(false,
"",
"Test",
"Test.cs",
"Test.vb",
"AssemblyInfo.cs",
"AssemblyInfo.vb",
".NETFramework,Version=v4.5.AssemblyAttributes.cs",
".NETFramework,Version=v4.5.AssemblyAttributes.vb",
"Test.notgenerated.cs",
"Test.notgenerated.vb",
"Test.generated",
"Test.designer");
}
[Fact]
public void TestFileNamesGenerated()
{
TestFileNames(true,
"TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92",
"TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs",
"TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.vb",
"Test.designer.cs",
"Test.designer.vb",
"Test.Designer.cs",
"Test.Designer.vb",
"Test.generated.cs",
"Test.generated.vb",
"Test.g.cs",
"Test.g.vb",
"Test.g.i.cs",
"Test.g.i.vb");
}
private static void TestFileNames(bool assertGenerated, params string[] fileNames)
{
var project = CreateProject();
var projectWithUserConfiguredGeneratedCodeTrue = project.AddAnalyzerConfigDocument(".editorconfig",
SourceText.From(@"
[*.{cs,vb}]
generated_code = true
"), filePath: @"z:\.editorconfig").Project;
var projectWithUserConfiguredGeneratedCodeFalse = project.AddAnalyzerConfigDocument(".editorconfig",
SourceText.From(@"
[*.{cs,vb}]
generated_code = false
"), filePath: @"z:\.editorconfig").Project;
foreach (var fileName in fileNames)
{
TestCore(fileName, project, assertGenerated);
// Verify user configuration always overrides generated code heuristic.
if (fileName.EndsWith(".cs") || fileName.EndsWith(".vb"))
{
TestCore(fileName, projectWithUserConfiguredGeneratedCodeTrue, assertGenerated: true);
TestCore(fileName, projectWithUserConfiguredGeneratedCodeFalse, assertGenerated: false);
}
}
static void TestCore(string fileName, Project project, bool assertGenerated)
{
var document = project.AddDocument(fileName, "", filePath: $"z:\\{fileName}");
if (assertGenerated)
{
Assert.True(document.IsGeneratedCode(CancellationToken.None), string.Format("Expected file '{0}' to be interpreted as generated code", fileName));
}
else
{
Assert.False(document.IsGeneratedCode(CancellationToken.None), string.Format("Did not expect file '{0}' to be interpreted as generated code", fileName));
}
}
}
private static Project CreateProject()
{
var projectName = "TestProject";
var projectId = ProjectId.CreateNewId(projectName);
return new AdhocWorkspace().CurrentSolution
.AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
.GetProject(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.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
[UseExportProvider]
public class GeneratedCodeRecognitionTests
{
[Fact]
public void TestFileNamesNotGenerated()
{
TestFileNames(false,
"",
"Test",
"Test.cs",
"Test.vb",
"AssemblyInfo.cs",
"AssemblyInfo.vb",
".NETFramework,Version=v4.5.AssemblyAttributes.cs",
".NETFramework,Version=v4.5.AssemblyAttributes.vb",
"Test.notgenerated.cs",
"Test.notgenerated.vb",
"Test.generated",
"Test.designer");
}
[Fact]
public void TestFileNamesGenerated()
{
TestFileNames(true,
"TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92",
"TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs",
"TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.vb",
"Test.designer.cs",
"Test.designer.vb",
"Test.Designer.cs",
"Test.Designer.vb",
"Test.generated.cs",
"Test.generated.vb",
"Test.g.cs",
"Test.g.vb",
"Test.g.i.cs",
"Test.g.i.vb");
}
private static void TestFileNames(bool assertGenerated, params string[] fileNames)
{
var project = CreateProject();
var projectWithUserConfiguredGeneratedCodeTrue = project.AddAnalyzerConfigDocument(".editorconfig",
SourceText.From(@"
[*.{cs,vb}]
generated_code = true
"), filePath: @"z:\.editorconfig").Project;
var projectWithUserConfiguredGeneratedCodeFalse = project.AddAnalyzerConfigDocument(".editorconfig",
SourceText.From(@"
[*.{cs,vb}]
generated_code = false
"), filePath: @"z:\.editorconfig").Project;
foreach (var fileName in fileNames)
{
TestCore(fileName, project, assertGenerated);
// Verify user configuration always overrides generated code heuristic.
if (fileName.EndsWith(".cs") || fileName.EndsWith(".vb"))
{
TestCore(fileName, projectWithUserConfiguredGeneratedCodeTrue, assertGenerated: true);
TestCore(fileName, projectWithUserConfiguredGeneratedCodeFalse, assertGenerated: false);
}
}
static void TestCore(string fileName, Project project, bool assertGenerated)
{
var document = project.AddDocument(fileName, "", filePath: $"z:\\{fileName}");
if (assertGenerated)
{
Assert.True(document.IsGeneratedCode(CancellationToken.None), string.Format("Expected file '{0}' to be interpreted as generated code", fileName));
}
else
{
Assert.False(document.IsGeneratedCode(CancellationToken.None), string.Format("Did not expect file '{0}' to be interpreted as generated code", fileName));
}
}
}
private static Project CreateProject()
{
var projectName = "TestProject";
var projectId = ProjectId.CreateNewId(projectName);
return new AdhocWorkspace().CurrentSolution
.AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
.GetProject(projectId);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/OperatorKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class OperatorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public OperatorKeywordRecommender()
: base(SyntaxKind.OperatorKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// cases:
// public static implicit |
// public static explicit |
var token = context.TargetToken;
return
token.Kind() == SyntaxKind.ImplicitKeyword ||
token.Kind() == SyntaxKind.ExplicitKeyword;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class OperatorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public OperatorKeywordRecommender()
: base(SyntaxKind.OperatorKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// cases:
// public static implicit |
// public static explicit |
var token = context.TargetToken;
return
token.Kind() == SyntaxKind.ImplicitKeyword ||
token.Kind() == SyntaxKind.ExplicitKeyword;
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Analyzers/CSharp/Tests/UpdateLegacySuppressions/UpdateLegacySuppressionsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions.CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer,
Microsoft.CodeAnalysis.UpdateLegacySuppressions.UpdateLegacySuppressionsCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UpdateLegacySuppressions
{
[Trait(Traits.Feature, Traits.Features.CodeActionsUpdateLegacySuppressions)]
[WorkItem(44362, "https://github.com/dotnet/roslyn/issues/44362")]
public class UpdateLegacySuppressionsTests
{
[Theory, CombinatorialData]
public void TestStandardProperty(AnalyzerProperty property)
=> VerifyCS.VerifyStandardProperty(property);
// Namespace
[InlineData("namespace", "N", "~N:N")]
// Type
[InlineData("type", "N.C+D", "~T:N.C.D")]
// Field
[InlineData("member", "N.C.#F", "~F:N.C.F")]
// Property
[InlineData("member", "N.C.#P", "~P:N.C.P")]
// Method
[InlineData("member", "N.C.#M", "~M:N.C.M")]
// Generic method with parameters
[InlineData("member", "N.C.#M2(!!0)", "~M:N.C.M2``1(``0)~System.Int32")]
// Event
[InlineData("member", "e:N.C.#E", "~E:N.C.E")]
[Theory]
public async Task LegacySuppressions(string scope, string target, string fixedTarget)
{
var input = $@"
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = {{|#0:""{target}""|}})]
namespace N
{{
class C
{{
private int F;
public int P {{ get; set; }}
public void M() {{ }}
public int M2<T>(T t) => 0;
public event System.EventHandler<int> E;
class D
{{
}}
}}
}}";
var expectedDiagnostic = VerifyCS.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor)
.WithLocation(0)
.WithArguments(target);
var fixedCode = $@"
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = ""{fixedTarget}"")]
namespace N
{{
class C
{{
private int F;
public int P {{ get; set; }}
public void M() {{ }}
public int M2<T>(T t) => 0;
public event System.EventHandler<int> E;
class D
{{
}}
}}
}}";
await VerifyCS.VerifyCodeFixAsync(input, expectedDiagnostic, fixedCode);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions.CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer,
Microsoft.CodeAnalysis.UpdateLegacySuppressions.UpdateLegacySuppressionsCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UpdateLegacySuppressions
{
[Trait(Traits.Feature, Traits.Features.CodeActionsUpdateLegacySuppressions)]
[WorkItem(44362, "https://github.com/dotnet/roslyn/issues/44362")]
public class UpdateLegacySuppressionsTests
{
[Theory, CombinatorialData]
public void TestStandardProperty(AnalyzerProperty property)
=> VerifyCS.VerifyStandardProperty(property);
// Namespace
[InlineData("namespace", "N", "~N:N")]
// Type
[InlineData("type", "N.C+D", "~T:N.C.D")]
// Field
[InlineData("member", "N.C.#F", "~F:N.C.F")]
// Property
[InlineData("member", "N.C.#P", "~P:N.C.P")]
// Method
[InlineData("member", "N.C.#M", "~M:N.C.M")]
// Generic method with parameters
[InlineData("member", "N.C.#M2(!!0)", "~M:N.C.M2``1(``0)~System.Int32")]
// Event
[InlineData("member", "e:N.C.#E", "~E:N.C.E")]
[Theory]
public async Task LegacySuppressions(string scope, string target, string fixedTarget)
{
var input = $@"
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = {{|#0:""{target}""|}})]
namespace N
{{
class C
{{
private int F;
public int P {{ get; set; }}
public void M() {{ }}
public int M2<T>(T t) => 0;
public event System.EventHandler<int> E;
class D
{{
}}
}}
}}";
var expectedDiagnostic = VerifyCS.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor)
.WithLocation(0)
.WithArguments(target);
var fixedCode = $@"
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = ""{fixedTarget}"")]
namespace N
{{
class C
{{
private int F;
public int P {{ get; set; }}
public void M() {{ }}
public int M2<T>(T t) => 0;
public event System.EventHandler<int> E;
class D
{{
}}
}}
}}";
await VerifyCS.VerifyCodeFixAsync(input, expectedDiagnostic, fixedCode);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/View/CodeStyleSeverityControl.xaml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Windows.Automation;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleSeverityControl.xaml
/// </summary>
internal partial class CodeStyleSeverityControl : UserControl
{
private readonly ComboBox _comboBox;
private readonly CodeStyleSetting _setting;
public CodeStyleSeverityControl(CodeStyleSetting setting)
{
InitializeComponent();
_setting = setting;
_comboBox = new ComboBox()
{
ItemsSource = new[]
{
ServicesVSResources.Refactoring_Only,
ServicesVSResources.Suggestion,
ServicesVSResources.Warning,
ServicesVSResources.Error
}
};
_comboBox.SelectedIndex = setting.Severity switch
{
DiagnosticSeverity.Hidden => 0,
DiagnosticSeverity.Info => 1,
DiagnosticSeverity.Warning => 2,
DiagnosticSeverity.Error => 3,
_ => throw new InvalidOperationException(),
};
_comboBox.SelectionChanged += ComboBox_SelectionChanged;
_comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity);
_ = RootGrid.Children.Add(_comboBox);
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var severity = _comboBox.SelectedIndex switch
{
0 => DiagnosticSeverity.Hidden,
1 => DiagnosticSeverity.Info,
2 => DiagnosticSeverity.Warning,
3 => DiagnosticSeverity.Error,
_ => throw new InvalidOperationException(),
};
if (_setting.Severity != severity)
{
_setting.ChangeSeverity(severity);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Windows.Automation;
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleSeverityControl.xaml
/// </summary>
internal partial class CodeStyleSeverityControl : UserControl
{
private readonly ComboBox _comboBox;
private readonly CodeStyleSetting _setting;
public CodeStyleSeverityControl(CodeStyleSetting setting)
{
InitializeComponent();
_setting = setting;
_comboBox = new ComboBox()
{
ItemsSource = new[]
{
ServicesVSResources.Refactoring_Only,
ServicesVSResources.Suggestion,
ServicesVSResources.Warning,
ServicesVSResources.Error
}
};
_comboBox.SelectedIndex = setting.Severity switch
{
DiagnosticSeverity.Hidden => 0,
DiagnosticSeverity.Info => 1,
DiagnosticSeverity.Warning => 2,
DiagnosticSeverity.Error => 3,
_ => throw new InvalidOperationException(),
};
_comboBox.SelectionChanged += ComboBox_SelectionChanged;
_comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity);
_ = RootGrid.Children.Add(_comboBox);
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var severity = _comboBox.SelectedIndex switch
{
0 => DiagnosticSeverity.Hidden,
1 => DiagnosticSeverity.Info,
2 => DiagnosticSeverity.Warning,
3 => DiagnosticSeverity.Error,
_ => throw new InvalidOperationException(),
};
if (_setting.Severity != severity)
{
_setting.ChangeSeverity(severity);
}
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Analyzers/Core/CodeFixes/xlf/CodeFixesResources.ko.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="ko" original="../CodeFixesResources.resx">
<body>
<trans-unit id="Add_blank_line_after_block">
<source>Add blank line after block</source>
<target state="translated">블록 뒤에 빈 줄 추가</target>
<note />
</trans-unit>
<trans-unit id="Add_both">
<source>Add both</source>
<target state="translated">둘 다 추가</target>
<note />
</trans-unit>
<trans-unit id="Add_default_case">
<source>Add default case</source>
<target state="translated">Default Case 추가</target>
<note />
</trans-unit>
<trans-unit id="Add_file_header">
<source>Add file header</source>
<target state="translated">파일 헤더 추가</target>
<note />
</trans-unit>
<trans-unit id="Fix_Name_Violation_colon_0">
<source>Fix Name Violation: {0}</source>
<target state="translated">이름 위반 수정: {0}</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_occurrences_in">
<source>Fix all occurrences in</source>
<target state="translated">다음 위치에서 모든 발생 수정</target>
<note />
</trans-unit>
<trans-unit id="Remove_extra_blank_lines">
<source>Remove extra blank lines</source>
<target state="translated">여분의 빈 줄 제거</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_assignment">
<source>Remove redundant assignment</source>
<target state="translated">중복 할당 제거</target>
<note />
</trans-unit>
<trans-unit id="Suppress_or_Configure_issues">
<source>Suppress or Configure issues</source>
<target state="translated">문제 표시 안 함 또는 구성</target>
<note />
</trans-unit>
<trans-unit id="Update_suppression_format">
<source>Update suppression format</source>
<target state="translated">제거 형식 업데이트</target>
<note />
</trans-unit>
<trans-unit id="Use_discard_underscore">
<source>Use discard '_'</source>
<target state="translated">무시 항목 '_' 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_discarded_local">
<source>Use discarded local</source>
<target state="translated">무시된 로컬 사용</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="ko" original="../CodeFixesResources.resx">
<body>
<trans-unit id="Add_blank_line_after_block">
<source>Add blank line after block</source>
<target state="translated">블록 뒤에 빈 줄 추가</target>
<note />
</trans-unit>
<trans-unit id="Add_both">
<source>Add both</source>
<target state="translated">둘 다 추가</target>
<note />
</trans-unit>
<trans-unit id="Add_default_case">
<source>Add default case</source>
<target state="translated">Default Case 추가</target>
<note />
</trans-unit>
<trans-unit id="Add_file_header">
<source>Add file header</source>
<target state="translated">파일 헤더 추가</target>
<note />
</trans-unit>
<trans-unit id="Fix_Name_Violation_colon_0">
<source>Fix Name Violation: {0}</source>
<target state="translated">이름 위반 수정: {0}</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_occurrences_in">
<source>Fix all occurrences in</source>
<target state="translated">다음 위치에서 모든 발생 수정</target>
<note />
</trans-unit>
<trans-unit id="Remove_extra_blank_lines">
<source>Remove extra blank lines</source>
<target state="translated">여분의 빈 줄 제거</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_assignment">
<source>Remove redundant assignment</source>
<target state="translated">중복 할당 제거</target>
<note />
</trans-unit>
<trans-unit id="Suppress_or_Configure_issues">
<source>Suppress or Configure issues</source>
<target state="translated">문제 표시 안 함 또는 구성</target>
<note />
</trans-unit>
<trans-unit id="Update_suppression_format">
<source>Update suppression format</source>
<target state="translated">제거 형식 업데이트</target>
<note />
</trans-unit>
<trans-unit id="Use_discard_underscore">
<source>Use discard '_'</source>
<target state="translated">무시 항목 '_' 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_discarded_local">
<source>Use discarded local</source>
<target state="translated">무시된 로컬 사용</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Semantics/TypeInference/TypeArgumentInference.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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The only public entry point is the Infer method.
''' </summary>
Friend MustInherit Class TypeArgumentInference
Public Shared Function Infer(
candidate As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
parameterToArgumentMap As ArrayBuilder(Of Integer),
paramArrayItems As ArrayBuilder(Of Integer),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
ByRef typeArguments As ImmutableArray(Of TypeSymbol),
ByRef inferenceLevel As InferenceLevel,
ByRef allFailedInferenceIsDueToObject As Boolean,
ByRef someInferenceFailed As Boolean,
ByRef inferenceErrorReasons As InferenceErrorReasons,
<Out> ByRef inferredTypeByAssumption As BitVector,
<Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
ByRef diagnostic As BindingDiagnosticBag,
Optional inferTheseTypeParameters As BitVector = Nothing
) As Boolean
Debug.Assert(candidate Is candidate.ConstructedFrom)
Return InferenceGraph.Infer(candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode,
typeArguments, inferenceLevel, allFailedInferenceIsDueToObject, someInferenceFailed, inferenceErrorReasons,
inferredTypeByAssumption, typeArgumentsLocation, asyncLambdaSubToFunctionMismatch,
useSiteInfo, diagnostic, inferTheseTypeParameters)
End Function
' No-one should create instances of this class.
Private Sub New()
End Sub
Public Enum InferenceLevel As Byte
None = 0
' None is used to indicate uninitialized but semantically it should not matter if there is a whidbey delegate
' or no delegate in the overload resolution hence both have value 0 such that overload resolution
' will not prefer a non inferred method over an inferred one.
Whidbey = 0
Orcas = 1
' Keep invalid the biggest number
Invalid = 2
End Enum
' MatchGenericArgumentParameter:
' This is used in type inference, when matching an argument e.g. Arg(Of String) against a parameter Parm(Of T).
' In covariant contexts e.g. Action(Of _), the two match if Arg <= Parm (i.e. Arg inherits/implements Parm).
' In contravariant contexts e.g. IEnumerable(Of _), the two match if Parm <= Arg (i.e. Parm inherits/implements Arg).
' In invariant contexts e.g. List(Of _), the two match only if Arg and Parm are identical.
' Note: remember that rank-1 arrays T() implement IEnumerable(Of T), IList(Of T) and ICollection(Of T).
Public Enum MatchGenericArgumentToParameter
MatchBaseOfGenericArgumentToParameter
MatchArgumentToBaseOfGenericParameter
MatchGenericArgumentToParameterExactly
End Enum
Private Enum InferenceNodeType As Byte
ArgumentNode
TypeParameterNode
End Enum
Private MustInherit Class InferenceNode
Inherits GraphNode(Of InferenceNode)
Public ReadOnly NodeType As InferenceNodeType
Public InferenceComplete As Boolean
Protected Sub New(graph As InferenceGraph, nodeType As InferenceNodeType)
MyBase.New(graph)
Me.NodeType = nodeType
End Sub
Public Shadows ReadOnly Property Graph As InferenceGraph
Get
Return DirectCast(MyBase.Graph, InferenceGraph)
End Get
End Property
''' <summary>
''' Returns True if the inference algorithm should be restarted.
''' </summary>
Public MustOverride Function InferTypeAndPropagateHints() As Boolean
<Conditional("DEBUG")>
Public Sub VerifyIncomingInferenceComplete(
ByVal nodeType As InferenceNodeType
)
If Not Graph.SomeInferenceHasFailed() Then
For Each current As InferenceNode In IncomingEdges
Debug.Assert(current.NodeType = nodeType, "Should only have expected incoming edges.")
Debug.Assert(current.InferenceComplete, "Should have inferred type already")
Next
End If
End Sub
End Class
Private Class DominantTypeDataTypeInference
Inherits DominantTypeData
' Fields needed for error reporting
Public ByAssumption As Boolean ' was ResultType chosen by assumption or intention?
Public Parameter As ParameterSymbol
Public InferredFromObject As Boolean
Public TypeParameter As TypeParameterSymbol
Public ArgumentLocation As SyntaxNode
End Class
Private Class TypeParameterNode
Inherits InferenceNode
Public ReadOnly DeclaredTypeParam As TypeParameterSymbol
Public ReadOnly InferenceTypeCollection As TypeInferenceCollection(Of DominantTypeDataTypeInference)
Private _inferredType As TypeSymbol
Private _inferredFromLocation As SyntaxNodeOrToken
Private _inferredTypeByAssumption As Boolean
' TODO: Dev10 has two locations to track type inferred so far.
' One that can be changed with time and the other one that cannot be changed.
' This one, cannot be changed once set. We need to clean this up later.
Private _candidateInferredType As TypeSymbol
Private _parameter As ParameterSymbol
Public Sub New(graph As InferenceGraph, typeParameter As TypeParameterSymbol)
MyBase.New(graph, InferenceNodeType.TypeParameterNode)
DeclaredTypeParam = typeParameter
InferenceTypeCollection = New TypeInferenceCollection(Of DominantTypeDataTypeInference)()
End Sub
Public ReadOnly Property InferredType As TypeSymbol
Get
Return _inferredType
End Get
End Property
Public ReadOnly Property CandidateInferredType As TypeSymbol
Get
Return _candidateInferredType
End Get
End Property
Public ReadOnly Property InferredFromLocation As SyntaxNodeOrToken
Get
Return _inferredFromLocation
End Get
End Property
Public ReadOnly Property InferredTypeByAssumption As Boolean
Get
Return _inferredTypeByAssumption
End Get
End Property
Public Sub RegisterInferredType(inferredType As TypeSymbol, inferredFromLocation As SyntaxNodeOrToken, inferredTypeByAssumption As Boolean)
' Make sure ArrayLiteralTypeSymbol does not leak out
Dim arrayLiteralType = TryCast(inferredType, ArrayLiteralTypeSymbol)
If arrayLiteralType IsNot Nothing Then
Dim arrayLiteral = arrayLiteralType.ArrayLiteral
Dim arrayType = arrayLiteral.InferredType
If Not (arrayLiteral.HasDominantType AndAlso arrayLiteral.NumberOfCandidates = 1) AndAlso
arrayType.ElementType.SpecialType = SpecialType.System_Object Then
' ReportArrayLiteralInferredTypeDiagnostics in ReclassifyArrayLiteralExpression reports an error
' when option strict is on and the array type is object() and there wasn't a dominant type. However,
' Dev10 does not report this error when inferring a type parameter's type. Create a new object() type
' to suppress the error.
inferredType = ArrayTypeSymbol.CreateVBArray(arrayType.ElementType, Nothing, arrayType.Rank, arrayLiteral.Binder.Compilation.Assembly)
Else
inferredType = arrayLiteral.InferredType
End If
End If
Debug.Assert(Not (TypeOf inferredType Is ArrayLiteralTypeSymbol))
_inferredType = inferredType
_inferredFromLocation = inferredFromLocation
_inferredTypeByAssumption = inferredTypeByAssumption
' TODO: Dev10 has two locations to track type inferred so far.
' One that can be changed with time and the other one that cannot be changed.
' We need to clean this up.
If _candidateInferredType Is Nothing Then
_candidateInferredType = inferredType
End If
End Sub
Public ReadOnly Property Parameter As ParameterSymbol
Get
Return _parameter
End Get
End Property
Public Sub SetParameter(parameter As ParameterSymbol)
Debug.Assert(_parameter Is Nothing)
_parameter = parameter
End Sub
Public Overrides Function InferTypeAndPropagateHints() As Boolean
Dim numberOfIncomingEdges As Integer = IncomingEdges.Count
Dim restartAlgorithm As Boolean = False
Dim argumentLocation As SyntaxNode
Dim numberOfIncomingWithNothing As Integer = 0
If numberOfIncomingEdges > 0 Then
argumentLocation = DirectCast(IncomingEdges(0), ArgumentNode).Expression.Syntax
Else
argumentLocation = Nothing
End If
Dim numberOfAssertions As Integer = 0
Dim incomingFromObject As Boolean = False
Dim list As ArrayBuilder(Of InferenceNode) = IncomingEdges
For Each currentGraphNode As InferenceNode In IncomingEdges
Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.ArgumentNode, "Should only have named nodes as incoming edges.")
Dim currentNamedNode = DirectCast(currentGraphNode, ArgumentNode)
If currentNamedNode.Expression.Type IsNot Nothing AndAlso
currentNamedNode.Expression.Type.IsObjectType() Then
incomingFromObject = True
End If
If Not currentNamedNode.InferenceComplete Then
Graph.RemoveEdge(currentNamedNode, Me)
restartAlgorithm = True
numberOfAssertions += 1
Else
' We should not infer from a Nothing literal.
If currentNamedNode.Expression.IsStrictNothingLiteral() Then
numberOfIncomingWithNothing += 1
End If
End If
Next
If numberOfIncomingEdges > 0 AndAlso numberOfIncomingEdges = numberOfIncomingWithNothing Then
' !! Inference has failed: All incoming type hints, were based on 'Nothing'
Graph.MarkInferenceFailure()
Graph.ReportNotFailedInferenceDueToObject()
End If
Dim numberOfTypeHints As Integer = InferenceTypeCollection.GetTypeDataList().Count()
If numberOfTypeHints = 0 Then
If numberOfAssertions = numberOfIncomingEdges Then
Graph.MarkInferenceLevel(InferenceLevel.Orcas)
Else
' !! Inference has failed. No Type hints, and some, not all were assertions, otherwise we would have picked object for strict.
RegisterInferredType(Nothing, Nothing, False)
Graph.MarkInferenceFailure()
If Not incomingFromObject Then
Graph.ReportNotFailedInferenceDueToObject()
End If
End If
ElseIf numberOfTypeHints = 1 Then
Dim typeData As DominantTypeDataTypeInference = InferenceTypeCollection.GetTypeDataList()(0)
If argumentLocation Is Nothing AndAlso typeData.ArgumentLocation IsNot Nothing Then
argumentLocation = typeData.ArgumentLocation
End If
RegisterInferredType(typeData.ResultType, argumentLocation, typeData.ByAssumption)
Else
' Run the whidbey algorithm to see if we are smarter now.
Dim firstInferredType As TypeSymbol = Nothing
Dim allTypeData As ArrayBuilder(Of DominantTypeDataTypeInference) = InferenceTypeCollection.GetTypeDataList()
For Each currentTypeInfo As DominantTypeDataTypeInference In allTypeData
If firstInferredType Is Nothing Then
firstInferredType = currentTypeInfo.ResultType
ElseIf Not firstInferredType.IsSameTypeIgnoringAll(currentTypeInfo.ResultType) Then
' Whidbey failed hard here, in Orcas we added dominant type information.
Graph.MarkInferenceLevel(InferenceLevel.Orcas)
End If
Next
Dim dominantTypeDataList = ArrayBuilder(Of DominantTypeDataTypeInference).GetInstance()
Dim errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other
InferenceTypeCollection.FindDominantType(dominantTypeDataList, errorReasons, Graph.UseSiteInfo)
If dominantTypeDataList.Count = 1 Then
' //consider: scottwis
' // This seems dangerous to me, that we
' // remove error reasons here.
' // Instead of clearing these, what we should be doing is
' // asserting that they are not set.
' // If for some reason they get set, but
' // we enter this path, then we have a bug.
' // This code is just masking any such bugs.
errorReasons = errorReasons And (Not (InferenceErrorReasons.Ambiguous Or InferenceErrorReasons.NoBest))
Dim typeData As DominantTypeDataTypeInference = dominantTypeDataList(0)
RegisterInferredType(typeData.ResultType, typeData.ArgumentLocation, typeData.ByAssumption)
' // Also update the location of the argument for constraint error reporting later on.
Else
If (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then
' !! Inference has failed. Dominant type algorithm found ambiguous types.
Graph.ReportAmbiguousInferenceError(dominantTypeDataList)
Else
' //consider: scottwis
' // This code appears to be operating under the assumption that if the error reason is not due to an
' // ambiguity then it must be because there was no best match.
' // We should be asserting here to verify that assertion.
' !! Inference has failed. Dominant type algorithm could not find a dominant type.
Graph.ReportIncompatibleInferenceError(allTypeData)
End If
RegisterInferredType(allTypeData(0).ResultType, argumentLocation, False)
Graph.MarkInferenceFailure()
End If
Graph.RegisterErrorReasons(errorReasons)
dominantTypeDataList.Free()
End If
InferenceComplete = True
Return restartAlgorithm
End Function
Public Sub AddTypeHint(
type As TypeSymbol,
typeByAssumption As Boolean,
argumentLocation As SyntaxNode,
parameter As ParameterSymbol,
inferredFromObject As Boolean,
inferenceRestrictions As RequiredConversion
)
Debug.Assert(Not typeByAssumption OrElse type.IsObjectType() OrElse TypeOf type Is ArrayLiteralTypeSymbol, "unexpected: a type which was 'by assumption', but isn't object or array literal")
' Don't add error types to the type argument inference collection.
If type.IsErrorType Then
Return
End If
Dim foundInList As Boolean = False
' Do not merge array literals with other expressions
If TypeOf type IsNot ArrayLiteralTypeSymbol Then
For Each competitor As DominantTypeDataTypeInference In InferenceTypeCollection.GetTypeDataList()
' Do not merge array literals with other expressions
If TypeOf competitor.ResultType IsNot ArrayLiteralTypeSymbol AndAlso type.IsSameTypeIgnoringAll(competitor.ResultType) Then
competitor.ResultType = TypeInferenceCollection.MergeTupleNames(competitor.ResultType, type)
competitor.InferenceRestrictions = Conversions.CombineConversionRequirements(
competitor.InferenceRestrictions,
inferenceRestrictions)
competitor.ByAssumption = competitor.ByAssumption AndAlso typeByAssumption
Debug.Assert(Not foundInList, "List is supposed to be unique: how can we already find two of the same type in this list.")
foundInList = True
' TODO: Should we simply exit the loop for RELEASE build?
End If
Next
End If
If Not foundInList Then
Dim typeData As DominantTypeDataTypeInference = New DominantTypeDataTypeInference()
typeData.ResultType = type
typeData.ByAssumption = typeByAssumption
typeData.InferenceRestrictions = inferenceRestrictions
typeData.ArgumentLocation = argumentLocation
typeData.Parameter = parameter
typeData.InferredFromObject = inferredFromObject
typeData.TypeParameter = DeclaredTypeParam
InferenceTypeCollection.GetTypeDataList().Add(typeData)
End If
End Sub
End Class
Private Class ArgumentNode
Inherits InferenceNode
Public ReadOnly ParameterType As TypeSymbol
Public ReadOnly Expression As BoundExpression
Public ReadOnly Parameter As ParameterSymbol
Public Sub New(graph As InferenceGraph, expression As BoundExpression, parameterType As TypeSymbol, parameter As ParameterSymbol)
MyBase.New(graph, InferenceNodeType.ArgumentNode)
Me.Expression = expression
Me.ParameterType = parameterType
Me.Parameter = parameter
End Sub
Public Overrides Function InferTypeAndPropagateHints() As Boolean
#If DEBUG Then
VerifyIncomingInferenceComplete(InferenceNodeType.TypeParameterNode)
#End If
' Check if all incoming are ok, otherwise skip inference.
For Each currentGraphNode As InferenceNode In IncomingEdges
Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.TypeParameterNode, "Should only have typed nodes as incoming edges.")
Dim currentTypedNode As TypeParameterNode = DirectCast(currentGraphNode, TypeParameterNode)
If currentTypedNode.InferredType Is Nothing Then
Dim skipThisNode As Boolean = True
If Expression.Kind = BoundKind.UnboundLambda AndAlso ParameterType.IsDelegateType() Then
' Check here if we need to infer Object for some of the parameters of the Lambda if we weren't able
' to infer these otherwise. This is only the case for arguments of the lambda that have a GenericParam
' of the method we are inferring that is not yet inferred.
' Now find the invoke method of the delegate
Dim delegateType = DirectCast(ParameterType, NamedTypeSymbol)
Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod
If invokeMethod IsNot Nothing AndAlso invokeMethod.GetUseSiteInfo().DiagnosticInfo Is Nothing Then
Dim unboundLambda = DirectCast(Expression, UnboundLambda)
Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) = unboundLambda.Parameters
Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters
For i As Integer = 0 To Math.Min(lambdaParameters.Length, delegateParameters.Length) - 1 Step 1
Dim lambdaParameter = DirectCast(lambdaParameters(i), UnboundLambdaParameterSymbol)
Dim delegateParam As ParameterSymbol = delegateParameters(i)
If lambdaParameter.Type Is Nothing AndAlso
delegateParam.Type.Equals(currentTypedNode.DeclaredTypeParam) Then
If Graph.Diagnostic Is Nothing Then
Graph.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Graph.UseSiteInfo.AccumulatesDependencies)
End If
' If this was an argument to the unbound Lambda, infer Object.
If Graph.ObjectType Is Nothing Then
Debug.Assert(Graph.Diagnostic IsNot Nothing)
Graph.ObjectType = unboundLambda.Binder.GetSpecialType(SpecialType.System_Object, lambdaParameter.IdentifierSyntax, Graph.Diagnostic)
End If
currentTypedNode.RegisterInferredType(Graph.ObjectType,
lambdaParameter.TypeSyntax,
currentTypedNode.InferredTypeByAssumption)
'
' Port SP1 CL 2941063 to VS10
' Bug 153317
' Report an error if Option Strict On or a warning if Option Strict Off
' because we have no hints about the lambda parameter
' and we are assuming that it is an object.
' e.g. "Sub f(Of T, U)(ByVal x As Func(Of T, U))" invoked with "f(function(z)z)"
' needs to put the squiggly on the first "z".
Debug.Assert(Graph.Diagnostic IsNot Nothing)
unboundLambda.Binder.ReportLambdaParameterInferredToBeObject(lambdaParameter, Graph.Diagnostic)
skipThisNode = False
Exit For
End If
Next
End If
End If
If skipThisNode Then
InferenceComplete = True
Return False ' DOn't restart the algorithm.
End If
End If
Next
Dim argumentType As TypeSymbol = Nothing
Dim inferenceOk As Boolean = False
Select Case Expression.Kind
Case BoundKind.AddressOfOperator
inferenceOk = Graph.InferTypeArgumentsFromAddressOfArgument(
Expression,
ParameterType,
Parameter)
Case BoundKind.LateAddressOfOperator
' We can not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference
' as not failed due to object.
Graph.ReportNotFailedInferenceDueToObject()
inferenceOk = True
Case BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda, BoundKind.UnboundLambda
' TODO: Not sure if this is applicable to Roslyn, need to try this out when all required features are available.
' BUG: 131359 If the lambda is wrapped in a delegate constructor the resultType
' will be set and not be Void. In this case the lambda argument should be treated as a regular
' argument so fall through in this case.
Debug.Assert(Expression.Type Is Nothing)
' TODO: We are setting inference level before
' even trying to infer something from the lambda. It is possible
' that we won't infer anything, should consider changing the
' inference level after.
Graph.MarkInferenceLevel(InferenceLevel.Orcas)
inferenceOk = Graph.InferTypeArgumentsFromLambdaArgument(
Expression,
ParameterType,
Parameter)
Case Else
HandleAsAGeneralExpression:
' We should not infer from a Nothing literal.
If Expression.IsStrictNothingLiteral() Then
InferenceComplete = True
' continue without restarting, if all hints are Nothing the InferenceTypeNode will mark
' the inference as failed.
Return False
End If
Dim inferenceRestrictions As RequiredConversion = RequiredConversion.Any
If Parameter IsNot Nothing AndAlso
Parameter.IsByRef AndAlso
(Expression.IsLValue() OrElse Expression.IsPropertySupportingAssignment()) Then
' A ByRef parameter needs (if the argument was an lvalue) to be copy-backable into
' that argument.
Debug.Assert(inferenceRestrictions = RequiredConversion.Any, "there should have been no prior restrictions by the time we encountered ByRef")
inferenceRestrictions = Conversions.CombineConversionRequirements(
inferenceRestrictions,
Conversions.InvertConversionRequirement(inferenceRestrictions))
Debug.Assert(inferenceRestrictions = RequiredConversion.AnyAndReverse, "expected ByRef to require AnyAndReverseConversion")
End If
Dim arrayLiteral As BoundArrayLiteral = Nothing
Dim argumentTypeByAssumption As Boolean = False
Dim expressionType As TypeSymbol
If Expression.Kind = BoundKind.ArrayLiteral Then
arrayLiteral = DirectCast(Expression, BoundArrayLiteral)
argumentTypeByAssumption = arrayLiteral.NumberOfCandidates <> 1
expressionType = New ArrayLiteralTypeSymbol(arrayLiteral)
ElseIf Expression.Kind = BoundKind.TupleLiteral Then
expressionType = DirectCast(Expression, BoundTupleLiteral).InferredType
Else
expressionType = Expression.Type
End If
' Need to create an ArrayLiteralTypeSymbol
inferenceOk = Graph.InferTypeArgumentsFromArgument(
Expression.Syntax,
expressionType,
argumentTypeByAssumption,
ParameterType,
Parameter,
MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions)
End Select
If Not inferenceOk Then
' !! Inference has failed. Mismatch of Argument and Parameter signature, so could not find type hints.
Graph.MarkInferenceFailure()
If Not (Expression.Type IsNot Nothing AndAlso Expression.Type.IsObjectType()) Then
Graph.ReportNotFailedInferenceDueToObject()
End If
End If
InferenceComplete = True
Return False ' // Don't restart the algorithm;
End Function
End Class
Private Class InferenceGraph
Inherits Graph(Of InferenceNode)
Public Diagnostic As BindingDiagnosticBag
Public ObjectType As NamedTypeSymbol
Public ReadOnly Candidate As MethodSymbol
Public ReadOnly Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly ParameterToArgumentMap As ArrayBuilder(Of Integer)
Public ReadOnly ParamArrayItems As ArrayBuilder(Of Integer)
Public ReadOnly DelegateReturnType As TypeSymbol
Public ReadOnly DelegateReturnTypeReferenceBoundNode As BoundNode
Public UseSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
Private _someInferenceFailed As Boolean
Private _inferenceErrorReasons As InferenceErrorReasons
Private _allFailedInferenceIsDueToObject As Boolean = True ' remains true until proven otherwise.
Private _typeInferenceLevel As InferenceLevel = InferenceLevel.None
Private _asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression)
Private ReadOnly _typeParameterNodes As ImmutableArray(Of TypeParameterNode)
Private ReadOnly _verifyingAssertions As Boolean
Private Sub New(
diagnostic As BindingDiagnosticBag,
candidate As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
parameterToArgumentMap As ArrayBuilder(Of Integer),
paramArrayItems As ArrayBuilder(Of Integer),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(delegateReturnType Is Nothing OrElse delegateReturnTypeReferenceBoundNode IsNot Nothing)
Me.Diagnostic = diagnostic
Me.Candidate = candidate
Me.Arguments = arguments
Me.ParameterToArgumentMap = parameterToArgumentMap
Me.ParamArrayItems = paramArrayItems
Me.DelegateReturnType = delegateReturnType
Me.DelegateReturnTypeReferenceBoundNode = delegateReturnTypeReferenceBoundNode
Me._asyncLambdaSubToFunctionMismatch = asyncLambdaSubToFunctionMismatch
Me.UseSiteInfo = useSiteInfo
' Allocate the array of TypeParameter nodes.
Dim arity As Integer = candidate.Arity
Dim typeParameterNodes(arity - 1) As TypeParameterNode
For i As Integer = 0 To arity - 1 Step 1
typeParameterNodes(i) = New TypeParameterNode(Me, candidate.TypeParameters(i))
Next
_typeParameterNodes = typeParameterNodes.AsImmutableOrNull()
End Sub
Public ReadOnly Property SomeInferenceHasFailed As Boolean
Get
Return _someInferenceFailed
End Get
End Property
Public Sub MarkInferenceFailure()
_someInferenceFailed = True
End Sub
Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean
Get
Return _allFailedInferenceIsDueToObject
End Get
End Property
Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons
Get
Return _inferenceErrorReasons
End Get
End Property
Public Sub ReportNotFailedInferenceDueToObject()
_allFailedInferenceIsDueToObject = False
End Sub
Public ReadOnly Property TypeInferenceLevel As InferenceLevel
Get
Return _typeInferenceLevel
End Get
End Property
Public Sub MarkInferenceLevel(typeInferenceLevel As InferenceLevel)
If _typeInferenceLevel < typeInferenceLevel Then
_typeInferenceLevel = typeInferenceLevel
End If
End Sub
Public Shared Function Infer(
candidate As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
parameterToArgumentMap As ArrayBuilder(Of Integer),
paramArrayItems As ArrayBuilder(Of Integer),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
ByRef typeArguments As ImmutableArray(Of TypeSymbol),
ByRef inferenceLevel As InferenceLevel,
ByRef allFailedInferenceIsDueToObject As Boolean,
ByRef someInferenceFailed As Boolean,
ByRef inferenceErrorReasons As InferenceErrorReasons,
<Out> ByRef inferredTypeByAssumption As BitVector,
<Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
ByRef diagnostic As BindingDiagnosticBag,
inferTheseTypeParameters As BitVector
) As Boolean
Dim graph As New InferenceGraph(diagnostic, candidate, arguments, parameterToArgumentMap, paramArrayItems,
delegateReturnType, delegateReturnTypeReferenceBoundNode, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
' Build a graph describing the flow of type inference data.
' This creates edges from "regular" arguments to type parameters and from type parameters to lambda arguments.
' In the rest of this function that graph is then processed (see below for more details). Essentially, for each
' "type parameter" node a list of "type hints" (possible candidates for type inference) is collected. The dominant
' type algorithm is then performed over the list of hints associated with each node.
'
' The process of populating the graph also seeds type hints for type parameters referenced by explicitly typed
' lambda parameters. Also, hints sometimes have restrictions placed on them that limit what conversions the dominant type
' algorithm can consider when it processes them. The restrictions are generally driven by the context in which type
' parameters are used. For example if a type parameter is used as a type parameter of another type (something like IGoo(of T)),
' then the dominant type algorithm is not allowed to consider any conversions. There are similar restrictions for
' Array co-variance.
graph.PopulateGraph()
Dim topoSortedGraph = ArrayBuilder(Of StronglyConnectedComponent(Of InferenceNode)).GetInstance()
' This is the restart point of the algorithm
Do
Dim restartAlgorithm As Boolean = False
Dim stronglyConnectedComponents As Graph(Of StronglyConnectedComponent(Of InferenceNode)) =
graph.BuildStronglyConnectedComponents()
topoSortedGraph.Clear()
stronglyConnectedComponents.TopoSort(topoSortedGraph)
' We now iterate over the topologically-sorted strongly connected components of the graph, and generate
' type hints as appropriate.
'
' When we find a node for an argument (or an ArgumentNode as it's referred to in the code), we infer
' types for all type parameters referenced by that argument and then propagate those types as hints
' to the referenced type parameters. If there are incoming edges into the argument node, they correspond
' to parameters of lambda arguments that get their value from the delegate type that contains type
' parameters that would have been inferred during a previous iteration of the loop. Those types are
' flowed into the lambda argument.
'
' When we encounter a "type parameter" node (or TypeParameterNode as it is called in the code), we run
' the dominant type algorithm over all of it's hints and use the resulting type as the value for the
' referenced type parameter.
'
' If we find a strongly connected component with more than one node, it means we
' have a cycle and cannot simply run the inference algorithm. When this happens,
' we look through the nodes in the cycle for a type parameter node with at least
' one type hint. If we find one, we remove all incoming edges to that node,
' infer the type using its hints, and then restart the whole algorithm from the
' beginning (recompute the strongly connected components, resort them, and then
' iterate over the graph again). The source nodes of the incoming edges we
' removed are added to an "assertion list". After graph traversal is done we
' then run inference on any "assertion nodes" we may have created.
For Each sccNode As StronglyConnectedComponent(Of InferenceNode) In topoSortedGraph
Dim childNodes As ArrayBuilder(Of InferenceNode) = sccNode.ChildNodes
' Small optimization if one node
If childNodes.Count = 1 Then
If childNodes(0).InferTypeAndPropagateHints() Then
' consider: scottwis
' We should be asserting here, because this code is unreachable..
' There are two implementations of InferTypeAndPropagateHints,
' one for "named nodes" (nodes corresponding to arguments) and another
' for "type nodes" (nodes corresponding to types).
' The implementation for "named nodes" always returns false, which means
' "don't restart the algorithm". The implementation for "type nodes" only returns true
' if a node has incoming edges that have not been visited previously. In order for that
' to happen the node must be inside a strongly connected component with more than one node
' (i.e. it must be involved in a cycle). If it wasn't we would be visiting it in
' topological order, which means all incoming edges should have already been visited.
' That means that if we reach this code, there is probably a bug in the traversal process. We
' don't want to silently mask the bug. At a minimum we should either assert or generate a compiler error.
'
' An argument could be made that it is good to have this because
' InferTypeAndPropagateHints is virtual, and should some new node type be
' added it's implementation may return true, and so this would follow that
' path. That argument does make some tiny amount of sense, and so we
' should keep this code here to make it easier to make any such
' modifications in the future. However, we still need an assert to guard
' against graph traversal bugs, and in the event that such changes are
' made, leave it to the modifier to remove the assert if necessary.
Throw ExceptionUtilities.Unreachable
End If
Else
Dim madeInferenceProgress As Boolean = False
For Each child As InferenceNode In childNodes
If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso
DirectCast(child, TypeParameterNode).InferenceTypeCollection.GetTypeDataList().Count > 0 Then
If child.InferTypeAndPropagateHints() Then
' If edges were broken, restart algorithm to recompute strongly connected components.
restartAlgorithm = True
End If
madeInferenceProgress = True
End If
Next
If Not madeInferenceProgress Then
' Did not make progress trying to force incoming edges for nodes with TypesHints, just inferring all now,
' will infer object if no type hints.
For Each child As InferenceNode In childNodes
If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso
child.InferTypeAndPropagateHints() Then
' If edges were broken, restart algorithm to recompute strongly connected components.
restartAlgorithm = True
End If
Next
End If
If restartAlgorithm Then
Exit For ' For Each sccNode
End If
End If
Next
If restartAlgorithm Then
Continue Do
End If
Exit Do
Loop
'The commented code below is from Dev10, but it looks like
'it doesn't do anything useful because topoSortedGraph contains
'StronglyConnectedComponents, which have NodeType=None.
'
'graph.m_VerifyingAssertions = True
'GraphNodeListIterator assertionIter(&topoSortedGraph);
' While (assertionIter.MoveNext())
'{
' GraphNode* currentNode = assertionIter.Current();
' if (currentNode->m_NodeType == TypedNodeType)
' {
' InferenceTypeNode* currentTypeNode = (InferenceTypeNode*)currentNode;
' currentTypeNode->VerifyTypeAssertions();
' }
'}
'graph.m_VerifyingAssertions = False
topoSortedGraph.Free()
Dim succeeded As Boolean = Not graph.SomeInferenceHasFailed
someInferenceFailed = graph.SomeInferenceHasFailed
allFailedInferenceIsDueToObject = graph.AllFailedInferenceIsDueToObject
inferenceErrorReasons = graph.InferenceErrorReasons
' Make sure that allFailedInferenceIsDueToObject only stays set,
' if there was an actual inference failure.
If Not someInferenceFailed OrElse delegateReturnType IsNot Nothing Then
allFailedInferenceIsDueToObject = False
End If
Dim arity As Integer = candidate.Arity
Dim inferredTypes(arity - 1) As TypeSymbol
Dim inferredFromLocation(arity - 1) As SyntaxNodeOrToken
For i As Integer = 0 To arity - 1 Step 1
' TODO: Should we use InferredType or CandidateInferredType here? It looks like Dev10 is using the latter,
' it might not be cleaned in case of a failure. Will use the former for now.
Dim typeParameterNode = graph._typeParameterNodes(i)
Dim inferredType As TypeSymbol = typeParameterNode.InferredType
If inferredType Is Nothing AndAlso
(inferTheseTypeParameters.IsNull OrElse inferTheseTypeParameters(i)) Then
succeeded = False
End If
If typeParameterNode.InferredTypeByAssumption Then
If inferredTypeByAssumption.IsNull Then
inferredTypeByAssumption = BitVector.Create(arity)
End If
inferredTypeByAssumption(i) = True
End If
inferredTypes(i) = inferredType
inferredFromLocation(i) = typeParameterNode.InferredFromLocation
Next
typeArguments = inferredTypes.AsImmutableOrNull()
typeArgumentsLocation = inferredFromLocation.AsImmutableOrNull()
inferenceLevel = graph._typeInferenceLevel
Debug.Assert(diagnostic Is Nothing OrElse diagnostic Is graph.Diagnostic)
diagnostic = graph.Diagnostic
asyncLambdaSubToFunctionMismatch = graph._asyncLambdaSubToFunctionMismatch
useSiteInfo = graph.UseSiteInfo
Return succeeded
End Function
Private Sub PopulateGraph()
Dim candidate As MethodSymbol = Me.Candidate
Dim arguments As ImmutableArray(Of BoundExpression) = Me.Arguments
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Me.ParameterToArgumentMap
Dim paramArrayItems As ArrayBuilder(Of Integer) = Me.ParamArrayItems
Dim isExpandedParamArrayForm As Boolean = (paramArrayItems IsNot Nothing)
Dim argIndex As Integer
For paramIndex = 0 To candidate.ParameterCount - 1 Step 1
Dim param As ParameterSymbol = candidate.Parameters(paramIndex)
Dim targetType As TypeSymbol = param.Type
If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then
If targetType.Kind <> SymbolKind.ArrayType Then
Continue For
End If
If Not isExpandedParamArrayForm Then
argIndex = parameterToArgumentMap(paramIndex)
Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex))
Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument)
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
'!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!!
If paramArrayArgument Is Nothing OrElse paramArrayArgument.HasErrors OrElse
Not ArgumentTypePossiblyMatchesParamarrayShape(paramArrayArgument, targetType) Then
Continue For
End If
RegisterArgument(paramArrayArgument, targetType, param)
Else
Debug.Assert(isExpandedParamArrayForm)
'§11.8.2 Applicable Methods
'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form.
' Note, that explicitly converted NOTHING is treated the same way by Dev10.
If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() Then
Continue For
End If
' Otherwise, for a ParamArray parameter, all the matching arguments are passed
' ByVal as instances of the element type of the ParamArray.
' Perform the conversions to the element type of the ParamArray here.
Dim arrayType = DirectCast(targetType, ArrayTypeSymbol)
If Not arrayType.IsSZArray Then
Continue For
End If
targetType = arrayType.ElementType
If targetType.Kind = SymbolKind.ErrorType Then
Continue For
End If
For j As Integer = 0 To paramArrayItems.Count - 1 Step 1
If arguments(paramArrayItems(j)).HasErrors Then
Continue For
End If
RegisterArgument(arguments(paramArrayItems(j)), targetType, param)
Next
End If
Continue For
End If
argIndex = parameterToArgumentMap(paramIndex)
Dim argument = If(argIndex = -1, Nothing, arguments(argIndex))
If argument Is Nothing OrElse argument.HasErrors OrElse targetType.IsErrorType() OrElse argument.Kind = BoundKind.OmittedArgument Then
Continue For
End If
RegisterArgument(argument, targetType, param)
Next
AddDelegateReturnTypeToGraph()
End Sub
Private Sub AddDelegateReturnTypeToGraph()
If Me.DelegateReturnType IsNot Nothing AndAlso Not Me.DelegateReturnType.IsVoidType() Then
Dim fakeArgument As New BoundRValuePlaceholder(Me.DelegateReturnTypeReferenceBoundNode.Syntax,
Me.DelegateReturnType)
Dim returnNode As New ArgumentNode(Me, fakeArgument, Me.Candidate.ReturnType, parameter:=Nothing)
' Add the edges from all the current generic parameters to this named node.
For Each current As InferenceNode In Vertices
If current.NodeType = InferenceNodeType.TypeParameterNode Then
AddEdge(current, returnNode)
End If
Next
' Add the edges from the resultType outgoing to the generic parameters.
AddTypeToGraph(returnNode, isOutgoingEdge:=True)
End If
End Sub
Private Sub RegisterArgument(
argument As BoundExpression,
targetType As TypeSymbol,
param As ParameterSymbol
)
' Dig through parenthesized.
If Not argument.IsNothingLiteral Then
argument = argument.GetMostEnclosedParenthesizedExpression()
End If
Dim argNode As New ArgumentNode(Me, argument, targetType, param)
Select Case argument.Kind
Case BoundKind.UnboundLambda, BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda
AddLambdaToGraph(argNode, argument.GetBinderFromLambda())
Case BoundKind.AddressOfOperator
AddAddressOfToGraph(argNode, DirectCast(argument, BoundAddressOfOperator).Binder)
Case BoundKind.TupleLiteral
AddTupleLiteralToGraph(argNode)
Case Else
AddTypeToGraph(argNode, isOutgoingEdge:=True)
End Select
End Sub
Private Sub AddTypeToGraph(
node As ArgumentNode,
isOutgoingEdge As Boolean
)
AddTypeToGraph(node.ParameterType, node, isOutgoingEdge, BitVector.Create(_typeParameterNodes.Length))
End Sub
Private Function FindTypeParameterNode(typeParameter As TypeParameterSymbol) As TypeParameterNode
Dim ordinal As Integer = typeParameter.Ordinal
If ordinal < _typeParameterNodes.Length AndAlso
_typeParameterNodes(ordinal) IsNot Nothing AndAlso
typeParameter.Equals(_typeParameterNodes(ordinal).DeclaredTypeParam) Then
Return _typeParameterNodes(ordinal)
End If
Return Nothing
End Function
Private Sub AddTypeToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode,
isOutgoingEdge As Boolean,
ByRef haveSeenTypeParameters As BitVector
)
Select Case parameterType.Kind
Case SymbolKind.TypeParameter
Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol)
Dim typeParameterNode As TypeParameterNode = FindTypeParameterNode(typeParameter)
If typeParameterNode IsNot Nothing AndAlso
Not haveSeenTypeParameters(typeParameter.Ordinal) Then
If typeParameterNode.Parameter Is Nothing Then
typeParameterNode.SetParameter(argNode.Parameter)
End If
If (isOutgoingEdge) Then
AddEdge(argNode, typeParameterNode)
Else
AddEdge(typeParameterNode, argNode)
End If
haveSeenTypeParameters(typeParameter.Ordinal) = True
End If
Case SymbolKind.ArrayType
AddTypeToGraph(DirectCast(parameterType, ArrayTypeSymbol).ElementType, argNode, isOutgoingEdge, haveSeenTypeParameters)
Case SymbolKind.NamedType
Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol)
Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing
If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then
For Each elementType In elementTypes
AddTypeToGraph(elementType, argNode, isOutgoingEdge, haveSeenTypeParameters)
Next
Else
Do
For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
AddTypeToGraph(typeArgument, argNode, isOutgoingEdge, haveSeenTypeParameters)
Next
possiblyGenericType = possiblyGenericType.ContainingType
Loop While possiblyGenericType IsNot Nothing
End If
End Select
End Sub
Private Sub AddTupleLiteralToGraph(argNode As ArgumentNode)
AddTupleLiteralToGraph(argNode.ParameterType, argNode)
End Sub
Private Sub AddTupleLiteralToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode
)
Debug.Assert(argNode.Expression.Kind = BoundKind.TupleLiteral)
Dim tupleLiteral = DirectCast(argNode.Expression, BoundTupleLiteral)
Dim tupleArguments = tupleLiteral.Arguments
If parameterType.IsTupleOrCompatibleWithTupleOfCardinality(tupleArguments.Length) Then
Dim parameterElementTypes = parameterType.GetElementTypesOfTupleOrCompatible
For i As Integer = 0 To tupleArguments.Length - 1
RegisterArgument(tupleArguments(i), parameterElementTypes(i), argNode.Parameter)
Next
Return
End If
AddTypeToGraph(argNode, isOutgoingEdge:=True)
End Sub
Private Sub AddAddressOfToGraph(argNode As ArgumentNode, binder As Binder)
AddAddressOfToGraph(argNode.ParameterType, argNode, binder)
End Sub
Private Sub AddAddressOfToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode,
binder As Binder
)
Debug.Assert(argNode.Expression.Kind = BoundKind.AddressOfOperator)
If parameterType.IsTypeParameter() Then
AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length))
ElseIf parameterType.IsDelegateType() Then
Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol)
Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod
If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then
Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length)
AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) ' outgoing (name->type) edge
haveSeenTypeParameters.Clear()
For Each delegateParameter As ParameterSymbol In invoke.Parameters
AddTypeToGraph(delegateParameter.Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) ' incoming (type->name) edge
Next
End If
ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then
' If we've got an Expression(Of T), skip through to T
AddAddressOfToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder)
End If
End Sub
Private Sub AddLambdaToGraph(argNode As ArgumentNode, binder As Binder)
AddLambdaToGraph(argNode.ParameterType, argNode, binder)
End Sub
Private Sub AddLambdaToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode,
binder As Binder
)
If parameterType.IsTypeParameter() Then
' Lambda is bound to a generic typeParam, just infer anonymous delegate
AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length))
ElseIf parameterType.IsDelegateType() Then
Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol)
Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod
If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then
Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invoke.Parameters
Dim lambdaParameters As ImmutableArray(Of ParameterSymbol)
Select Case argNode.Expression.Kind
Case BoundKind.QueryLambda
lambdaParameters = DirectCast(argNode.Expression, BoundQueryLambda).LambdaSymbol.Parameters
Case BoundKind.GroupTypeInferenceLambda
lambdaParameters = DirectCast(argNode.Expression, GroupTypeInferenceLambda).Parameters
Case BoundKind.UnboundLambda
lambdaParameters = DirectCast(argNode.Expression, UnboundLambda).Parameters
Case Else
Throw ExceptionUtilities.UnexpectedValue(argNode.Expression.Kind)
End Select
Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length)
For i As Integer = 0 To Math.Min(delegateParameters.Length, lambdaParameters.Length) - 1 Step 1
If lambdaParameters(i).Type IsNot Nothing Then
' Prepopulate the hint from the lambda's parameter.
' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic
' !!! parameter will be passed into the parameter of argument type.
' TODO: Consider using location for the type declaration.
InferTypeArgumentsFromArgument(
argNode.Expression.Syntax,
lambdaParameters(i).Type,
argumentTypeByAssumption:=False,
parameterType:=delegateParameters(i).Type,
param:=delegateParameters(i),
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter,
inferenceRestrictions:=RequiredConversion.Any)
End If
AddTypeToGraph(delegateParameters(i).Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters)
Next
haveSeenTypeParameters.Clear()
AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters)
End If
ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then
' If we've got an Expression(Of T), skip through to T
AddLambdaToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder)
End If
End Sub
Private Shared Function ArgumentTypePossiblyMatchesParamarrayShape(argument As BoundExpression, paramType As TypeSymbol) As Boolean
Dim argumentType As TypeSymbol = argument.Type
Dim isArrayLiteral As Boolean = False
If argumentType Is Nothing Then
If argument.Kind = BoundKind.ArrayLiteral Then
isArrayLiteral = True
argumentType = DirectCast(argument, BoundArrayLiteral).InferredType
Else
Return False
End If
End If
While paramType.IsArrayType()
If Not argumentType.IsArrayType() Then
Return False
End If
Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol)
Dim paramArrayType = DirectCast(paramType, ArrayTypeSymbol)
' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches.
If argumentArray.Rank <> paramArrayType.Rank OrElse
(Not isArrayLiteral AndAlso argumentArray.IsSZArray <> paramArrayType.IsSZArray) Then
Return False
End If
isArrayLiteral = False
argumentType = argumentArray.ElementType
paramType = paramArrayType.ElementType
End While
Return True
End Function
Public Sub RegisterTypeParameterHint(
genericParameter As TypeParameterSymbol,
inferredType As TypeSymbol,
inferredTypeByAssumption As Boolean,
argumentLocation As SyntaxNode,
parameter As ParameterSymbol,
inferredFromObject As Boolean,
inferenceRestrictions As RequiredConversion
)
Dim typeNode As TypeParameterNode = FindTypeParameterNode(genericParameter)
If typeNode IsNot Nothing Then
typeNode.AddTypeHint(inferredType, inferredTypeByAssumption, argumentLocation, parameter, inferredFromObject, inferenceRestrictions)
End If
End Sub
Private Function RefersToGenericParameterToInferArgumentFor(
parameterType As TypeSymbol
) As Boolean
Select Case parameterType.Kind
Case SymbolKind.TypeParameter
Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol)
Dim typeNode As TypeParameterNode = FindTypeParameterNode(typeParameter)
' TODO: It looks like this check can give us a false positive. For example,
' if we are resolving a recursive call we might already bind a type
' parameter to itself (to the same type parameter of the containing method).
' So, the fact that we ran into this type parameter doesn't necessary mean
' that there is anything to infer. I am not sure if this can lead to some
' negative effect. Dev10 appears to have the same behavior, from what I see
' in the code.
If typeNode IsNot Nothing Then
Return True
End If
Case SymbolKind.ArrayType
Return RefersToGenericParameterToInferArgumentFor(DirectCast(parameterType, ArrayTypeSymbol).ElementType)
Case SymbolKind.NamedType
Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol)
Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing
If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then
For Each elementType In elementTypes
If RefersToGenericParameterToInferArgumentFor(elementType) Then
Return True
End If
Next
Else
Do
For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If RefersToGenericParameterToInferArgumentFor(typeArgument) Then
Return True
End If
Next
possiblyGenericType = possiblyGenericType.ContainingType
Loop While possiblyGenericType IsNot Nothing
End If
End Select
Return False
End Function
' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments
' to a generic method, infer type arguments corresponding to type parameters that occur
' in the parameter type.
'
' A return value of false indicates that inference fails.
'
' If a generic method is parameterized by T, an argument of type A matches a parameter of type
' P, this function tries to infer type for T by using these patterns:
'
' -- If P is T, then infer A for T
' -- If P is G(Of T) and A is G(Of X), then infer X for T
' -- If P is Array Of T, and A is Array Of X, then infer X for T
' -- If P is ByRef T, then infer A for T
Private Function InferTypeArgumentsFromArgumentDirectly(
argumentLocation As SyntaxNode,
argumentType As TypeSymbol,
argumentTypeByAssumption As Boolean,
parameterType As TypeSymbol,
param As ParameterSymbol,
digThroughToBasesAndImplements As MatchGenericArgumentToParameter,
inferenceRestrictions As RequiredConversion
) As Boolean
If argumentType Is Nothing OrElse argumentType.IsVoidType() Then
' We should never be able to infer a value from something that doesn't provide a value, e.g:
' Goo(Of T) can't be passed Sub bar(), as in Goo(Bar())
Return False
End If
' If a generic method is parameterized by T, an argument of type A matching a parameter of type
' P can be used to infer a type for T by these patterns:
'
' -- If P is T, then infer A for T
' -- If P is G(Of T) and A is G(Of X), then infer X for T
' -- If P is Array Of T, and A is Array Of X, then infer X for T
' -- If P is ByRef T, then infer A for T
' -- If P is (T, T) and A is (X, X), then infer X for T
If parameterType.IsTypeParameter() Then
RegisterTypeParameterHint(
DirectCast(parameterType, TypeParameterSymbol),
argumentType,
argumentTypeByAssumption,
argumentLocation,
param,
False,
inferenceRestrictions)
Return True
End If
Dim parameterElementTypes As ImmutableArray(Of TypeSymbol) = Nothing
Dim argumentElementTypes As ImmutableArray(Of TypeSymbol) = Nothing
If parameterType.GetNullableUnderlyingTypeOrSelf().TryGetElementTypesIfTupleOrCompatible(parameterElementTypes) AndAlso
If(parameterType.IsNullableType(), argumentType.GetNullableUnderlyingTypeOrSelf(), argumentType).
TryGetElementTypesIfTupleOrCompatible(argumentElementTypes) Then
If parameterElementTypes.Length <> argumentElementTypes.Length Then
Return False
End If
For typeArgumentIndex As Integer = 0 To parameterElementTypes.Length - 1
Dim parameterElementType = parameterElementTypes(typeArgumentIndex)
Dim argumentElementType = argumentElementTypes(typeArgumentIndex)
' propagate restrictions to the elements
If Not InferTypeArgumentsFromArgument(
argumentLocation,
argumentElementType,
argumentTypeByAssumption,
parameterElementType,
param,
digThroughToBasesAndImplements,
inferenceRestrictions
) Then
Return False
End If
Next
Return True
ElseIf parameterType.Kind = SymbolKind.NamedType Then
' e.g. handle goo(of T)(x as Bar(Of T)) We need to dig into Bar(Of T)
Dim parameterTypeAsNamedType = DirectCast(parameterType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
If parameterTypeAsNamedType.IsGenericType Then
Dim argumentTypeAsNamedType = If(argumentType.Kind = SymbolKind.NamedType, DirectCast(argumentType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol), Nothing)
If argumentTypeAsNamedType IsNot Nothing AndAlso argumentTypeAsNamedType.IsGenericType Then
If argumentTypeAsNamedType.OriginalDefinition.IsSameTypeIgnoringAll(parameterTypeAsNamedType.OriginalDefinition) Then
Do
For typeArgumentIndex As Integer = 0 To parameterTypeAsNamedType.Arity - 1 Step 1
' The following code is subtle. Let's recap what's going on...
' We've so far encountered some context, e.g. "_" or "ICovariant(_)"
' or "ByRef _" or the like. This context will have given us some TypeInferenceRestrictions.
' Now, inside the context, we've discovered a generic binding "G(Of _,_,_)"
' and we have to apply extra restrictions to each of those subcontexts.
' For non-variant parameters it's easy: the subcontexts just acquire the Identity constraint.
' For variant parameters it's more subtle. First, we have to strengthen the
' restrictions to require reference conversion (rather than just VB conversion or
' whatever it was). Second, if it was an In parameter, then we have to invert
' the sense.
'
' Processing of generics is tricky in the case that we've already encountered
' a "ByRef _". From that outer "ByRef _" we will have inferred the restriction
' "AnyConversionAndReverse", so that the argument could be copied into the parameter
' and back again. But now consider if we find a generic inside that ByRef, e.g.
' if it had been "ByRef x as G(Of T)" then what should we do? More specifically, consider a case
' "Sub f(Of T)(ByRef x as G(Of T))" invoked with some "dim arg as G(Of Hint)".
' What's needed for any candidate for T is that G(Of Hint) be convertible to
' G(Of Candidate), and vice versa for the copyback.
'
' But then what should we write down for the hints? The problem is that hints inhere
' to the generic parameter T, not to the function parameter G(Of T). So we opt for a
' safe approximation: we just require CLR identity between a candidate and the hint.
' This is safe but is a little overly-strict. For example:
' Class G(Of T)
' Public Shared Widening Operator CType(ByVal x As G(Of T)) As G(Of Animal)
' Public Shared Widening Operator CType(ByVal x As G(Of Animal)) As G(Of T)
' Sub inf(Of T)(ByRef x as G(Of T), ByVal y as T)
' ...
' inf(New G(Of Car), New Animal)
' inf(Of Animal)(New G(Of Car), New Animal)
' Then the hints will be "T:{Car=, Animal+}" and they'll result in inference-failure,
' even though the explicitly-provided T=Animal ends up working.
'
' Well, it's the best we can do without some major re-architecting of the way
' hints and type-inference works. That's because all our hints inhere to the
' type parameter T; in an ideal world, the ByRef hint would inhere to the parameter.
' But I don't think we'll ever do better than this, just because trying to do
' type inference inferring to arguments/parameters becomes exponential.
' Variance generic parameters will work the same.
' Dev10#595234: each Param'sInferenceRestriction is found as a modification of the surrounding InferenceRestriction:
Dim paramInferenceRestrictions As RequiredConversion
Select Case parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance
Case VarianceKind.In
paramInferenceRestrictions = Conversions.InvertConversionRequirement(
Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions))
Case VarianceKind.Out
paramInferenceRestrictions = Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions)
Case Else
Debug.Assert(VarianceKind.None = parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance)
paramInferenceRestrictions = RequiredConversion.Identity
End Select
Dim _DigThroughToBasesAndImplements As MatchGenericArgumentToParameter
If paramInferenceRestrictions = RequiredConversion.Reference Then
_DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter
ElseIf paramInferenceRestrictions = RequiredConversion.ReverseReference Then
_DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter
Else
_DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly
End If
If Not InferTypeArgumentsFromArgument(
argumentLocation,
argumentTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo),
argumentTypeByAssumption,
parameterTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo),
param,
_DigThroughToBasesAndImplements,
paramInferenceRestrictions
) Then
' TODO: Would it make sense to continue through other type arguments even if inference failed for
' the current one?
Return False
End If
Next
' Do not forget about type parameters of containing type
parameterTypeAsNamedType = parameterTypeAsNamedType.ContainingType
argumentTypeAsNamedType = argumentTypeAsNamedType.ContainingType
Loop While parameterTypeAsNamedType IsNot Nothing
Debug.Assert(parameterTypeAsNamedType Is Nothing AndAlso argumentTypeAsNamedType Is Nothing)
Return True
End If
ElseIf parameterTypeAsNamedType.IsNullableType() Then
' we reach here when the ParameterType is an instantiation of Nullable,
' and the argument type is NOT a generic type.
' lwischik: ??? what do array elements have to do with nullables?
Return InferTypeArgumentsFromArgument(
argumentLocation,
argumentType,
argumentTypeByAssumption,
parameterTypeAsNamedType.GetNullableUnderlyingType(),
param,
digThroughToBasesAndImplements,
Conversions.CombineConversionRequirements(inferenceRestrictions, RequiredConversion.ArrayElement))
End If
Return False
End If
ElseIf parameterType.IsArrayType() Then
If argumentType.IsArrayType() Then
Dim parameterArray = DirectCast(parameterType, ArrayTypeSymbol)
Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol)
Dim argumentIsAarrayLiteral = TypeOf argumentArray Is ArrayLiteralTypeSymbol
' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches.
If parameterArray.Rank = argumentArray.Rank AndAlso
(argumentIsAarrayLiteral OrElse parameterArray.IsSZArray = argumentArray.IsSZArray) Then
Return InferTypeArgumentsFromArgument(
argumentLocation,
argumentArray.ElementType,
argumentTypeByAssumption,
parameterArray.ElementType,
param,
digThroughToBasesAndImplements,
Conversions.CombineConversionRequirements(inferenceRestrictions, If(argumentIsAarrayLiteral, RequiredConversion.Any, RequiredConversion.ArrayElement)))
End If
End If
Return False
End If
Return True
End Function
' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments
' to a generic method, infer type arguments corresponding to type parameters that occur
' in the parameter type.
'
' A return value of false indicates that inference fails.
'
' This routine is given an argument e.g. "List(Of IEnumerable(Of Int))",
' and a parameter e.g. "IEnumerable(Of IEnumerable(Of T))".
' The task is to infer hints for T, e.g. "T=int".
' This function takes care of allowing (in this example) List(Of _) to match IEnumerable(Of _).
' As for the real work, i.e. matching the contents, we invoke "InferTypeArgumentsFromArgumentDirectly"
' to do that.
'
' Note: this function returns "false" if it failed to pattern-match between argument and parameter type,
' and "true" if it succeeded.
' Success in pattern-matching may or may not produce type-hints for generic parameters.
' If it happened not to produce any type-hints, then maybe other argument/parameter pairs will have produced
' their own type hints that allow inference to succeed, or maybe no-one else will have produced type hints,
' or maybe other people will have produced conflicting type hints. In those cases, we'd return True from
' here (to show success at pattern-matching) and leave the downstream code to produce an error message about
' failing to infer T.
Friend Function InferTypeArgumentsFromArgument(
argumentLocation As SyntaxNode,
argumentType As TypeSymbol,
argumentTypeByAssumption As Boolean,
parameterType As TypeSymbol,
param As ParameterSymbol,
digThroughToBasesAndImplements As MatchGenericArgumentToParameter,
inferenceRestrictions As RequiredConversion
) As Boolean
If Not RefersToGenericParameterToInferArgumentFor(parameterType) Then
Return True
End If
' First try to the things directly. Only if this fails will we bother searching for things like List->IEnumerable.
Dim Inferred As Boolean = InferTypeArgumentsFromArgumentDirectly(
argumentLocation,
argumentType,
argumentTypeByAssumption,
parameterType,
param,
digThroughToBasesAndImplements,
inferenceRestrictions)
If Inferred Then
Return True
End If
If parameterType.IsTypeParameter() Then
' If we failed to match an argument against a generic parameter T, it means that the
' argument was something unmatchable, e.g. an AddressOf.
Return False
End If
' If we didn't find a direct match, we will have to look in base classes for a match.
' We'll either fix ParameterType and look amongst the bases of ArgumentType,
' or we'll fix ArgumentType and look amongst the bases of ParameterType,
' depending on the "DigThroughToBasesAndImplements" flag. This flag is affected by
' covariance and contravariance...
If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly Then
Return False
End If
' Special handling for Anonymous Delegates.
If argumentType IsNot Nothing AndAlso argumentType.IsDelegateType() AndAlso parameterType.IsDelegateType() AndAlso
digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter AndAlso
(inferenceRestrictions = RequiredConversion.Any OrElse inferenceRestrictions = RequiredConversion.AnyReverse OrElse
inferenceRestrictions = RequiredConversion.AnyAndReverse) Then
Dim argumentDelegateType = DirectCast(argumentType, NamedTypeSymbol)
Dim argumentInvokeProc As MethodSymbol = argumentDelegateType.DelegateInvokeMethod
Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol)
Dim parameterInvokeProc As MethodSymbol = parameterDelegateType.DelegateInvokeMethod
Debug.Assert(argumentInvokeProc IsNot Nothing OrElse Not argumentDelegateType.IsAnonymousType)
' Note, null check for parameterInvokeDeclaration should also filter out MultiCastDelegate type.
If argumentDelegateType.IsAnonymousType AndAlso Not parameterDelegateType.IsAnonymousType AndAlso
parameterInvokeProc IsNot Nothing AndAlso parameterInvokeProc.GetUseSiteInfo().DiagnosticInfo Is Nothing Then
' Some trickery relating to the fact that anonymous delegates can be converted to any delegate type.
' We are trying to match the anonymous delegate "BaseSearchType" onto the delegate "FixedType". e.g.
' Dim f = function(i as integer) i // ArgumentType = VB$AnonymousDelegate`2(Of Integer,Integer)
' inf(f) // ParameterType might be e.g. D(Of T) for some function inf(Of T)(f as D(Of T))
' // maybe defined as Delegate Function D(Of T)(x as T) as T.
' We're looking to achieve the same functionality in pattern-matching these types as we already
' have for calling "inf(function(i as integer) i)" directly.
' It allows any VB conversion from param-of-fixed-type to param-of-base-type (not just reference conversions).
' But it does allow a zero-argument BaseSearchType to be used for a FixedType with more.
' And it does allow a function BaseSearchType to be used for a sub FixedType.
'
' Anyway, the plan is to match each of the parameters in the ArgumentType delegate
' to the equivalent parameters in the ParameterType delegate, and also match the return types.
'
' This only works for "ConversionRequired::Any", i.e. using VB conversion semantics. It doesn't work for
' reference conversions. As for the AnyReverse/AnyAndReverse, well, in Orcas that was guaranteed
' to fail type inference (i.e. return a false from this function). In Dev10 we will let it succeed
' with some inferred types, for the sake of better error messages, even though we know that ultimately
' it will fail (because no non-anonymous delegate type can be converted to a delegate type).
Dim argumentParams As ImmutableArray(Of ParameterSymbol) = argumentInvokeProc.Parameters
Dim parameterParams As ImmutableArray(Of ParameterSymbol) = parameterInvokeProc.Parameters
If parameterParams.Length <> argumentParams.Length AndAlso argumentParams.Length <> 0 Then
' If parameter-counts are mismatched then it's a failure.
' Exception: Zero-argument relaxation: we allow a parameterless VB$AnonymousDelegate argument
' to be supplied to a function which expects a parameterfull delegate.
Return False
End If
' First we'll check that the argument types all match.
For i As Integer = 0 To argumentParams.Length - 1
If argumentParams(i).IsByRef <> parameterParams(i).IsByRef Then
' Require an exact match between ByRef/ByVal, since that's how type inference of lambda expressions works.
Return False
End If
If Not InferTypeArgumentsFromArgument(
argumentLocation,
argumentParams(i).Type,
argumentTypeByAssumption,
parameterParams(i).Type,
param,
MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter,
RequiredConversion.AnyReverse) Then ' AnyReverse: contravariance in delegate arguments
Return False
End If
Next
' Now check that the return type matches.
' Note: we allow a *function* VB$AnonymousDelegate to be supplied to a function which expects a *sub* delegate.
If parameterInvokeProc.IsSub Then
' A *sub* delegate parameter can accept either a *function* or a *sub* argument:
Return True
ElseIf argumentInvokeProc.IsSub Then
' A *function* delegate parameter cannot accept a *sub* argument.
Return False
Else
' Otherwise, a function argument VB$AnonymousDelegate was supplied to a function parameter:
Return InferTypeArgumentsFromArgument(
argumentLocation,
argumentInvokeProc.ReturnType,
argumentTypeByAssumption,
parameterInvokeProc.ReturnType,
param,
MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
RequiredConversion.Any) ' Any: covariance in delegate returns
End If
End If
End If
' MatchBaseOfGenericArgumentToParameter: used for covariant situations,
' e.g. matching argument "List(Of _)" to parameter "ByVal x as IEnumerable(Of _)".
'
' Otherwise, MatchArgumentToBaseOfGenericParameter, used for contravariant situations,
' e.g. when matching argument "Action(Of IEnumerable(Of _))" to parameter "ByVal x as Action(Of List(Of _))".
Dim fContinue As Boolean = False
If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter Then
fContinue = FindMatchingBase(argumentType, parameterType)
Else
fContinue = FindMatchingBase(parameterType, argumentType)
End If
If Not fContinue Then
Return False
End If
' NOTE: baseSearchType was a REFERENCE, to either ArgumentType or ParameterType.
' Therefore the above statement has altered either ArgumentType or ParameterType.
Return InferTypeArgumentsFromArgumentDirectly(
argumentLocation,
argumentType,
argumentTypeByAssumption,
parameterType,
param,
digThroughToBasesAndImplements,
inferenceRestrictions)
End Function
Private Function FindMatchingBase(
ByRef baseSearchType As TypeSymbol,
ByRef fixedType As TypeSymbol
) As Boolean
Dim fixedTypeAsNamedType = If(fixedType.Kind = SymbolKind.NamedType, DirectCast(fixedType, NamedTypeSymbol), Nothing)
If fixedTypeAsNamedType Is Nothing OrElse Not fixedTypeAsNamedType.IsGenericType Then
' If the fixed candidate isn't a generic (e.g. matching argument IList(Of String) to non-generic parameter IList),
' then we won't learn anything about generic type parameters here:
Return False
End If
Dim fixedTypeTypeKind As TypeKind = fixedType.TypeKind
If fixedTypeTypeKind <> TypeKind.Class AndAlso fixedTypeTypeKind <> TypeKind.Interface Then
' Whatever "BaseSearchType" is, it can only inherit from "FixedType" if FixedType is a class/interface.
' (it's impossible to inherit from anything else).
Return False
End If
Dim baseSearchTypeKind As SymbolKind = baseSearchType.Kind
If baseSearchTypeKind <> SymbolKind.NamedType AndAlso baseSearchTypeKind <> SymbolKind.TypeParameter AndAlso
Not (baseSearchTypeKind = SymbolKind.ArrayType AndAlso DirectCast(baseSearchType, ArrayTypeSymbol).IsSZArray) Then
' The things listed above are the only ones that have bases that could ever lead anywhere useful.
' NamedType is satisfied by interfaces, structures, enums, delegates and modules as well as just classes.
Return False
End If
If baseSearchType.IsSameTypeIgnoringAll(fixedType) Then
' If the types checked were already identical, then exit
Return False
End If
' Otherwise, if we got through all the above tests, then it really is worth searching through the base
' types to see if that helps us find a match.
Dim matchingBase As TypeSymbol = Nothing
If fixedTypeTypeKind = TypeKind.Class Then
FindMatchingBaseClass(baseSearchType, fixedType, matchingBase)
Else
Debug.Assert(fixedTypeTypeKind = TypeKind.Interface)
FindMatchingBaseInterface(baseSearchType, fixedType, matchingBase)
End If
If matchingBase Is Nothing Then
Return False
End If
' And this is what we found
baseSearchType = matchingBase
Return True
End Function
Private Shared Function SetMatchIfNothingOrEqual(type As TypeSymbol, ByRef match As TypeSymbol) As Boolean
If match Is Nothing Then
match = type
Return True
ElseIf match.IsSameTypeIgnoringAll(type) Then
Return True
Else
match = Nothing
Return False
End If
End Function
''' <summary>
''' Returns False if the search should be cancelled.
''' </summary>
Private Function FindMatchingBaseInterface(derivedType As TypeSymbol, baseInterface As TypeSymbol, ByRef match As TypeSymbol) As Boolean
Select Case derivedType.Kind
Case SymbolKind.TypeParameter
For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual(constraint, match) Then
Return False
End If
End If
If Not FindMatchingBaseInterface(constraint, baseInterface, match) Then
Return False
End If
Next
Case Else
For Each [interface] In derivedType.AllInterfacesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If [interface].OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual([interface], match) Then
Return False
End If
End If
Next
End Select
Return True
End Function
''' <summary>
''' Returns False if the search should be cancelled.
''' </summary>
Private Function FindMatchingBaseClass(derivedType As TypeSymbol, baseClass As TypeSymbol, ByRef match As TypeSymbol) As Boolean
Select Case derivedType.Kind
Case SymbolKind.TypeParameter
For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual(constraint, match) Then
Return False
End If
End If
' TODO: Do we need to continue even if we already have a matching base class?
' It looks like Dev10 continues.
If Not FindMatchingBaseClass(constraint, baseClass, match) Then
Return False
End If
Next
Case Else
Dim baseType As NamedTypeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
While baseType IsNot Nothing
If baseType.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual(baseType, match) Then
Return False
End If
Exit While
End If
baseType = baseType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
End While
End Select
Return True
End Function
Public Function InferTypeArgumentsFromAddressOfArgument(
argument As BoundExpression,
parameterType As TypeSymbol,
param As ParameterSymbol
) As Boolean
If parameterType.IsDelegateType() Then
Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterType), NamedTypeSymbol)
' Now find the invoke method of the delegate
Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod
If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then
' If we don't have an Invoke method, just bail.
Return False
End If
Dim returnType As TypeSymbol = invokeMethod.ReturnType
' If the return type doesn't refer to parameters, no inference required.
If Not RefersToGenericParameterToInferArgumentFor(returnType) Then
Return True
End If
Dim addrOf = DirectCast(argument, BoundAddressOfOperator)
Dim fromMethod As MethodSymbol = Nothing
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = Binder.ResolveMethodForDelegateInvokeFullAndRelaxed(
addrOf,
invokeMethod,
ignoreMethodReturnType:=True,
diagnostics:=BindingDiagnosticBag.Discarded)
fromMethod = matchingMethod.Key
methodConversions = matchingMethod.Value
If fromMethod Is Nothing OrElse (methodConversions And MethodConversionKind.AllErrorReasons) <> 0 OrElse
(addrOf.Binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=True)) Then
Return False
End If
If fromMethod.IsSub Then
ReportNotFailedInferenceDueToObject()
Return True
End If
Dim targetReturnType As TypeSymbol = fromMethod.ReturnType
If RefersToGenericParameterToInferArgumentFor(targetReturnType) Then
' Return false if we didn't make any inference progress.
Return False
End If
Return InferTypeArgumentsFromArgument(
argument.Syntax,
targetReturnType,
argumentTypeByAssumption:=False,
parameterType:=returnType,
param:=param,
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions:=RequiredConversion.Any)
End If
' We did not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference
' as not failed due to object.
ReportNotFailedInferenceDueToObject()
Return True
End Function
Public Function InferTypeArgumentsFromLambdaArgument(
argument As BoundExpression,
parameterType As TypeSymbol,
param As ParameterSymbol
) As Boolean
Debug.Assert(argument.Kind = BoundKind.UnboundLambda OrElse
argument.Kind = BoundKind.QueryLambda OrElse
argument.Kind = BoundKind.GroupTypeInferenceLambda)
If parameterType.IsTypeParameter() Then
Dim anonymousLambdaType As TypeSymbol = Nothing
Select Case argument.Kind
Case BoundKind.QueryLambda
' Do not infer Anonymous Delegate type from query lambda.
Case BoundKind.GroupTypeInferenceLambda
' Can't infer from this lambda.
Case BoundKind.UnboundLambda
' Infer Anonymous Delegate type from unbound lambda.
Dim inferredAnonymousDelegate As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = DirectCast(argument, UnboundLambda).InferredAnonymousDelegate
If (inferredAnonymousDelegate.Value.Diagnostics.IsDefault OrElse Not inferredAnonymousDelegate.Value.Diagnostics.HasAnyErrors()) Then
Dim delegateInvokeMethod As MethodSymbol = Nothing
If inferredAnonymousDelegate.Key IsNot Nothing Then
delegateInvokeMethod = inferredAnonymousDelegate.Key.DelegateInvokeMethod
End If
If delegateInvokeMethod IsNot Nothing AndAlso delegateInvokeMethod.ReturnType IsNot LambdaSymbol.ReturnTypeIsUnknown Then
anonymousLambdaType = inferredAnonymousDelegate.Key
End If
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
If anonymousLambdaType IsNot Nothing Then
Return InferTypeArgumentsFromArgument(
argument.Syntax,
anonymousLambdaType,
argumentTypeByAssumption:=False,
parameterType:=parameterType,
param:=param,
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions:=RequiredConversion.Any)
Else
Return True
End If
ElseIf parameterType.IsDelegateType() Then
Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol)
' First, we need to build a partial type substitution using the type of
' arguments as they stand right now, with some of them still being uninferred.
' TODO: Doesn't this make the inference algorithm order dependent? For example, if we were to
' infer more stuff from other non-lambda arguments, we might have a better chance to have
' more type information for the lambda, allowing successful lambda interpretation.
' Perhaps the graph doesn't allow us to get here until all "inputs" for lambda parameters
' are inferred.
Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterDelegateType), NamedTypeSymbol)
' Now find the invoke method of the delegate
Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod
If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then
' If we don't have an Invoke method, just bail.
Return True
End If
Dim returnType As TypeSymbol = invokeMethod.ReturnType
' If the return type doesn't refer to parameters, no inference required.
If Not RefersToGenericParameterToInferArgumentFor(returnType) Then
Return True
End If
Dim lambdaParams As ImmutableArray(Of ParameterSymbol)
Select Case argument.Kind
Case BoundKind.QueryLambda
lambdaParams = DirectCast(argument, BoundQueryLambda).LambdaSymbol.Parameters
Case BoundKind.GroupTypeInferenceLambda
lambdaParams = DirectCast(argument, GroupTypeInferenceLambda).Parameters
Case BoundKind.UnboundLambda
lambdaParams = DirectCast(argument, UnboundLambda).Parameters
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
Dim delegateParams As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters
If lambdaParams.Length > delegateParams.Length Then
Return True
End If
For i As Integer = 0 To lambdaParams.Length - 1 Step 1
Dim lambdaParam As ParameterSymbol = lambdaParams(i)
Dim delegateParam As ParameterSymbol = delegateParams(i)
If lambdaParam.Type Is Nothing Then
' If a lambda parameter has no type and the delegate parameter refers
' to an unbound generic parameter, we can't infer yet.
If RefersToGenericParameterToInferArgumentFor(delegateParam.Type) Then
' Skip this type argument and other parameters will infer it or
' if that doesn't happen it will report an error.
' TODO: Why does it make sense to continue here? It looks like we can infer something from
' lambda's return type based on incomplete information. Also, this 'if' is redundant,
' there is nothing left to do in this loop anyway, and "continue" doesn't change anything.
Continue For
End If
Else
' report the type of the lambda parameter to the delegate parameter.
' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic
' !!! parameter will be passed into the parameter of argument type.
InferTypeArgumentsFromArgument(
argument.Syntax,
lambdaParam.Type,
argumentTypeByAssumption:=False,
parameterType:=delegateParam.Type,
param:=param,
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter,
inferenceRestrictions:=RequiredConversion.Any)
End If
Next
' OK, now try to infer delegates return type from the lambda.
Dim lambdaReturnType As TypeSymbol
Select Case argument.Kind
Case BoundKind.QueryLambda
Dim queryLambda = DirectCast(argument, BoundQueryLambda)
lambdaReturnType = queryLambda.LambdaSymbol.ReturnType
If lambdaReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then
lambdaReturnType = queryLambda.Expression.Type
If lambdaReturnType Is Nothing Then
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Debug.Assert(Me.Diagnostic IsNot Nothing)
lambdaReturnType = queryLambda.LambdaSymbol.ContainingBinder.MakeRValue(queryLambda.Expression, Me.Diagnostic).Type
End If
End If
Case BoundKind.GroupTypeInferenceLambda
lambdaReturnType = DirectCast(argument, GroupTypeInferenceLambda).InferLambdaReturnType(delegateParams)
Case BoundKind.UnboundLambda
Dim unboundLambda = DirectCast(argument, UnboundLambda)
If unboundLambda.IsFunctionLambda Then
Dim inferenceSignature As New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False)
Dim returnTypeInfo As KeyValuePair(Of TypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferReturnType(inferenceSignature)
If Not returnTypeInfo.Value.Diagnostics.IsDefault AndAlso returnTypeInfo.Value.Diagnostics.HasAnyErrors() Then
lambdaReturnType = Nothing
' Let's keep return type inference errors
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Me.Diagnostic.AddRange(returnTypeInfo.Value)
ElseIf returnTypeInfo.Key Is LambdaSymbol.ReturnTypeIsUnknown Then
lambdaReturnType = Nothing
Else
Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(inferenceSignature.ParameterTypes,
inferenceSignature.ParameterIsByRef,
returnTypeInfo.Key,
returnsByRef:=False))
Debug.Assert(boundLambda.LambdaSymbol.ReturnType Is returnTypeInfo.Key)
If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors Then
lambdaReturnType = returnTypeInfo.Key
' Let's keep return type inference warnings, if any.
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Me.Diagnostic.AddRange(returnTypeInfo.Value)
Me.Diagnostic.AddDependencies(boundLambda.Diagnostics.Dependencies)
Else
lambdaReturnType = Nothing
' Let's preserve diagnostics that caused the failure
If Not boundLambda.Diagnostics.Diagnostics.IsDefaultOrEmpty Then
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Me.Diagnostic.AddRange(boundLambda.Diagnostics)
End If
End If
End If
' But in the case of async/iterator lambdas, e.g. pass "Async Function() 1" to a parameter
' of type "Func(Of Task(Of T))" then we have to dig in further and match 1 to T...
If (unboundLambda.Flags And (SourceMemberFlags.Async Or SourceMemberFlags.Iterator)) <> 0 AndAlso
lambdaReturnType IsNot Nothing AndAlso lambdaReturnType.Kind = SymbolKind.NamedType AndAlso
returnType IsNot Nothing AndAlso returnType.Kind = SymbolKind.NamedType Then
' By this stage we know that
' * we have an async/iterator lambda argument
' * the parameter-to-match is a delegate type whose result type refers to generic parameters
' The parameter might be a delegate with result type e.g. "Task(Of T)" in which case we have
' to dig in. Or it might be a delegate with result type "T" in which case we
' don't dig in.
Dim lambdaReturnNamedType = DirectCast(lambdaReturnType, NamedTypeSymbol)
Dim returnNamedType = DirectCast(returnType, NamedTypeSymbol)
If lambdaReturnNamedType.Arity = 1 AndAlso
IsSameTypeIgnoringAll(lambdaReturnNamedType.OriginalDefinition,
returnNamedType.OriginalDefinition) Then
' We can assume that the lambda will have return type Task(Of T) or IEnumerable(Of T)
' or IEnumerator(Of T) as appropriate. That's already been ensured by the lambda-interpretation.
Debug.Assert(TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything) OrElse
TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T), TypeCompareKind.ConsiderEverything) OrElse
TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T), TypeCompareKind.ConsiderEverything))
lambdaReturnType = lambdaReturnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo)
returnType = returnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo)
End If
End If
Else
lambdaReturnType = Nothing
If Not invokeMethod.IsSub AndAlso (unboundLambda.Flags And SourceMemberFlags.Async) <> 0 Then
Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(delegateParams,
unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void),
returnsByRef:=False))
If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors() Then
If _asyncLambdaSubToFunctionMismatch Is Nothing Then
_asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance)
End If
_asyncLambdaSubToFunctionMismatch.Add(unboundLambda)
End If
End If
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
If lambdaReturnType Is Nothing Then
' Inference failed, give up.
Return False
End If
If lambdaReturnType.IsErrorType() Then
Return True
End If
' Now infer from the result type
' not ArgumentTypeByAssumption ??? lwischik: but maybe it should...
Return InferTypeArgumentsFromArgument(
argument.Syntax,
lambdaReturnType,
argumentTypeByAssumption:=False,
parameterType:=returnType,
param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions:=RequiredConversion.Any)
ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then
' If we've got an Expression(Of T), skip through to T
Return InferTypeArgumentsFromLambdaArgument(argument, DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), param)
End If
Return True
End Function
Public Function ConstructParameterTypeIfNeeded(parameterType As TypeSymbol) As TypeSymbol
' First, we need to build a partial type substitution using the type of
' arguments as they stand right now, with some of them still being uninferred.
Dim methodSymbol As MethodSymbol = Candidate
Dim typeArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance(_typeParameterNodes.Length)
For i As Integer = 0 To _typeParameterNodes.Length - 1 Step 1
Dim typeNode As TypeParameterNode = _typeParameterNodes(i)
Dim newType As TypeSymbol
If typeNode Is Nothing OrElse typeNode.CandidateInferredType Is Nothing Then
'No substitution
newType = methodSymbol.TypeParameters(i)
Else
newType = typeNode.CandidateInferredType
End If
typeArguments.Add(New TypeWithModifiers(newType))
Next
Dim partialSubstitution = TypeSubstitution.CreateAdditionalMethodTypeParameterSubstitution(methodSymbol.ConstructedFrom, typeArguments.ToImmutableAndFree())
' Now we apply the partial substitution to the delegate type, leaving uninferred type parameters as is
Return parameterType.InternalSubstituteTypeParameters(partialSubstitution).Type
End Function
Public Sub ReportAmbiguousInferenceError(typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference))
Debug.Assert(typeInfos.Count() >= 2, "Must have at least 2 elements in the list")
' Since they get added fifo, we need to walk the list backward.
For i As Integer = 1 To typeInfos.Count - 1 Step 1
Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i)
If Not currentTypeInfo.InferredFromObject Then
ReportNotFailedInferenceDueToObject()
' TODO: Should we exit the loop? For some reason Dev10 keeps going.
End If
Next
End Sub
Public Sub ReportIncompatibleInferenceError(
typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference))
If typeInfos.Count < 1 Then
Return
End If
' Since they get added fifo, we need to walk the list backward.
For i As Integer = 1 To typeInfos.Count - 1 Step 1
Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i)
If Not currentTypeInfo.InferredFromObject Then
ReportNotFailedInferenceDueToObject()
' TODO: Should we exit the loop? For some reason Dev10 keeps going.
End If
Next
End Sub
Public Sub RegisterErrorReasons(inferenceErrorReasons As InferenceErrorReasons)
_inferenceErrorReasons = _inferenceErrorReasons Or inferenceErrorReasons
End Sub
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' The only public entry point is the Infer method.
''' </summary>
Friend MustInherit Class TypeArgumentInference
Public Shared Function Infer(
candidate As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
parameterToArgumentMap As ArrayBuilder(Of Integer),
paramArrayItems As ArrayBuilder(Of Integer),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
ByRef typeArguments As ImmutableArray(Of TypeSymbol),
ByRef inferenceLevel As InferenceLevel,
ByRef allFailedInferenceIsDueToObject As Boolean,
ByRef someInferenceFailed As Boolean,
ByRef inferenceErrorReasons As InferenceErrorReasons,
<Out> ByRef inferredTypeByAssumption As BitVector,
<Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
ByRef diagnostic As BindingDiagnosticBag,
Optional inferTheseTypeParameters As BitVector = Nothing
) As Boolean
Debug.Assert(candidate Is candidate.ConstructedFrom)
Return InferenceGraph.Infer(candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode,
typeArguments, inferenceLevel, allFailedInferenceIsDueToObject, someInferenceFailed, inferenceErrorReasons,
inferredTypeByAssumption, typeArgumentsLocation, asyncLambdaSubToFunctionMismatch,
useSiteInfo, diagnostic, inferTheseTypeParameters)
End Function
' No-one should create instances of this class.
Private Sub New()
End Sub
Public Enum InferenceLevel As Byte
None = 0
' None is used to indicate uninitialized but semantically it should not matter if there is a whidbey delegate
' or no delegate in the overload resolution hence both have value 0 such that overload resolution
' will not prefer a non inferred method over an inferred one.
Whidbey = 0
Orcas = 1
' Keep invalid the biggest number
Invalid = 2
End Enum
' MatchGenericArgumentParameter:
' This is used in type inference, when matching an argument e.g. Arg(Of String) against a parameter Parm(Of T).
' In covariant contexts e.g. Action(Of _), the two match if Arg <= Parm (i.e. Arg inherits/implements Parm).
' In contravariant contexts e.g. IEnumerable(Of _), the two match if Parm <= Arg (i.e. Parm inherits/implements Arg).
' In invariant contexts e.g. List(Of _), the two match only if Arg and Parm are identical.
' Note: remember that rank-1 arrays T() implement IEnumerable(Of T), IList(Of T) and ICollection(Of T).
Public Enum MatchGenericArgumentToParameter
MatchBaseOfGenericArgumentToParameter
MatchArgumentToBaseOfGenericParameter
MatchGenericArgumentToParameterExactly
End Enum
Private Enum InferenceNodeType As Byte
ArgumentNode
TypeParameterNode
End Enum
Private MustInherit Class InferenceNode
Inherits GraphNode(Of InferenceNode)
Public ReadOnly NodeType As InferenceNodeType
Public InferenceComplete As Boolean
Protected Sub New(graph As InferenceGraph, nodeType As InferenceNodeType)
MyBase.New(graph)
Me.NodeType = nodeType
End Sub
Public Shadows ReadOnly Property Graph As InferenceGraph
Get
Return DirectCast(MyBase.Graph, InferenceGraph)
End Get
End Property
''' <summary>
''' Returns True if the inference algorithm should be restarted.
''' </summary>
Public MustOverride Function InferTypeAndPropagateHints() As Boolean
<Conditional("DEBUG")>
Public Sub VerifyIncomingInferenceComplete(
ByVal nodeType As InferenceNodeType
)
If Not Graph.SomeInferenceHasFailed() Then
For Each current As InferenceNode In IncomingEdges
Debug.Assert(current.NodeType = nodeType, "Should only have expected incoming edges.")
Debug.Assert(current.InferenceComplete, "Should have inferred type already")
Next
End If
End Sub
End Class
Private Class DominantTypeDataTypeInference
Inherits DominantTypeData
' Fields needed for error reporting
Public ByAssumption As Boolean ' was ResultType chosen by assumption or intention?
Public Parameter As ParameterSymbol
Public InferredFromObject As Boolean
Public TypeParameter As TypeParameterSymbol
Public ArgumentLocation As SyntaxNode
End Class
Private Class TypeParameterNode
Inherits InferenceNode
Public ReadOnly DeclaredTypeParam As TypeParameterSymbol
Public ReadOnly InferenceTypeCollection As TypeInferenceCollection(Of DominantTypeDataTypeInference)
Private _inferredType As TypeSymbol
Private _inferredFromLocation As SyntaxNodeOrToken
Private _inferredTypeByAssumption As Boolean
' TODO: Dev10 has two locations to track type inferred so far.
' One that can be changed with time and the other one that cannot be changed.
' This one, cannot be changed once set. We need to clean this up later.
Private _candidateInferredType As TypeSymbol
Private _parameter As ParameterSymbol
Public Sub New(graph As InferenceGraph, typeParameter As TypeParameterSymbol)
MyBase.New(graph, InferenceNodeType.TypeParameterNode)
DeclaredTypeParam = typeParameter
InferenceTypeCollection = New TypeInferenceCollection(Of DominantTypeDataTypeInference)()
End Sub
Public ReadOnly Property InferredType As TypeSymbol
Get
Return _inferredType
End Get
End Property
Public ReadOnly Property CandidateInferredType As TypeSymbol
Get
Return _candidateInferredType
End Get
End Property
Public ReadOnly Property InferredFromLocation As SyntaxNodeOrToken
Get
Return _inferredFromLocation
End Get
End Property
Public ReadOnly Property InferredTypeByAssumption As Boolean
Get
Return _inferredTypeByAssumption
End Get
End Property
Public Sub RegisterInferredType(inferredType As TypeSymbol, inferredFromLocation As SyntaxNodeOrToken, inferredTypeByAssumption As Boolean)
' Make sure ArrayLiteralTypeSymbol does not leak out
Dim arrayLiteralType = TryCast(inferredType, ArrayLiteralTypeSymbol)
If arrayLiteralType IsNot Nothing Then
Dim arrayLiteral = arrayLiteralType.ArrayLiteral
Dim arrayType = arrayLiteral.InferredType
If Not (arrayLiteral.HasDominantType AndAlso arrayLiteral.NumberOfCandidates = 1) AndAlso
arrayType.ElementType.SpecialType = SpecialType.System_Object Then
' ReportArrayLiteralInferredTypeDiagnostics in ReclassifyArrayLiteralExpression reports an error
' when option strict is on and the array type is object() and there wasn't a dominant type. However,
' Dev10 does not report this error when inferring a type parameter's type. Create a new object() type
' to suppress the error.
inferredType = ArrayTypeSymbol.CreateVBArray(arrayType.ElementType, Nothing, arrayType.Rank, arrayLiteral.Binder.Compilation.Assembly)
Else
inferredType = arrayLiteral.InferredType
End If
End If
Debug.Assert(Not (TypeOf inferredType Is ArrayLiteralTypeSymbol))
_inferredType = inferredType
_inferredFromLocation = inferredFromLocation
_inferredTypeByAssumption = inferredTypeByAssumption
' TODO: Dev10 has two locations to track type inferred so far.
' One that can be changed with time and the other one that cannot be changed.
' We need to clean this up.
If _candidateInferredType Is Nothing Then
_candidateInferredType = inferredType
End If
End Sub
Public ReadOnly Property Parameter As ParameterSymbol
Get
Return _parameter
End Get
End Property
Public Sub SetParameter(parameter As ParameterSymbol)
Debug.Assert(_parameter Is Nothing)
_parameter = parameter
End Sub
Public Overrides Function InferTypeAndPropagateHints() As Boolean
Dim numberOfIncomingEdges As Integer = IncomingEdges.Count
Dim restartAlgorithm As Boolean = False
Dim argumentLocation As SyntaxNode
Dim numberOfIncomingWithNothing As Integer = 0
If numberOfIncomingEdges > 0 Then
argumentLocation = DirectCast(IncomingEdges(0), ArgumentNode).Expression.Syntax
Else
argumentLocation = Nothing
End If
Dim numberOfAssertions As Integer = 0
Dim incomingFromObject As Boolean = False
Dim list As ArrayBuilder(Of InferenceNode) = IncomingEdges
For Each currentGraphNode As InferenceNode In IncomingEdges
Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.ArgumentNode, "Should only have named nodes as incoming edges.")
Dim currentNamedNode = DirectCast(currentGraphNode, ArgumentNode)
If currentNamedNode.Expression.Type IsNot Nothing AndAlso
currentNamedNode.Expression.Type.IsObjectType() Then
incomingFromObject = True
End If
If Not currentNamedNode.InferenceComplete Then
Graph.RemoveEdge(currentNamedNode, Me)
restartAlgorithm = True
numberOfAssertions += 1
Else
' We should not infer from a Nothing literal.
If currentNamedNode.Expression.IsStrictNothingLiteral() Then
numberOfIncomingWithNothing += 1
End If
End If
Next
If numberOfIncomingEdges > 0 AndAlso numberOfIncomingEdges = numberOfIncomingWithNothing Then
' !! Inference has failed: All incoming type hints, were based on 'Nothing'
Graph.MarkInferenceFailure()
Graph.ReportNotFailedInferenceDueToObject()
End If
Dim numberOfTypeHints As Integer = InferenceTypeCollection.GetTypeDataList().Count()
If numberOfTypeHints = 0 Then
If numberOfAssertions = numberOfIncomingEdges Then
Graph.MarkInferenceLevel(InferenceLevel.Orcas)
Else
' !! Inference has failed. No Type hints, and some, not all were assertions, otherwise we would have picked object for strict.
RegisterInferredType(Nothing, Nothing, False)
Graph.MarkInferenceFailure()
If Not incomingFromObject Then
Graph.ReportNotFailedInferenceDueToObject()
End If
End If
ElseIf numberOfTypeHints = 1 Then
Dim typeData As DominantTypeDataTypeInference = InferenceTypeCollection.GetTypeDataList()(0)
If argumentLocation Is Nothing AndAlso typeData.ArgumentLocation IsNot Nothing Then
argumentLocation = typeData.ArgumentLocation
End If
RegisterInferredType(typeData.ResultType, argumentLocation, typeData.ByAssumption)
Else
' Run the whidbey algorithm to see if we are smarter now.
Dim firstInferredType As TypeSymbol = Nothing
Dim allTypeData As ArrayBuilder(Of DominantTypeDataTypeInference) = InferenceTypeCollection.GetTypeDataList()
For Each currentTypeInfo As DominantTypeDataTypeInference In allTypeData
If firstInferredType Is Nothing Then
firstInferredType = currentTypeInfo.ResultType
ElseIf Not firstInferredType.IsSameTypeIgnoringAll(currentTypeInfo.ResultType) Then
' Whidbey failed hard here, in Orcas we added dominant type information.
Graph.MarkInferenceLevel(InferenceLevel.Orcas)
End If
Next
Dim dominantTypeDataList = ArrayBuilder(Of DominantTypeDataTypeInference).GetInstance()
Dim errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other
InferenceTypeCollection.FindDominantType(dominantTypeDataList, errorReasons, Graph.UseSiteInfo)
If dominantTypeDataList.Count = 1 Then
' //consider: scottwis
' // This seems dangerous to me, that we
' // remove error reasons here.
' // Instead of clearing these, what we should be doing is
' // asserting that they are not set.
' // If for some reason they get set, but
' // we enter this path, then we have a bug.
' // This code is just masking any such bugs.
errorReasons = errorReasons And (Not (InferenceErrorReasons.Ambiguous Or InferenceErrorReasons.NoBest))
Dim typeData As DominantTypeDataTypeInference = dominantTypeDataList(0)
RegisterInferredType(typeData.ResultType, typeData.ArgumentLocation, typeData.ByAssumption)
' // Also update the location of the argument for constraint error reporting later on.
Else
If (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then
' !! Inference has failed. Dominant type algorithm found ambiguous types.
Graph.ReportAmbiguousInferenceError(dominantTypeDataList)
Else
' //consider: scottwis
' // This code appears to be operating under the assumption that if the error reason is not due to an
' // ambiguity then it must be because there was no best match.
' // We should be asserting here to verify that assertion.
' !! Inference has failed. Dominant type algorithm could not find a dominant type.
Graph.ReportIncompatibleInferenceError(allTypeData)
End If
RegisterInferredType(allTypeData(0).ResultType, argumentLocation, False)
Graph.MarkInferenceFailure()
End If
Graph.RegisterErrorReasons(errorReasons)
dominantTypeDataList.Free()
End If
InferenceComplete = True
Return restartAlgorithm
End Function
Public Sub AddTypeHint(
type As TypeSymbol,
typeByAssumption As Boolean,
argumentLocation As SyntaxNode,
parameter As ParameterSymbol,
inferredFromObject As Boolean,
inferenceRestrictions As RequiredConversion
)
Debug.Assert(Not typeByAssumption OrElse type.IsObjectType() OrElse TypeOf type Is ArrayLiteralTypeSymbol, "unexpected: a type which was 'by assumption', but isn't object or array literal")
' Don't add error types to the type argument inference collection.
If type.IsErrorType Then
Return
End If
Dim foundInList As Boolean = False
' Do not merge array literals with other expressions
If TypeOf type IsNot ArrayLiteralTypeSymbol Then
For Each competitor As DominantTypeDataTypeInference In InferenceTypeCollection.GetTypeDataList()
' Do not merge array literals with other expressions
If TypeOf competitor.ResultType IsNot ArrayLiteralTypeSymbol AndAlso type.IsSameTypeIgnoringAll(competitor.ResultType) Then
competitor.ResultType = TypeInferenceCollection.MergeTupleNames(competitor.ResultType, type)
competitor.InferenceRestrictions = Conversions.CombineConversionRequirements(
competitor.InferenceRestrictions,
inferenceRestrictions)
competitor.ByAssumption = competitor.ByAssumption AndAlso typeByAssumption
Debug.Assert(Not foundInList, "List is supposed to be unique: how can we already find two of the same type in this list.")
foundInList = True
' TODO: Should we simply exit the loop for RELEASE build?
End If
Next
End If
If Not foundInList Then
Dim typeData As DominantTypeDataTypeInference = New DominantTypeDataTypeInference()
typeData.ResultType = type
typeData.ByAssumption = typeByAssumption
typeData.InferenceRestrictions = inferenceRestrictions
typeData.ArgumentLocation = argumentLocation
typeData.Parameter = parameter
typeData.InferredFromObject = inferredFromObject
typeData.TypeParameter = DeclaredTypeParam
InferenceTypeCollection.GetTypeDataList().Add(typeData)
End If
End Sub
End Class
Private Class ArgumentNode
Inherits InferenceNode
Public ReadOnly ParameterType As TypeSymbol
Public ReadOnly Expression As BoundExpression
Public ReadOnly Parameter As ParameterSymbol
Public Sub New(graph As InferenceGraph, expression As BoundExpression, parameterType As TypeSymbol, parameter As ParameterSymbol)
MyBase.New(graph, InferenceNodeType.ArgumentNode)
Me.Expression = expression
Me.ParameterType = parameterType
Me.Parameter = parameter
End Sub
Public Overrides Function InferTypeAndPropagateHints() As Boolean
#If DEBUG Then
VerifyIncomingInferenceComplete(InferenceNodeType.TypeParameterNode)
#End If
' Check if all incoming are ok, otherwise skip inference.
For Each currentGraphNode As InferenceNode In IncomingEdges
Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.TypeParameterNode, "Should only have typed nodes as incoming edges.")
Dim currentTypedNode As TypeParameterNode = DirectCast(currentGraphNode, TypeParameterNode)
If currentTypedNode.InferredType Is Nothing Then
Dim skipThisNode As Boolean = True
If Expression.Kind = BoundKind.UnboundLambda AndAlso ParameterType.IsDelegateType() Then
' Check here if we need to infer Object for some of the parameters of the Lambda if we weren't able
' to infer these otherwise. This is only the case for arguments of the lambda that have a GenericParam
' of the method we are inferring that is not yet inferred.
' Now find the invoke method of the delegate
Dim delegateType = DirectCast(ParameterType, NamedTypeSymbol)
Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod
If invokeMethod IsNot Nothing AndAlso invokeMethod.GetUseSiteInfo().DiagnosticInfo Is Nothing Then
Dim unboundLambda = DirectCast(Expression, UnboundLambda)
Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) = unboundLambda.Parameters
Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters
For i As Integer = 0 To Math.Min(lambdaParameters.Length, delegateParameters.Length) - 1 Step 1
Dim lambdaParameter = DirectCast(lambdaParameters(i), UnboundLambdaParameterSymbol)
Dim delegateParam As ParameterSymbol = delegateParameters(i)
If lambdaParameter.Type Is Nothing AndAlso
delegateParam.Type.Equals(currentTypedNode.DeclaredTypeParam) Then
If Graph.Diagnostic Is Nothing Then
Graph.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Graph.UseSiteInfo.AccumulatesDependencies)
End If
' If this was an argument to the unbound Lambda, infer Object.
If Graph.ObjectType Is Nothing Then
Debug.Assert(Graph.Diagnostic IsNot Nothing)
Graph.ObjectType = unboundLambda.Binder.GetSpecialType(SpecialType.System_Object, lambdaParameter.IdentifierSyntax, Graph.Diagnostic)
End If
currentTypedNode.RegisterInferredType(Graph.ObjectType,
lambdaParameter.TypeSyntax,
currentTypedNode.InferredTypeByAssumption)
'
' Port SP1 CL 2941063 to VS10
' Bug 153317
' Report an error if Option Strict On or a warning if Option Strict Off
' because we have no hints about the lambda parameter
' and we are assuming that it is an object.
' e.g. "Sub f(Of T, U)(ByVal x As Func(Of T, U))" invoked with "f(function(z)z)"
' needs to put the squiggly on the first "z".
Debug.Assert(Graph.Diagnostic IsNot Nothing)
unboundLambda.Binder.ReportLambdaParameterInferredToBeObject(lambdaParameter, Graph.Diagnostic)
skipThisNode = False
Exit For
End If
Next
End If
End If
If skipThisNode Then
InferenceComplete = True
Return False ' DOn't restart the algorithm.
End If
End If
Next
Dim argumentType As TypeSymbol = Nothing
Dim inferenceOk As Boolean = False
Select Case Expression.Kind
Case BoundKind.AddressOfOperator
inferenceOk = Graph.InferTypeArgumentsFromAddressOfArgument(
Expression,
ParameterType,
Parameter)
Case BoundKind.LateAddressOfOperator
' We can not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference
' as not failed due to object.
Graph.ReportNotFailedInferenceDueToObject()
inferenceOk = True
Case BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda, BoundKind.UnboundLambda
' TODO: Not sure if this is applicable to Roslyn, need to try this out when all required features are available.
' BUG: 131359 If the lambda is wrapped in a delegate constructor the resultType
' will be set and not be Void. In this case the lambda argument should be treated as a regular
' argument so fall through in this case.
Debug.Assert(Expression.Type Is Nothing)
' TODO: We are setting inference level before
' even trying to infer something from the lambda. It is possible
' that we won't infer anything, should consider changing the
' inference level after.
Graph.MarkInferenceLevel(InferenceLevel.Orcas)
inferenceOk = Graph.InferTypeArgumentsFromLambdaArgument(
Expression,
ParameterType,
Parameter)
Case Else
HandleAsAGeneralExpression:
' We should not infer from a Nothing literal.
If Expression.IsStrictNothingLiteral() Then
InferenceComplete = True
' continue without restarting, if all hints are Nothing the InferenceTypeNode will mark
' the inference as failed.
Return False
End If
Dim inferenceRestrictions As RequiredConversion = RequiredConversion.Any
If Parameter IsNot Nothing AndAlso
Parameter.IsByRef AndAlso
(Expression.IsLValue() OrElse Expression.IsPropertySupportingAssignment()) Then
' A ByRef parameter needs (if the argument was an lvalue) to be copy-backable into
' that argument.
Debug.Assert(inferenceRestrictions = RequiredConversion.Any, "there should have been no prior restrictions by the time we encountered ByRef")
inferenceRestrictions = Conversions.CombineConversionRequirements(
inferenceRestrictions,
Conversions.InvertConversionRequirement(inferenceRestrictions))
Debug.Assert(inferenceRestrictions = RequiredConversion.AnyAndReverse, "expected ByRef to require AnyAndReverseConversion")
End If
Dim arrayLiteral As BoundArrayLiteral = Nothing
Dim argumentTypeByAssumption As Boolean = False
Dim expressionType As TypeSymbol
If Expression.Kind = BoundKind.ArrayLiteral Then
arrayLiteral = DirectCast(Expression, BoundArrayLiteral)
argumentTypeByAssumption = arrayLiteral.NumberOfCandidates <> 1
expressionType = New ArrayLiteralTypeSymbol(arrayLiteral)
ElseIf Expression.Kind = BoundKind.TupleLiteral Then
expressionType = DirectCast(Expression, BoundTupleLiteral).InferredType
Else
expressionType = Expression.Type
End If
' Need to create an ArrayLiteralTypeSymbol
inferenceOk = Graph.InferTypeArgumentsFromArgument(
Expression.Syntax,
expressionType,
argumentTypeByAssumption,
ParameterType,
Parameter,
MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions)
End Select
If Not inferenceOk Then
' !! Inference has failed. Mismatch of Argument and Parameter signature, so could not find type hints.
Graph.MarkInferenceFailure()
If Not (Expression.Type IsNot Nothing AndAlso Expression.Type.IsObjectType()) Then
Graph.ReportNotFailedInferenceDueToObject()
End If
End If
InferenceComplete = True
Return False ' // Don't restart the algorithm;
End Function
End Class
Private Class InferenceGraph
Inherits Graph(Of InferenceNode)
Public Diagnostic As BindingDiagnosticBag
Public ObjectType As NamedTypeSymbol
Public ReadOnly Candidate As MethodSymbol
Public ReadOnly Arguments As ImmutableArray(Of BoundExpression)
Public ReadOnly ParameterToArgumentMap As ArrayBuilder(Of Integer)
Public ReadOnly ParamArrayItems As ArrayBuilder(Of Integer)
Public ReadOnly DelegateReturnType As TypeSymbol
Public ReadOnly DelegateReturnTypeReferenceBoundNode As BoundNode
Public UseSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
Private _someInferenceFailed As Boolean
Private _inferenceErrorReasons As InferenceErrorReasons
Private _allFailedInferenceIsDueToObject As Boolean = True ' remains true until proven otherwise.
Private _typeInferenceLevel As InferenceLevel = InferenceLevel.None
Private _asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression)
Private ReadOnly _typeParameterNodes As ImmutableArray(Of TypeParameterNode)
Private ReadOnly _verifyingAssertions As Boolean
Private Sub New(
diagnostic As BindingDiagnosticBag,
candidate As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
parameterToArgumentMap As ArrayBuilder(Of Integer),
paramArrayItems As ArrayBuilder(Of Integer),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
)
Debug.Assert(delegateReturnType Is Nothing OrElse delegateReturnTypeReferenceBoundNode IsNot Nothing)
Me.Diagnostic = diagnostic
Me.Candidate = candidate
Me.Arguments = arguments
Me.ParameterToArgumentMap = parameterToArgumentMap
Me.ParamArrayItems = paramArrayItems
Me.DelegateReturnType = delegateReturnType
Me.DelegateReturnTypeReferenceBoundNode = delegateReturnTypeReferenceBoundNode
Me._asyncLambdaSubToFunctionMismatch = asyncLambdaSubToFunctionMismatch
Me.UseSiteInfo = useSiteInfo
' Allocate the array of TypeParameter nodes.
Dim arity As Integer = candidate.Arity
Dim typeParameterNodes(arity - 1) As TypeParameterNode
For i As Integer = 0 To arity - 1 Step 1
typeParameterNodes(i) = New TypeParameterNode(Me, candidate.TypeParameters(i))
Next
_typeParameterNodes = typeParameterNodes.AsImmutableOrNull()
End Sub
Public ReadOnly Property SomeInferenceHasFailed As Boolean
Get
Return _someInferenceFailed
End Get
End Property
Public Sub MarkInferenceFailure()
_someInferenceFailed = True
End Sub
Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean
Get
Return _allFailedInferenceIsDueToObject
End Get
End Property
Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons
Get
Return _inferenceErrorReasons
End Get
End Property
Public Sub ReportNotFailedInferenceDueToObject()
_allFailedInferenceIsDueToObject = False
End Sub
Public ReadOnly Property TypeInferenceLevel As InferenceLevel
Get
Return _typeInferenceLevel
End Get
End Property
Public Sub MarkInferenceLevel(typeInferenceLevel As InferenceLevel)
If _typeInferenceLevel < typeInferenceLevel Then
_typeInferenceLevel = typeInferenceLevel
End If
End Sub
Public Shared Function Infer(
candidate As MethodSymbol,
arguments As ImmutableArray(Of BoundExpression),
parameterToArgumentMap As ArrayBuilder(Of Integer),
paramArrayItems As ArrayBuilder(Of Integer),
delegateReturnType As TypeSymbol,
delegateReturnTypeReferenceBoundNode As BoundNode,
ByRef typeArguments As ImmutableArray(Of TypeSymbol),
ByRef inferenceLevel As InferenceLevel,
ByRef allFailedInferenceIsDueToObject As Boolean,
ByRef someInferenceFailed As Boolean,
ByRef inferenceErrorReasons As InferenceErrorReasons,
<Out> ByRef inferredTypeByAssumption As BitVector,
<Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken),
<[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression),
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol),
ByRef diagnostic As BindingDiagnosticBag,
inferTheseTypeParameters As BitVector
) As Boolean
Dim graph As New InferenceGraph(diagnostic, candidate, arguments, parameterToArgumentMap, paramArrayItems,
delegateReturnType, delegateReturnTypeReferenceBoundNode, asyncLambdaSubToFunctionMismatch,
useSiteInfo)
' Build a graph describing the flow of type inference data.
' This creates edges from "regular" arguments to type parameters and from type parameters to lambda arguments.
' In the rest of this function that graph is then processed (see below for more details). Essentially, for each
' "type parameter" node a list of "type hints" (possible candidates for type inference) is collected. The dominant
' type algorithm is then performed over the list of hints associated with each node.
'
' The process of populating the graph also seeds type hints for type parameters referenced by explicitly typed
' lambda parameters. Also, hints sometimes have restrictions placed on them that limit what conversions the dominant type
' algorithm can consider when it processes them. The restrictions are generally driven by the context in which type
' parameters are used. For example if a type parameter is used as a type parameter of another type (something like IGoo(of T)),
' then the dominant type algorithm is not allowed to consider any conversions. There are similar restrictions for
' Array co-variance.
graph.PopulateGraph()
Dim topoSortedGraph = ArrayBuilder(Of StronglyConnectedComponent(Of InferenceNode)).GetInstance()
' This is the restart point of the algorithm
Do
Dim restartAlgorithm As Boolean = False
Dim stronglyConnectedComponents As Graph(Of StronglyConnectedComponent(Of InferenceNode)) =
graph.BuildStronglyConnectedComponents()
topoSortedGraph.Clear()
stronglyConnectedComponents.TopoSort(topoSortedGraph)
' We now iterate over the topologically-sorted strongly connected components of the graph, and generate
' type hints as appropriate.
'
' When we find a node for an argument (or an ArgumentNode as it's referred to in the code), we infer
' types for all type parameters referenced by that argument and then propagate those types as hints
' to the referenced type parameters. If there are incoming edges into the argument node, they correspond
' to parameters of lambda arguments that get their value from the delegate type that contains type
' parameters that would have been inferred during a previous iteration of the loop. Those types are
' flowed into the lambda argument.
'
' When we encounter a "type parameter" node (or TypeParameterNode as it is called in the code), we run
' the dominant type algorithm over all of it's hints and use the resulting type as the value for the
' referenced type parameter.
'
' If we find a strongly connected component with more than one node, it means we
' have a cycle and cannot simply run the inference algorithm. When this happens,
' we look through the nodes in the cycle for a type parameter node with at least
' one type hint. If we find one, we remove all incoming edges to that node,
' infer the type using its hints, and then restart the whole algorithm from the
' beginning (recompute the strongly connected components, resort them, and then
' iterate over the graph again). The source nodes of the incoming edges we
' removed are added to an "assertion list". After graph traversal is done we
' then run inference on any "assertion nodes" we may have created.
For Each sccNode As StronglyConnectedComponent(Of InferenceNode) In topoSortedGraph
Dim childNodes As ArrayBuilder(Of InferenceNode) = sccNode.ChildNodes
' Small optimization if one node
If childNodes.Count = 1 Then
If childNodes(0).InferTypeAndPropagateHints() Then
' consider: scottwis
' We should be asserting here, because this code is unreachable..
' There are two implementations of InferTypeAndPropagateHints,
' one for "named nodes" (nodes corresponding to arguments) and another
' for "type nodes" (nodes corresponding to types).
' The implementation for "named nodes" always returns false, which means
' "don't restart the algorithm". The implementation for "type nodes" only returns true
' if a node has incoming edges that have not been visited previously. In order for that
' to happen the node must be inside a strongly connected component with more than one node
' (i.e. it must be involved in a cycle). If it wasn't we would be visiting it in
' topological order, which means all incoming edges should have already been visited.
' That means that if we reach this code, there is probably a bug in the traversal process. We
' don't want to silently mask the bug. At a minimum we should either assert or generate a compiler error.
'
' An argument could be made that it is good to have this because
' InferTypeAndPropagateHints is virtual, and should some new node type be
' added it's implementation may return true, and so this would follow that
' path. That argument does make some tiny amount of sense, and so we
' should keep this code here to make it easier to make any such
' modifications in the future. However, we still need an assert to guard
' against graph traversal bugs, and in the event that such changes are
' made, leave it to the modifier to remove the assert if necessary.
Throw ExceptionUtilities.Unreachable
End If
Else
Dim madeInferenceProgress As Boolean = False
For Each child As InferenceNode In childNodes
If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso
DirectCast(child, TypeParameterNode).InferenceTypeCollection.GetTypeDataList().Count > 0 Then
If child.InferTypeAndPropagateHints() Then
' If edges were broken, restart algorithm to recompute strongly connected components.
restartAlgorithm = True
End If
madeInferenceProgress = True
End If
Next
If Not madeInferenceProgress Then
' Did not make progress trying to force incoming edges for nodes with TypesHints, just inferring all now,
' will infer object if no type hints.
For Each child As InferenceNode In childNodes
If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso
child.InferTypeAndPropagateHints() Then
' If edges were broken, restart algorithm to recompute strongly connected components.
restartAlgorithm = True
End If
Next
End If
If restartAlgorithm Then
Exit For ' For Each sccNode
End If
End If
Next
If restartAlgorithm Then
Continue Do
End If
Exit Do
Loop
'The commented code below is from Dev10, but it looks like
'it doesn't do anything useful because topoSortedGraph contains
'StronglyConnectedComponents, which have NodeType=None.
'
'graph.m_VerifyingAssertions = True
'GraphNodeListIterator assertionIter(&topoSortedGraph);
' While (assertionIter.MoveNext())
'{
' GraphNode* currentNode = assertionIter.Current();
' if (currentNode->m_NodeType == TypedNodeType)
' {
' InferenceTypeNode* currentTypeNode = (InferenceTypeNode*)currentNode;
' currentTypeNode->VerifyTypeAssertions();
' }
'}
'graph.m_VerifyingAssertions = False
topoSortedGraph.Free()
Dim succeeded As Boolean = Not graph.SomeInferenceHasFailed
someInferenceFailed = graph.SomeInferenceHasFailed
allFailedInferenceIsDueToObject = graph.AllFailedInferenceIsDueToObject
inferenceErrorReasons = graph.InferenceErrorReasons
' Make sure that allFailedInferenceIsDueToObject only stays set,
' if there was an actual inference failure.
If Not someInferenceFailed OrElse delegateReturnType IsNot Nothing Then
allFailedInferenceIsDueToObject = False
End If
Dim arity As Integer = candidate.Arity
Dim inferredTypes(arity - 1) As TypeSymbol
Dim inferredFromLocation(arity - 1) As SyntaxNodeOrToken
For i As Integer = 0 To arity - 1 Step 1
' TODO: Should we use InferredType or CandidateInferredType here? It looks like Dev10 is using the latter,
' it might not be cleaned in case of a failure. Will use the former for now.
Dim typeParameterNode = graph._typeParameterNodes(i)
Dim inferredType As TypeSymbol = typeParameterNode.InferredType
If inferredType Is Nothing AndAlso
(inferTheseTypeParameters.IsNull OrElse inferTheseTypeParameters(i)) Then
succeeded = False
End If
If typeParameterNode.InferredTypeByAssumption Then
If inferredTypeByAssumption.IsNull Then
inferredTypeByAssumption = BitVector.Create(arity)
End If
inferredTypeByAssumption(i) = True
End If
inferredTypes(i) = inferredType
inferredFromLocation(i) = typeParameterNode.InferredFromLocation
Next
typeArguments = inferredTypes.AsImmutableOrNull()
typeArgumentsLocation = inferredFromLocation.AsImmutableOrNull()
inferenceLevel = graph._typeInferenceLevel
Debug.Assert(diagnostic Is Nothing OrElse diagnostic Is graph.Diagnostic)
diagnostic = graph.Diagnostic
asyncLambdaSubToFunctionMismatch = graph._asyncLambdaSubToFunctionMismatch
useSiteInfo = graph.UseSiteInfo
Return succeeded
End Function
Private Sub PopulateGraph()
Dim candidate As MethodSymbol = Me.Candidate
Dim arguments As ImmutableArray(Of BoundExpression) = Me.Arguments
Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Me.ParameterToArgumentMap
Dim paramArrayItems As ArrayBuilder(Of Integer) = Me.ParamArrayItems
Dim isExpandedParamArrayForm As Boolean = (paramArrayItems IsNot Nothing)
Dim argIndex As Integer
For paramIndex = 0 To candidate.ParameterCount - 1 Step 1
Dim param As ParameterSymbol = candidate.Parameters(paramIndex)
Dim targetType As TypeSymbol = param.Type
If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then
If targetType.Kind <> SymbolKind.ArrayType Then
Continue For
End If
If Not isExpandedParamArrayForm Then
argIndex = parameterToArgumentMap(paramIndex)
Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex))
Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument)
'§11.8.2 Applicable Methods
'If the conversion from the type of the argument expression to the paramarray type is narrowing,
'then the method is only applicable in its expanded form.
'!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!!
If paramArrayArgument Is Nothing OrElse paramArrayArgument.HasErrors OrElse
Not ArgumentTypePossiblyMatchesParamarrayShape(paramArrayArgument, targetType) Then
Continue For
End If
RegisterArgument(paramArrayArgument, targetType, param)
Else
Debug.Assert(isExpandedParamArrayForm)
'§11.8.2 Applicable Methods
'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form.
' Note, that explicitly converted NOTHING is treated the same way by Dev10.
If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() Then
Continue For
End If
' Otherwise, for a ParamArray parameter, all the matching arguments are passed
' ByVal as instances of the element type of the ParamArray.
' Perform the conversions to the element type of the ParamArray here.
Dim arrayType = DirectCast(targetType, ArrayTypeSymbol)
If Not arrayType.IsSZArray Then
Continue For
End If
targetType = arrayType.ElementType
If targetType.Kind = SymbolKind.ErrorType Then
Continue For
End If
For j As Integer = 0 To paramArrayItems.Count - 1 Step 1
If arguments(paramArrayItems(j)).HasErrors Then
Continue For
End If
RegisterArgument(arguments(paramArrayItems(j)), targetType, param)
Next
End If
Continue For
End If
argIndex = parameterToArgumentMap(paramIndex)
Dim argument = If(argIndex = -1, Nothing, arguments(argIndex))
If argument Is Nothing OrElse argument.HasErrors OrElse targetType.IsErrorType() OrElse argument.Kind = BoundKind.OmittedArgument Then
Continue For
End If
RegisterArgument(argument, targetType, param)
Next
AddDelegateReturnTypeToGraph()
End Sub
Private Sub AddDelegateReturnTypeToGraph()
If Me.DelegateReturnType IsNot Nothing AndAlso Not Me.DelegateReturnType.IsVoidType() Then
Dim fakeArgument As New BoundRValuePlaceholder(Me.DelegateReturnTypeReferenceBoundNode.Syntax,
Me.DelegateReturnType)
Dim returnNode As New ArgumentNode(Me, fakeArgument, Me.Candidate.ReturnType, parameter:=Nothing)
' Add the edges from all the current generic parameters to this named node.
For Each current As InferenceNode In Vertices
If current.NodeType = InferenceNodeType.TypeParameterNode Then
AddEdge(current, returnNode)
End If
Next
' Add the edges from the resultType outgoing to the generic parameters.
AddTypeToGraph(returnNode, isOutgoingEdge:=True)
End If
End Sub
Private Sub RegisterArgument(
argument As BoundExpression,
targetType As TypeSymbol,
param As ParameterSymbol
)
' Dig through parenthesized.
If Not argument.IsNothingLiteral Then
argument = argument.GetMostEnclosedParenthesizedExpression()
End If
Dim argNode As New ArgumentNode(Me, argument, targetType, param)
Select Case argument.Kind
Case BoundKind.UnboundLambda, BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda
AddLambdaToGraph(argNode, argument.GetBinderFromLambda())
Case BoundKind.AddressOfOperator
AddAddressOfToGraph(argNode, DirectCast(argument, BoundAddressOfOperator).Binder)
Case BoundKind.TupleLiteral
AddTupleLiteralToGraph(argNode)
Case Else
AddTypeToGraph(argNode, isOutgoingEdge:=True)
End Select
End Sub
Private Sub AddTypeToGraph(
node As ArgumentNode,
isOutgoingEdge As Boolean
)
AddTypeToGraph(node.ParameterType, node, isOutgoingEdge, BitVector.Create(_typeParameterNodes.Length))
End Sub
Private Function FindTypeParameterNode(typeParameter As TypeParameterSymbol) As TypeParameterNode
Dim ordinal As Integer = typeParameter.Ordinal
If ordinal < _typeParameterNodes.Length AndAlso
_typeParameterNodes(ordinal) IsNot Nothing AndAlso
typeParameter.Equals(_typeParameterNodes(ordinal).DeclaredTypeParam) Then
Return _typeParameterNodes(ordinal)
End If
Return Nothing
End Function
Private Sub AddTypeToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode,
isOutgoingEdge As Boolean,
ByRef haveSeenTypeParameters As BitVector
)
Select Case parameterType.Kind
Case SymbolKind.TypeParameter
Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol)
Dim typeParameterNode As TypeParameterNode = FindTypeParameterNode(typeParameter)
If typeParameterNode IsNot Nothing AndAlso
Not haveSeenTypeParameters(typeParameter.Ordinal) Then
If typeParameterNode.Parameter Is Nothing Then
typeParameterNode.SetParameter(argNode.Parameter)
End If
If (isOutgoingEdge) Then
AddEdge(argNode, typeParameterNode)
Else
AddEdge(typeParameterNode, argNode)
End If
haveSeenTypeParameters(typeParameter.Ordinal) = True
End If
Case SymbolKind.ArrayType
AddTypeToGraph(DirectCast(parameterType, ArrayTypeSymbol).ElementType, argNode, isOutgoingEdge, haveSeenTypeParameters)
Case SymbolKind.NamedType
Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol)
Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing
If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then
For Each elementType In elementTypes
AddTypeToGraph(elementType, argNode, isOutgoingEdge, haveSeenTypeParameters)
Next
Else
Do
For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
AddTypeToGraph(typeArgument, argNode, isOutgoingEdge, haveSeenTypeParameters)
Next
possiblyGenericType = possiblyGenericType.ContainingType
Loop While possiblyGenericType IsNot Nothing
End If
End Select
End Sub
Private Sub AddTupleLiteralToGraph(argNode As ArgumentNode)
AddTupleLiteralToGraph(argNode.ParameterType, argNode)
End Sub
Private Sub AddTupleLiteralToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode
)
Debug.Assert(argNode.Expression.Kind = BoundKind.TupleLiteral)
Dim tupleLiteral = DirectCast(argNode.Expression, BoundTupleLiteral)
Dim tupleArguments = tupleLiteral.Arguments
If parameterType.IsTupleOrCompatibleWithTupleOfCardinality(tupleArguments.Length) Then
Dim parameterElementTypes = parameterType.GetElementTypesOfTupleOrCompatible
For i As Integer = 0 To tupleArguments.Length - 1
RegisterArgument(tupleArguments(i), parameterElementTypes(i), argNode.Parameter)
Next
Return
End If
AddTypeToGraph(argNode, isOutgoingEdge:=True)
End Sub
Private Sub AddAddressOfToGraph(argNode As ArgumentNode, binder As Binder)
AddAddressOfToGraph(argNode.ParameterType, argNode, binder)
End Sub
Private Sub AddAddressOfToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode,
binder As Binder
)
Debug.Assert(argNode.Expression.Kind = BoundKind.AddressOfOperator)
If parameterType.IsTypeParameter() Then
AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length))
ElseIf parameterType.IsDelegateType() Then
Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol)
Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod
If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then
Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length)
AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) ' outgoing (name->type) edge
haveSeenTypeParameters.Clear()
For Each delegateParameter As ParameterSymbol In invoke.Parameters
AddTypeToGraph(delegateParameter.Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) ' incoming (type->name) edge
Next
End If
ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then
' If we've got an Expression(Of T), skip through to T
AddAddressOfToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder)
End If
End Sub
Private Sub AddLambdaToGraph(argNode As ArgumentNode, binder As Binder)
AddLambdaToGraph(argNode.ParameterType, argNode, binder)
End Sub
Private Sub AddLambdaToGraph(
parameterType As TypeSymbol,
argNode As ArgumentNode,
binder As Binder
)
If parameterType.IsTypeParameter() Then
' Lambda is bound to a generic typeParam, just infer anonymous delegate
AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length))
ElseIf parameterType.IsDelegateType() Then
Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol)
Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod
If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then
Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invoke.Parameters
Dim lambdaParameters As ImmutableArray(Of ParameterSymbol)
Select Case argNode.Expression.Kind
Case BoundKind.QueryLambda
lambdaParameters = DirectCast(argNode.Expression, BoundQueryLambda).LambdaSymbol.Parameters
Case BoundKind.GroupTypeInferenceLambda
lambdaParameters = DirectCast(argNode.Expression, GroupTypeInferenceLambda).Parameters
Case BoundKind.UnboundLambda
lambdaParameters = DirectCast(argNode.Expression, UnboundLambda).Parameters
Case Else
Throw ExceptionUtilities.UnexpectedValue(argNode.Expression.Kind)
End Select
Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length)
For i As Integer = 0 To Math.Min(delegateParameters.Length, lambdaParameters.Length) - 1 Step 1
If lambdaParameters(i).Type IsNot Nothing Then
' Prepopulate the hint from the lambda's parameter.
' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic
' !!! parameter will be passed into the parameter of argument type.
' TODO: Consider using location for the type declaration.
InferTypeArgumentsFromArgument(
argNode.Expression.Syntax,
lambdaParameters(i).Type,
argumentTypeByAssumption:=False,
parameterType:=delegateParameters(i).Type,
param:=delegateParameters(i),
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter,
inferenceRestrictions:=RequiredConversion.Any)
End If
AddTypeToGraph(delegateParameters(i).Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters)
Next
haveSeenTypeParameters.Clear()
AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters)
End If
ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then
' If we've got an Expression(Of T), skip through to T
AddLambdaToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder)
End If
End Sub
Private Shared Function ArgumentTypePossiblyMatchesParamarrayShape(argument As BoundExpression, paramType As TypeSymbol) As Boolean
Dim argumentType As TypeSymbol = argument.Type
Dim isArrayLiteral As Boolean = False
If argumentType Is Nothing Then
If argument.Kind = BoundKind.ArrayLiteral Then
isArrayLiteral = True
argumentType = DirectCast(argument, BoundArrayLiteral).InferredType
Else
Return False
End If
End If
While paramType.IsArrayType()
If Not argumentType.IsArrayType() Then
Return False
End If
Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol)
Dim paramArrayType = DirectCast(paramType, ArrayTypeSymbol)
' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches.
If argumentArray.Rank <> paramArrayType.Rank OrElse
(Not isArrayLiteral AndAlso argumentArray.IsSZArray <> paramArrayType.IsSZArray) Then
Return False
End If
isArrayLiteral = False
argumentType = argumentArray.ElementType
paramType = paramArrayType.ElementType
End While
Return True
End Function
Public Sub RegisterTypeParameterHint(
genericParameter As TypeParameterSymbol,
inferredType As TypeSymbol,
inferredTypeByAssumption As Boolean,
argumentLocation As SyntaxNode,
parameter As ParameterSymbol,
inferredFromObject As Boolean,
inferenceRestrictions As RequiredConversion
)
Dim typeNode As TypeParameterNode = FindTypeParameterNode(genericParameter)
If typeNode IsNot Nothing Then
typeNode.AddTypeHint(inferredType, inferredTypeByAssumption, argumentLocation, parameter, inferredFromObject, inferenceRestrictions)
End If
End Sub
Private Function RefersToGenericParameterToInferArgumentFor(
parameterType As TypeSymbol
) As Boolean
Select Case parameterType.Kind
Case SymbolKind.TypeParameter
Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol)
Dim typeNode As TypeParameterNode = FindTypeParameterNode(typeParameter)
' TODO: It looks like this check can give us a false positive. For example,
' if we are resolving a recursive call we might already bind a type
' parameter to itself (to the same type parameter of the containing method).
' So, the fact that we ran into this type parameter doesn't necessary mean
' that there is anything to infer. I am not sure if this can lead to some
' negative effect. Dev10 appears to have the same behavior, from what I see
' in the code.
If typeNode IsNot Nothing Then
Return True
End If
Case SymbolKind.ArrayType
Return RefersToGenericParameterToInferArgumentFor(DirectCast(parameterType, ArrayTypeSymbol).ElementType)
Case SymbolKind.NamedType
Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol)
Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing
If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then
For Each elementType In elementTypes
If RefersToGenericParameterToInferArgumentFor(elementType) Then
Return True
End If
Next
Else
Do
For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If RefersToGenericParameterToInferArgumentFor(typeArgument) Then
Return True
End If
Next
possiblyGenericType = possiblyGenericType.ContainingType
Loop While possiblyGenericType IsNot Nothing
End If
End Select
Return False
End Function
' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments
' to a generic method, infer type arguments corresponding to type parameters that occur
' in the parameter type.
'
' A return value of false indicates that inference fails.
'
' If a generic method is parameterized by T, an argument of type A matches a parameter of type
' P, this function tries to infer type for T by using these patterns:
'
' -- If P is T, then infer A for T
' -- If P is G(Of T) and A is G(Of X), then infer X for T
' -- If P is Array Of T, and A is Array Of X, then infer X for T
' -- If P is ByRef T, then infer A for T
Private Function InferTypeArgumentsFromArgumentDirectly(
argumentLocation As SyntaxNode,
argumentType As TypeSymbol,
argumentTypeByAssumption As Boolean,
parameterType As TypeSymbol,
param As ParameterSymbol,
digThroughToBasesAndImplements As MatchGenericArgumentToParameter,
inferenceRestrictions As RequiredConversion
) As Boolean
If argumentType Is Nothing OrElse argumentType.IsVoidType() Then
' We should never be able to infer a value from something that doesn't provide a value, e.g:
' Goo(Of T) can't be passed Sub bar(), as in Goo(Bar())
Return False
End If
' If a generic method is parameterized by T, an argument of type A matching a parameter of type
' P can be used to infer a type for T by these patterns:
'
' -- If P is T, then infer A for T
' -- If P is G(Of T) and A is G(Of X), then infer X for T
' -- If P is Array Of T, and A is Array Of X, then infer X for T
' -- If P is ByRef T, then infer A for T
' -- If P is (T, T) and A is (X, X), then infer X for T
If parameterType.IsTypeParameter() Then
RegisterTypeParameterHint(
DirectCast(parameterType, TypeParameterSymbol),
argumentType,
argumentTypeByAssumption,
argumentLocation,
param,
False,
inferenceRestrictions)
Return True
End If
Dim parameterElementTypes As ImmutableArray(Of TypeSymbol) = Nothing
Dim argumentElementTypes As ImmutableArray(Of TypeSymbol) = Nothing
If parameterType.GetNullableUnderlyingTypeOrSelf().TryGetElementTypesIfTupleOrCompatible(parameterElementTypes) AndAlso
If(parameterType.IsNullableType(), argumentType.GetNullableUnderlyingTypeOrSelf(), argumentType).
TryGetElementTypesIfTupleOrCompatible(argumentElementTypes) Then
If parameterElementTypes.Length <> argumentElementTypes.Length Then
Return False
End If
For typeArgumentIndex As Integer = 0 To parameterElementTypes.Length - 1
Dim parameterElementType = parameterElementTypes(typeArgumentIndex)
Dim argumentElementType = argumentElementTypes(typeArgumentIndex)
' propagate restrictions to the elements
If Not InferTypeArgumentsFromArgument(
argumentLocation,
argumentElementType,
argumentTypeByAssumption,
parameterElementType,
param,
digThroughToBasesAndImplements,
inferenceRestrictions
) Then
Return False
End If
Next
Return True
ElseIf parameterType.Kind = SymbolKind.NamedType Then
' e.g. handle goo(of T)(x as Bar(Of T)) We need to dig into Bar(Of T)
Dim parameterTypeAsNamedType = DirectCast(parameterType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol)
If parameterTypeAsNamedType.IsGenericType Then
Dim argumentTypeAsNamedType = If(argumentType.Kind = SymbolKind.NamedType, DirectCast(argumentType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol), Nothing)
If argumentTypeAsNamedType IsNot Nothing AndAlso argumentTypeAsNamedType.IsGenericType Then
If argumentTypeAsNamedType.OriginalDefinition.IsSameTypeIgnoringAll(parameterTypeAsNamedType.OriginalDefinition) Then
Do
For typeArgumentIndex As Integer = 0 To parameterTypeAsNamedType.Arity - 1 Step 1
' The following code is subtle. Let's recap what's going on...
' We've so far encountered some context, e.g. "_" or "ICovariant(_)"
' or "ByRef _" or the like. This context will have given us some TypeInferenceRestrictions.
' Now, inside the context, we've discovered a generic binding "G(Of _,_,_)"
' and we have to apply extra restrictions to each of those subcontexts.
' For non-variant parameters it's easy: the subcontexts just acquire the Identity constraint.
' For variant parameters it's more subtle. First, we have to strengthen the
' restrictions to require reference conversion (rather than just VB conversion or
' whatever it was). Second, if it was an In parameter, then we have to invert
' the sense.
'
' Processing of generics is tricky in the case that we've already encountered
' a "ByRef _". From that outer "ByRef _" we will have inferred the restriction
' "AnyConversionAndReverse", so that the argument could be copied into the parameter
' and back again. But now consider if we find a generic inside that ByRef, e.g.
' if it had been "ByRef x as G(Of T)" then what should we do? More specifically, consider a case
' "Sub f(Of T)(ByRef x as G(Of T))" invoked with some "dim arg as G(Of Hint)".
' What's needed for any candidate for T is that G(Of Hint) be convertible to
' G(Of Candidate), and vice versa for the copyback.
'
' But then what should we write down for the hints? The problem is that hints inhere
' to the generic parameter T, not to the function parameter G(Of T). So we opt for a
' safe approximation: we just require CLR identity between a candidate and the hint.
' This is safe but is a little overly-strict. For example:
' Class G(Of T)
' Public Shared Widening Operator CType(ByVal x As G(Of T)) As G(Of Animal)
' Public Shared Widening Operator CType(ByVal x As G(Of Animal)) As G(Of T)
' Sub inf(Of T)(ByRef x as G(Of T), ByVal y as T)
' ...
' inf(New G(Of Car), New Animal)
' inf(Of Animal)(New G(Of Car), New Animal)
' Then the hints will be "T:{Car=, Animal+}" and they'll result in inference-failure,
' even though the explicitly-provided T=Animal ends up working.
'
' Well, it's the best we can do without some major re-architecting of the way
' hints and type-inference works. That's because all our hints inhere to the
' type parameter T; in an ideal world, the ByRef hint would inhere to the parameter.
' But I don't think we'll ever do better than this, just because trying to do
' type inference inferring to arguments/parameters becomes exponential.
' Variance generic parameters will work the same.
' Dev10#595234: each Param'sInferenceRestriction is found as a modification of the surrounding InferenceRestriction:
Dim paramInferenceRestrictions As RequiredConversion
Select Case parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance
Case VarianceKind.In
paramInferenceRestrictions = Conversions.InvertConversionRequirement(
Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions))
Case VarianceKind.Out
paramInferenceRestrictions = Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions)
Case Else
Debug.Assert(VarianceKind.None = parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance)
paramInferenceRestrictions = RequiredConversion.Identity
End Select
Dim _DigThroughToBasesAndImplements As MatchGenericArgumentToParameter
If paramInferenceRestrictions = RequiredConversion.Reference Then
_DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter
ElseIf paramInferenceRestrictions = RequiredConversion.ReverseReference Then
_DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter
Else
_DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly
End If
If Not InferTypeArgumentsFromArgument(
argumentLocation,
argumentTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo),
argumentTypeByAssumption,
parameterTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo),
param,
_DigThroughToBasesAndImplements,
paramInferenceRestrictions
) Then
' TODO: Would it make sense to continue through other type arguments even if inference failed for
' the current one?
Return False
End If
Next
' Do not forget about type parameters of containing type
parameterTypeAsNamedType = parameterTypeAsNamedType.ContainingType
argumentTypeAsNamedType = argumentTypeAsNamedType.ContainingType
Loop While parameterTypeAsNamedType IsNot Nothing
Debug.Assert(parameterTypeAsNamedType Is Nothing AndAlso argumentTypeAsNamedType Is Nothing)
Return True
End If
ElseIf parameterTypeAsNamedType.IsNullableType() Then
' we reach here when the ParameterType is an instantiation of Nullable,
' and the argument type is NOT a generic type.
' lwischik: ??? what do array elements have to do with nullables?
Return InferTypeArgumentsFromArgument(
argumentLocation,
argumentType,
argumentTypeByAssumption,
parameterTypeAsNamedType.GetNullableUnderlyingType(),
param,
digThroughToBasesAndImplements,
Conversions.CombineConversionRequirements(inferenceRestrictions, RequiredConversion.ArrayElement))
End If
Return False
End If
ElseIf parameterType.IsArrayType() Then
If argumentType.IsArrayType() Then
Dim parameterArray = DirectCast(parameterType, ArrayTypeSymbol)
Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol)
Dim argumentIsAarrayLiteral = TypeOf argumentArray Is ArrayLiteralTypeSymbol
' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches.
If parameterArray.Rank = argumentArray.Rank AndAlso
(argumentIsAarrayLiteral OrElse parameterArray.IsSZArray = argumentArray.IsSZArray) Then
Return InferTypeArgumentsFromArgument(
argumentLocation,
argumentArray.ElementType,
argumentTypeByAssumption,
parameterArray.ElementType,
param,
digThroughToBasesAndImplements,
Conversions.CombineConversionRequirements(inferenceRestrictions, If(argumentIsAarrayLiteral, RequiredConversion.Any, RequiredConversion.ArrayElement)))
End If
End If
Return False
End If
Return True
End Function
' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments
' to a generic method, infer type arguments corresponding to type parameters that occur
' in the parameter type.
'
' A return value of false indicates that inference fails.
'
' This routine is given an argument e.g. "List(Of IEnumerable(Of Int))",
' and a parameter e.g. "IEnumerable(Of IEnumerable(Of T))".
' The task is to infer hints for T, e.g. "T=int".
' This function takes care of allowing (in this example) List(Of _) to match IEnumerable(Of _).
' As for the real work, i.e. matching the contents, we invoke "InferTypeArgumentsFromArgumentDirectly"
' to do that.
'
' Note: this function returns "false" if it failed to pattern-match between argument and parameter type,
' and "true" if it succeeded.
' Success in pattern-matching may or may not produce type-hints for generic parameters.
' If it happened not to produce any type-hints, then maybe other argument/parameter pairs will have produced
' their own type hints that allow inference to succeed, or maybe no-one else will have produced type hints,
' or maybe other people will have produced conflicting type hints. In those cases, we'd return True from
' here (to show success at pattern-matching) and leave the downstream code to produce an error message about
' failing to infer T.
Friend Function InferTypeArgumentsFromArgument(
argumentLocation As SyntaxNode,
argumentType As TypeSymbol,
argumentTypeByAssumption As Boolean,
parameterType As TypeSymbol,
param As ParameterSymbol,
digThroughToBasesAndImplements As MatchGenericArgumentToParameter,
inferenceRestrictions As RequiredConversion
) As Boolean
If Not RefersToGenericParameterToInferArgumentFor(parameterType) Then
Return True
End If
' First try to the things directly. Only if this fails will we bother searching for things like List->IEnumerable.
Dim Inferred As Boolean = InferTypeArgumentsFromArgumentDirectly(
argumentLocation,
argumentType,
argumentTypeByAssumption,
parameterType,
param,
digThroughToBasesAndImplements,
inferenceRestrictions)
If Inferred Then
Return True
End If
If parameterType.IsTypeParameter() Then
' If we failed to match an argument against a generic parameter T, it means that the
' argument was something unmatchable, e.g. an AddressOf.
Return False
End If
' If we didn't find a direct match, we will have to look in base classes for a match.
' We'll either fix ParameterType and look amongst the bases of ArgumentType,
' or we'll fix ArgumentType and look amongst the bases of ParameterType,
' depending on the "DigThroughToBasesAndImplements" flag. This flag is affected by
' covariance and contravariance...
If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly Then
Return False
End If
' Special handling for Anonymous Delegates.
If argumentType IsNot Nothing AndAlso argumentType.IsDelegateType() AndAlso parameterType.IsDelegateType() AndAlso
digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter AndAlso
(inferenceRestrictions = RequiredConversion.Any OrElse inferenceRestrictions = RequiredConversion.AnyReverse OrElse
inferenceRestrictions = RequiredConversion.AnyAndReverse) Then
Dim argumentDelegateType = DirectCast(argumentType, NamedTypeSymbol)
Dim argumentInvokeProc As MethodSymbol = argumentDelegateType.DelegateInvokeMethod
Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol)
Dim parameterInvokeProc As MethodSymbol = parameterDelegateType.DelegateInvokeMethod
Debug.Assert(argumentInvokeProc IsNot Nothing OrElse Not argumentDelegateType.IsAnonymousType)
' Note, null check for parameterInvokeDeclaration should also filter out MultiCastDelegate type.
If argumentDelegateType.IsAnonymousType AndAlso Not parameterDelegateType.IsAnonymousType AndAlso
parameterInvokeProc IsNot Nothing AndAlso parameterInvokeProc.GetUseSiteInfo().DiagnosticInfo Is Nothing Then
' Some trickery relating to the fact that anonymous delegates can be converted to any delegate type.
' We are trying to match the anonymous delegate "BaseSearchType" onto the delegate "FixedType". e.g.
' Dim f = function(i as integer) i // ArgumentType = VB$AnonymousDelegate`2(Of Integer,Integer)
' inf(f) // ParameterType might be e.g. D(Of T) for some function inf(Of T)(f as D(Of T))
' // maybe defined as Delegate Function D(Of T)(x as T) as T.
' We're looking to achieve the same functionality in pattern-matching these types as we already
' have for calling "inf(function(i as integer) i)" directly.
' It allows any VB conversion from param-of-fixed-type to param-of-base-type (not just reference conversions).
' But it does allow a zero-argument BaseSearchType to be used for a FixedType with more.
' And it does allow a function BaseSearchType to be used for a sub FixedType.
'
' Anyway, the plan is to match each of the parameters in the ArgumentType delegate
' to the equivalent parameters in the ParameterType delegate, and also match the return types.
'
' This only works for "ConversionRequired::Any", i.e. using VB conversion semantics. It doesn't work for
' reference conversions. As for the AnyReverse/AnyAndReverse, well, in Orcas that was guaranteed
' to fail type inference (i.e. return a false from this function). In Dev10 we will let it succeed
' with some inferred types, for the sake of better error messages, even though we know that ultimately
' it will fail (because no non-anonymous delegate type can be converted to a delegate type).
Dim argumentParams As ImmutableArray(Of ParameterSymbol) = argumentInvokeProc.Parameters
Dim parameterParams As ImmutableArray(Of ParameterSymbol) = parameterInvokeProc.Parameters
If parameterParams.Length <> argumentParams.Length AndAlso argumentParams.Length <> 0 Then
' If parameter-counts are mismatched then it's a failure.
' Exception: Zero-argument relaxation: we allow a parameterless VB$AnonymousDelegate argument
' to be supplied to a function which expects a parameterfull delegate.
Return False
End If
' First we'll check that the argument types all match.
For i As Integer = 0 To argumentParams.Length - 1
If argumentParams(i).IsByRef <> parameterParams(i).IsByRef Then
' Require an exact match between ByRef/ByVal, since that's how type inference of lambda expressions works.
Return False
End If
If Not InferTypeArgumentsFromArgument(
argumentLocation,
argumentParams(i).Type,
argumentTypeByAssumption,
parameterParams(i).Type,
param,
MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter,
RequiredConversion.AnyReverse) Then ' AnyReverse: contravariance in delegate arguments
Return False
End If
Next
' Now check that the return type matches.
' Note: we allow a *function* VB$AnonymousDelegate to be supplied to a function which expects a *sub* delegate.
If parameterInvokeProc.IsSub Then
' A *sub* delegate parameter can accept either a *function* or a *sub* argument:
Return True
ElseIf argumentInvokeProc.IsSub Then
' A *function* delegate parameter cannot accept a *sub* argument.
Return False
Else
' Otherwise, a function argument VB$AnonymousDelegate was supplied to a function parameter:
Return InferTypeArgumentsFromArgument(
argumentLocation,
argumentInvokeProc.ReturnType,
argumentTypeByAssumption,
parameterInvokeProc.ReturnType,
param,
MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
RequiredConversion.Any) ' Any: covariance in delegate returns
End If
End If
End If
' MatchBaseOfGenericArgumentToParameter: used for covariant situations,
' e.g. matching argument "List(Of _)" to parameter "ByVal x as IEnumerable(Of _)".
'
' Otherwise, MatchArgumentToBaseOfGenericParameter, used for contravariant situations,
' e.g. when matching argument "Action(Of IEnumerable(Of _))" to parameter "ByVal x as Action(Of List(Of _))".
Dim fContinue As Boolean = False
If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter Then
fContinue = FindMatchingBase(argumentType, parameterType)
Else
fContinue = FindMatchingBase(parameterType, argumentType)
End If
If Not fContinue Then
Return False
End If
' NOTE: baseSearchType was a REFERENCE, to either ArgumentType or ParameterType.
' Therefore the above statement has altered either ArgumentType or ParameterType.
Return InferTypeArgumentsFromArgumentDirectly(
argumentLocation,
argumentType,
argumentTypeByAssumption,
parameterType,
param,
digThroughToBasesAndImplements,
inferenceRestrictions)
End Function
Private Function FindMatchingBase(
ByRef baseSearchType As TypeSymbol,
ByRef fixedType As TypeSymbol
) As Boolean
Dim fixedTypeAsNamedType = If(fixedType.Kind = SymbolKind.NamedType, DirectCast(fixedType, NamedTypeSymbol), Nothing)
If fixedTypeAsNamedType Is Nothing OrElse Not fixedTypeAsNamedType.IsGenericType Then
' If the fixed candidate isn't a generic (e.g. matching argument IList(Of String) to non-generic parameter IList),
' then we won't learn anything about generic type parameters here:
Return False
End If
Dim fixedTypeTypeKind As TypeKind = fixedType.TypeKind
If fixedTypeTypeKind <> TypeKind.Class AndAlso fixedTypeTypeKind <> TypeKind.Interface Then
' Whatever "BaseSearchType" is, it can only inherit from "FixedType" if FixedType is a class/interface.
' (it's impossible to inherit from anything else).
Return False
End If
Dim baseSearchTypeKind As SymbolKind = baseSearchType.Kind
If baseSearchTypeKind <> SymbolKind.NamedType AndAlso baseSearchTypeKind <> SymbolKind.TypeParameter AndAlso
Not (baseSearchTypeKind = SymbolKind.ArrayType AndAlso DirectCast(baseSearchType, ArrayTypeSymbol).IsSZArray) Then
' The things listed above are the only ones that have bases that could ever lead anywhere useful.
' NamedType is satisfied by interfaces, structures, enums, delegates and modules as well as just classes.
Return False
End If
If baseSearchType.IsSameTypeIgnoringAll(fixedType) Then
' If the types checked were already identical, then exit
Return False
End If
' Otherwise, if we got through all the above tests, then it really is worth searching through the base
' types to see if that helps us find a match.
Dim matchingBase As TypeSymbol = Nothing
If fixedTypeTypeKind = TypeKind.Class Then
FindMatchingBaseClass(baseSearchType, fixedType, matchingBase)
Else
Debug.Assert(fixedTypeTypeKind = TypeKind.Interface)
FindMatchingBaseInterface(baseSearchType, fixedType, matchingBase)
End If
If matchingBase Is Nothing Then
Return False
End If
' And this is what we found
baseSearchType = matchingBase
Return True
End Function
Private Shared Function SetMatchIfNothingOrEqual(type As TypeSymbol, ByRef match As TypeSymbol) As Boolean
If match Is Nothing Then
match = type
Return True
ElseIf match.IsSameTypeIgnoringAll(type) Then
Return True
Else
match = Nothing
Return False
End If
End Function
''' <summary>
''' Returns False if the search should be cancelled.
''' </summary>
Private Function FindMatchingBaseInterface(derivedType As TypeSymbol, baseInterface As TypeSymbol, ByRef match As TypeSymbol) As Boolean
Select Case derivedType.Kind
Case SymbolKind.TypeParameter
For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual(constraint, match) Then
Return False
End If
End If
If Not FindMatchingBaseInterface(constraint, baseInterface, match) Then
Return False
End If
Next
Case Else
For Each [interface] In derivedType.AllInterfacesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If [interface].OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual([interface], match) Then
Return False
End If
End If
Next
End Select
Return True
End Function
''' <summary>
''' Returns False if the search should be cancelled.
''' </summary>
Private Function FindMatchingBaseClass(derivedType As TypeSymbol, baseClass As TypeSymbol, ByRef match As TypeSymbol) As Boolean
Select Case derivedType.Kind
Case SymbolKind.TypeParameter
For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual(constraint, match) Then
Return False
End If
End If
' TODO: Do we need to continue even if we already have a matching base class?
' It looks like Dev10 continues.
If Not FindMatchingBaseClass(constraint, baseClass, match) Then
Return False
End If
Next
Case Else
Dim baseType As NamedTypeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
While baseType IsNot Nothing
If baseType.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then
If Not SetMatchIfNothingOrEqual(baseType, match) Then
Return False
End If
Exit While
End If
baseType = baseType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo)
End While
End Select
Return True
End Function
Public Function InferTypeArgumentsFromAddressOfArgument(
argument As BoundExpression,
parameterType As TypeSymbol,
param As ParameterSymbol
) As Boolean
If parameterType.IsDelegateType() Then
Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterType), NamedTypeSymbol)
' Now find the invoke method of the delegate
Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod
If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then
' If we don't have an Invoke method, just bail.
Return False
End If
Dim returnType As TypeSymbol = invokeMethod.ReturnType
' If the return type doesn't refer to parameters, no inference required.
If Not RefersToGenericParameterToInferArgumentFor(returnType) Then
Return True
End If
Dim addrOf = DirectCast(argument, BoundAddressOfOperator)
Dim fromMethod As MethodSymbol = Nothing
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = Binder.ResolveMethodForDelegateInvokeFullAndRelaxed(
addrOf,
invokeMethod,
ignoreMethodReturnType:=True,
diagnostics:=BindingDiagnosticBag.Discarded)
fromMethod = matchingMethod.Key
methodConversions = matchingMethod.Value
If fromMethod Is Nothing OrElse (methodConversions And MethodConversionKind.AllErrorReasons) <> 0 OrElse
(addrOf.Binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=True)) Then
Return False
End If
If fromMethod.IsSub Then
ReportNotFailedInferenceDueToObject()
Return True
End If
Dim targetReturnType As TypeSymbol = fromMethod.ReturnType
If RefersToGenericParameterToInferArgumentFor(targetReturnType) Then
' Return false if we didn't make any inference progress.
Return False
End If
Return InferTypeArgumentsFromArgument(
argument.Syntax,
targetReturnType,
argumentTypeByAssumption:=False,
parameterType:=returnType,
param:=param,
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions:=RequiredConversion.Any)
End If
' We did not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference
' as not failed due to object.
ReportNotFailedInferenceDueToObject()
Return True
End Function
Public Function InferTypeArgumentsFromLambdaArgument(
argument As BoundExpression,
parameterType As TypeSymbol,
param As ParameterSymbol
) As Boolean
Debug.Assert(argument.Kind = BoundKind.UnboundLambda OrElse
argument.Kind = BoundKind.QueryLambda OrElse
argument.Kind = BoundKind.GroupTypeInferenceLambda)
If parameterType.IsTypeParameter() Then
Dim anonymousLambdaType As TypeSymbol = Nothing
Select Case argument.Kind
Case BoundKind.QueryLambda
' Do not infer Anonymous Delegate type from query lambda.
Case BoundKind.GroupTypeInferenceLambda
' Can't infer from this lambda.
Case BoundKind.UnboundLambda
' Infer Anonymous Delegate type from unbound lambda.
Dim inferredAnonymousDelegate As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = DirectCast(argument, UnboundLambda).InferredAnonymousDelegate
If (inferredAnonymousDelegate.Value.Diagnostics.IsDefault OrElse Not inferredAnonymousDelegate.Value.Diagnostics.HasAnyErrors()) Then
Dim delegateInvokeMethod As MethodSymbol = Nothing
If inferredAnonymousDelegate.Key IsNot Nothing Then
delegateInvokeMethod = inferredAnonymousDelegate.Key.DelegateInvokeMethod
End If
If delegateInvokeMethod IsNot Nothing AndAlso delegateInvokeMethod.ReturnType IsNot LambdaSymbol.ReturnTypeIsUnknown Then
anonymousLambdaType = inferredAnonymousDelegate.Key
End If
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
If anonymousLambdaType IsNot Nothing Then
Return InferTypeArgumentsFromArgument(
argument.Syntax,
anonymousLambdaType,
argumentTypeByAssumption:=False,
parameterType:=parameterType,
param:=param,
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions:=RequiredConversion.Any)
Else
Return True
End If
ElseIf parameterType.IsDelegateType() Then
Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol)
' First, we need to build a partial type substitution using the type of
' arguments as they stand right now, with some of them still being uninferred.
' TODO: Doesn't this make the inference algorithm order dependent? For example, if we were to
' infer more stuff from other non-lambda arguments, we might have a better chance to have
' more type information for the lambda, allowing successful lambda interpretation.
' Perhaps the graph doesn't allow us to get here until all "inputs" for lambda parameters
' are inferred.
Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterDelegateType), NamedTypeSymbol)
' Now find the invoke method of the delegate
Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod
If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then
' If we don't have an Invoke method, just bail.
Return True
End If
Dim returnType As TypeSymbol = invokeMethod.ReturnType
' If the return type doesn't refer to parameters, no inference required.
If Not RefersToGenericParameterToInferArgumentFor(returnType) Then
Return True
End If
Dim lambdaParams As ImmutableArray(Of ParameterSymbol)
Select Case argument.Kind
Case BoundKind.QueryLambda
lambdaParams = DirectCast(argument, BoundQueryLambda).LambdaSymbol.Parameters
Case BoundKind.GroupTypeInferenceLambda
lambdaParams = DirectCast(argument, GroupTypeInferenceLambda).Parameters
Case BoundKind.UnboundLambda
lambdaParams = DirectCast(argument, UnboundLambda).Parameters
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
Dim delegateParams As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters
If lambdaParams.Length > delegateParams.Length Then
Return True
End If
For i As Integer = 0 To lambdaParams.Length - 1 Step 1
Dim lambdaParam As ParameterSymbol = lambdaParams(i)
Dim delegateParam As ParameterSymbol = delegateParams(i)
If lambdaParam.Type Is Nothing Then
' If a lambda parameter has no type and the delegate parameter refers
' to an unbound generic parameter, we can't infer yet.
If RefersToGenericParameterToInferArgumentFor(delegateParam.Type) Then
' Skip this type argument and other parameters will infer it or
' if that doesn't happen it will report an error.
' TODO: Why does it make sense to continue here? It looks like we can infer something from
' lambda's return type based on incomplete information. Also, this 'if' is redundant,
' there is nothing left to do in this loop anyway, and "continue" doesn't change anything.
Continue For
End If
Else
' report the type of the lambda parameter to the delegate parameter.
' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic
' !!! parameter will be passed into the parameter of argument type.
InferTypeArgumentsFromArgument(
argument.Syntax,
lambdaParam.Type,
argumentTypeByAssumption:=False,
parameterType:=delegateParam.Type,
param:=param,
digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter,
inferenceRestrictions:=RequiredConversion.Any)
End If
Next
' OK, now try to infer delegates return type from the lambda.
Dim lambdaReturnType As TypeSymbol
Select Case argument.Kind
Case BoundKind.QueryLambda
Dim queryLambda = DirectCast(argument, BoundQueryLambda)
lambdaReturnType = queryLambda.LambdaSymbol.ReturnType
If lambdaReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then
lambdaReturnType = queryLambda.Expression.Type
If lambdaReturnType Is Nothing Then
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Debug.Assert(Me.Diagnostic IsNot Nothing)
lambdaReturnType = queryLambda.LambdaSymbol.ContainingBinder.MakeRValue(queryLambda.Expression, Me.Diagnostic).Type
End If
End If
Case BoundKind.GroupTypeInferenceLambda
lambdaReturnType = DirectCast(argument, GroupTypeInferenceLambda).InferLambdaReturnType(delegateParams)
Case BoundKind.UnboundLambda
Dim unboundLambda = DirectCast(argument, UnboundLambda)
If unboundLambda.IsFunctionLambda Then
Dim inferenceSignature As New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False)
Dim returnTypeInfo As KeyValuePair(Of TypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferReturnType(inferenceSignature)
If Not returnTypeInfo.Value.Diagnostics.IsDefault AndAlso returnTypeInfo.Value.Diagnostics.HasAnyErrors() Then
lambdaReturnType = Nothing
' Let's keep return type inference errors
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Me.Diagnostic.AddRange(returnTypeInfo.Value)
ElseIf returnTypeInfo.Key Is LambdaSymbol.ReturnTypeIsUnknown Then
lambdaReturnType = Nothing
Else
Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(inferenceSignature.ParameterTypes,
inferenceSignature.ParameterIsByRef,
returnTypeInfo.Key,
returnsByRef:=False))
Debug.Assert(boundLambda.LambdaSymbol.ReturnType Is returnTypeInfo.Key)
If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors Then
lambdaReturnType = returnTypeInfo.Key
' Let's keep return type inference warnings, if any.
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Me.Diagnostic.AddRange(returnTypeInfo.Value)
Me.Diagnostic.AddDependencies(boundLambda.Diagnostics.Dependencies)
Else
lambdaReturnType = Nothing
' Let's preserve diagnostics that caused the failure
If Not boundLambda.Diagnostics.Diagnostics.IsDefaultOrEmpty Then
If Me.Diagnostic Is Nothing Then
Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies)
End If
Me.Diagnostic.AddRange(boundLambda.Diagnostics)
End If
End If
End If
' But in the case of async/iterator lambdas, e.g. pass "Async Function() 1" to a parameter
' of type "Func(Of Task(Of T))" then we have to dig in further and match 1 to T...
If (unboundLambda.Flags And (SourceMemberFlags.Async Or SourceMemberFlags.Iterator)) <> 0 AndAlso
lambdaReturnType IsNot Nothing AndAlso lambdaReturnType.Kind = SymbolKind.NamedType AndAlso
returnType IsNot Nothing AndAlso returnType.Kind = SymbolKind.NamedType Then
' By this stage we know that
' * we have an async/iterator lambda argument
' * the parameter-to-match is a delegate type whose result type refers to generic parameters
' The parameter might be a delegate with result type e.g. "Task(Of T)" in which case we have
' to dig in. Or it might be a delegate with result type "T" in which case we
' don't dig in.
Dim lambdaReturnNamedType = DirectCast(lambdaReturnType, NamedTypeSymbol)
Dim returnNamedType = DirectCast(returnType, NamedTypeSymbol)
If lambdaReturnNamedType.Arity = 1 AndAlso
IsSameTypeIgnoringAll(lambdaReturnNamedType.OriginalDefinition,
returnNamedType.OriginalDefinition) Then
' We can assume that the lambda will have return type Task(Of T) or IEnumerable(Of T)
' or IEnumerator(Of T) as appropriate. That's already been ensured by the lambda-interpretation.
Debug.Assert(TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything) OrElse
TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T), TypeCompareKind.ConsiderEverything) OrElse
TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T), TypeCompareKind.ConsiderEverything))
lambdaReturnType = lambdaReturnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo)
returnType = returnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo)
End If
End If
Else
lambdaReturnType = Nothing
If Not invokeMethod.IsSub AndAlso (unboundLambda.Flags And SourceMemberFlags.Async) <> 0 Then
Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(delegateParams,
unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void),
returnsByRef:=False))
If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors() Then
If _asyncLambdaSubToFunctionMismatch Is Nothing Then
_asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance)
End If
_asyncLambdaSubToFunctionMismatch.Add(unboundLambda)
End If
End If
End If
Case Else
Throw ExceptionUtilities.UnexpectedValue(argument.Kind)
End Select
If lambdaReturnType Is Nothing Then
' Inference failed, give up.
Return False
End If
If lambdaReturnType.IsErrorType() Then
Return True
End If
' Now infer from the result type
' not ArgumentTypeByAssumption ??? lwischik: but maybe it should...
Return InferTypeArgumentsFromArgument(
argument.Syntax,
lambdaReturnType,
argumentTypeByAssumption:=False,
parameterType:=returnType,
param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter,
inferenceRestrictions:=RequiredConversion.Any)
ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then
' If we've got an Expression(Of T), skip through to T
Return InferTypeArgumentsFromLambdaArgument(argument, DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), param)
End If
Return True
End Function
Public Function ConstructParameterTypeIfNeeded(parameterType As TypeSymbol) As TypeSymbol
' First, we need to build a partial type substitution using the type of
' arguments as they stand right now, with some of them still being uninferred.
Dim methodSymbol As MethodSymbol = Candidate
Dim typeArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance(_typeParameterNodes.Length)
For i As Integer = 0 To _typeParameterNodes.Length - 1 Step 1
Dim typeNode As TypeParameterNode = _typeParameterNodes(i)
Dim newType As TypeSymbol
If typeNode Is Nothing OrElse typeNode.CandidateInferredType Is Nothing Then
'No substitution
newType = methodSymbol.TypeParameters(i)
Else
newType = typeNode.CandidateInferredType
End If
typeArguments.Add(New TypeWithModifiers(newType))
Next
Dim partialSubstitution = TypeSubstitution.CreateAdditionalMethodTypeParameterSubstitution(methodSymbol.ConstructedFrom, typeArguments.ToImmutableAndFree())
' Now we apply the partial substitution to the delegate type, leaving uninferred type parameters as is
Return parameterType.InternalSubstituteTypeParameters(partialSubstitution).Type
End Function
Public Sub ReportAmbiguousInferenceError(typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference))
Debug.Assert(typeInfos.Count() >= 2, "Must have at least 2 elements in the list")
' Since they get added fifo, we need to walk the list backward.
For i As Integer = 1 To typeInfos.Count - 1 Step 1
Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i)
If Not currentTypeInfo.InferredFromObject Then
ReportNotFailedInferenceDueToObject()
' TODO: Should we exit the loop? For some reason Dev10 keeps going.
End If
Next
End Sub
Public Sub ReportIncompatibleInferenceError(
typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference))
If typeInfos.Count < 1 Then
Return
End If
' Since they get added fifo, we need to walk the list backward.
For i As Integer = 1 To typeInfos.Count - 1 Step 1
Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i)
If Not currentTypeInfo.InferredFromObject Then
ReportNotFailedInferenceDueToObject()
' TODO: Should we exit the loop? For some reason Dev10 keeps going.
End If
Next
End Sub
Public Sub RegisterErrorReasons(inferenceErrorReasons As InferenceErrorReasons)
_inferenceErrorReasons = _inferenceErrorReasons Or inferenceErrorReasons
End Sub
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#if DEBUG
//#define CHECK_LOCALS // define CHECK_LOCALS to help debug some rewriting problems that would otherwise cause code-gen failures
#endif
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The rewriter for removing lambda expressions from method bodies and introducing closure classes
/// as containers for captured variables along the lines of the example in section 6.5.3 of the
/// C# language specification. A closure is the lowered form of a nested function, consisting of a
/// synthesized method and a set of environments containing the captured variables.
///
/// The entry point is the public method <see cref="Rewrite"/>. It operates as follows:
///
/// First, an analysis of the whole method body is performed that determines which variables are
/// captured, what their scopes are, and what the nesting relationship is between scopes that
/// have captured variables. The result of this analysis is left in <see cref="_analysis"/>.
///
/// Then we make a frame, or compiler-generated class, represented by an instance of
/// <see cref="SynthesizedClosureEnvironment"/> for each scope with captured variables. The generated frames are kept
/// in <see cref="_frames"/>. Each frame is given a single field for each captured
/// variable in the corresponding scope. These are maintained in <see cref="MethodToClassRewriter.proxies"/>.
///
/// Next, we walk and rewrite the input bound tree, keeping track of the following:
/// (1) The current set of active frame pointers, in <see cref="_framePointers"/>
/// (2) The current method being processed (this changes within a lambda's body), in <see cref="_currentMethod"/>
/// (3) The "this" symbol for the current method in <see cref="_currentFrameThis"/>, and
/// (4) The symbol that is used to access the innermost frame pointer (it could be a local variable or "this" parameter)
///
/// Lastly, we visit the top-level method and each of the lowered methods
/// to rewrite references (e.g., calls and delegate conversions) to local
/// functions. We visit references to local functions separately from
/// lambdas because we may see the reference before we lower the target
/// local function. Lambdas, on the other hand, are always convertible as
/// they are being lowered.
///
/// There are a few key transformations done in the rewriting.
/// (1) Lambda expressions are turned into delegate creation expressions, and the body of the lambda is
/// moved into a new, compiler-generated method of a selected frame class.
/// (2) On entry to a scope with captured variables, we create a frame object and store it in a local variable.
/// (3) References to captured variables are transformed into references to fields of a frame class.
///
/// In addition, the rewriting deposits into <see cref="TypeCompilationState.SynthesizedMethods"/>
/// a (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pair for each generated method.
///
/// <see cref="Rewrite"/> produces its output in two forms. First, it returns a new bound statement
/// for the caller to use for the body of the original method. Second, it returns a collection of
/// (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pairs for additional methods that the lambda rewriter produced.
/// These additional methods contain the bodies of the lambdas moved into ordinary methods of their
/// respective frame classes, and the caller is responsible for processing them just as it does with
/// the returned bound node. For example, the caller will typically perform iterator method and
/// asynchronous method transformations, and emit IL instructions into an assembly.
/// </summary>
internal sealed partial class ClosureConversion : MethodToClassRewriter
{
private readonly Analysis _analysis;
private readonly MethodSymbol _topLevelMethod;
private readonly MethodSymbol _substitutedSourceMethod;
private readonly int _topLevelMethodOrdinal;
// lambda frame for static lambdas.
// initialized lazily and could be null if there are no static lambdas
private SynthesizedClosureEnvironment _lazyStaticLambdaFrame;
// A mapping from every lambda parameter to its corresponding method's parameter.
private readonly Dictionary<ParameterSymbol, ParameterSymbol> _parameterMap = new Dictionary<ParameterSymbol, ParameterSymbol>();
// for each block with lifted (captured) variables, the corresponding frame type
private readonly Dictionary<BoundNode, Analysis.ClosureEnvironment> _frames = new Dictionary<BoundNode, Analysis.ClosureEnvironment>();
// the current set of frame pointers in scope. Each is either a local variable (where introduced),
// or the "this" parameter when at the top level. Keys in this map are never constructed types.
private readonly Dictionary<NamedTypeSymbol, Symbol> _framePointers = new Dictionary<NamedTypeSymbol, Symbol>();
// The set of original locals that should be assigned to proxies
// if lifted. This is useful for the expression evaluator where
// the original locals are left as is.
private readonly HashSet<LocalSymbol> _assignLocals;
// The current method or lambda being processed.
private MethodSymbol _currentMethod;
// The "this" symbol for the current method.
private ParameterSymbol _currentFrameThis;
private readonly ArrayBuilder<LambdaDebugInfo> _lambdaDebugInfoBuilder;
// ID dispenser for field names of frame references
private int _synthesizedFieldNameIdDispenser;
// The symbol (field or local) holding the innermost frame
private Symbol _innermostFramePointer;
// The mapping of type parameters for the current lambda body
private TypeMap _currentLambdaBodyTypeMap;
// The current set of type parameters (mapped from the enclosing method's type parameters)
private ImmutableArray<TypeParameterSymbol> _currentTypeParameters;
// Initialization for the proxy of the upper frame if it needs to be deferred.
// Such situation happens when lifting this in a ctor.
private BoundExpression _thisProxyInitDeferred;
// Set to true once we've seen the base (or self) constructor invocation in a constructor
private bool _seenBaseCall;
// Set to true while translating code inside of an expression lambda.
private bool _inExpressionLambda;
// When a lambda captures only 'this' of the enclosing method, we cache it in a local
// variable. This is the set of such local variables that must be added to the enclosing
// method's top-level block.
private ArrayBuilder<LocalSymbol> _addedLocals;
// Similarly, this is the set of statements that must be added to the enclosing method's
// top-level block initializing those variables to null.
private ArrayBuilder<BoundStatement> _addedStatements;
/// <summary>
/// Temporary bag for methods synthesized by the rewriting. Added to
/// <see cref="TypeCompilationState.SynthesizedMethods"/> at the end of rewriting.
/// </summary>
private ArrayBuilder<TypeCompilationState.MethodWithBody> _synthesizedMethods;
/// <summary>
/// TODO(https://github.com/dotnet/roslyn/projects/26): Delete this.
/// This should only be used by <see cref="NeedsProxy(Symbol)"/> which
/// hasn't had logic to move the proxy analysis into <see cref="Analysis"/>,
/// where the <see cref="Analysis.ScopeTree"/> could be walked to build
/// the proxy list.
/// </summary>
private readonly ImmutableHashSet<Symbol> _allCapturedVariables;
#nullable enable
private ClosureConversion(
Analysis analysis,
NamedTypeSymbol thisType,
ParameterSymbol thisParameterOpt,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
: base(slotAllocatorOpt, compilationState, diagnostics)
{
RoslynDebug.Assert(analysis != null);
RoslynDebug.Assert((object)thisType != null);
RoslynDebug.Assert(method != null);
RoslynDebug.Assert(compilationState != null);
RoslynDebug.Assert(diagnostics != null);
_topLevelMethod = method;
_substitutedSourceMethod = substitutedSourceMethod;
_topLevelMethodOrdinal = methodOrdinal;
_lambdaDebugInfoBuilder = lambdaDebugInfoBuilder;
_currentMethod = method;
_analysis = analysis;
_assignLocals = assignLocals;
_currentTypeParameters = method.TypeParameters;
_currentLambdaBodyTypeMap = TypeMap.Empty;
_innermostFramePointer = _currentFrameThis = thisParameterOpt;
_framePointers[thisType] = thisParameterOpt;
_seenBaseCall = method.MethodKind != MethodKind.Constructor; // only used for ctors
_synthesizedFieldNameIdDispenser = 1;
var allCapturedVars = ImmutableHashSet.CreateBuilder<Symbol>();
Analysis.VisitNestedFunctions(analysis.ScopeTree, (scope, function) =>
{
allCapturedVars.UnionWith(function.CapturedVariables);
});
_allCapturedVariables = allCapturedVars.ToImmutable();
}
#nullable disable
protected override bool NeedsProxy(Symbol localOrParameter)
{
Debug.Assert(localOrParameter is LocalSymbol || localOrParameter is ParameterSymbol ||
(localOrParameter as MethodSymbol)?.MethodKind == MethodKind.LocalFunction);
return _allCapturedVariables.Contains(localOrParameter);
}
/// <summary>
/// Rewrite the given node to eliminate lambda expressions. Also returned are the method symbols and their
/// bound bodies for the extracted lambda bodies. These would typically be emitted by the caller such as
/// MethodBodyCompiler. See this class' documentation
/// for a more thorough explanation of the algorithm and its use by clients.
/// </summary>
/// <param name="loweredBody">The bound node to be rewritten</param>
/// <param name="thisType">The type of the top-most frame</param>
/// <param name="thisParameter">The "this" parameter in the top-most frame, or null if static method</param>
/// <param name="method">The containing method of the node to be rewritten</param>
/// <param name="methodOrdinal">Index of the method symbol in its containing type member list.</param>
/// <param name="substitutedSourceMethod">If this is non-null, then <paramref name="method"/> will be treated as this for uses of parent symbols. For use in EE.</param>
/// <param name="lambdaDebugInfoBuilder">Information on lambdas defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="closureDebugInfoBuilder">Information on closures defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="slotAllocatorOpt">Slot allocator.</param>
/// <param name="compilationState">The caller's buffer into which we produce additional methods to be emitted by the caller</param>
/// <param name="diagnostics">Diagnostic bag for diagnostics</param>
/// <param name="assignLocals">The set of original locals that should be assigned to proxies if lifted</param>
public static BoundStatement Rewrite(
BoundStatement loweredBody,
NamedTypeSymbol thisType,
ParameterSymbol thisParameter,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
{
Debug.Assert((object)thisType != null);
Debug.Assert(((object)thisParameter == null) || (TypeSymbol.Equals(thisParameter.Type, thisType, TypeCompareKind.ConsiderEverything2)));
Debug.Assert(compilationState.ModuleBuilderOpt != null);
Debug.Assert(diagnostics.DiagnosticBag is object);
var analysis = Analysis.Analyze(
loweredBody,
method,
methodOrdinal,
substitutedSourceMethod,
slotAllocatorOpt,
compilationState,
closureDebugInfoBuilder,
diagnostics.DiagnosticBag);
CheckLocalsDefined(loweredBody);
var rewriter = new ClosureConversion(
analysis,
thisType,
thisParameter,
method,
methodOrdinal,
substitutedSourceMethod,
lambdaDebugInfoBuilder,
slotAllocatorOpt,
compilationState,
diagnostics,
assignLocals);
rewriter.SynthesizeClosureEnvironments(closureDebugInfoBuilder);
rewriter.SynthesizeClosureMethods();
var body = rewriter.AddStatementsIfNeeded(
(BoundStatement)rewriter.Visit(loweredBody));
// Add the completed methods to the compilation state
if (rewriter._synthesizedMethods != null)
{
if (compilationState.SynthesizedMethods == null)
{
compilationState.SynthesizedMethods = rewriter._synthesizedMethods;
}
else
{
compilationState.SynthesizedMethods.AddRange(rewriter._synthesizedMethods);
rewriter._synthesizedMethods.Free();
}
}
CheckLocalsDefined(body);
analysis.Free();
return body;
}
private BoundStatement AddStatementsIfNeeded(BoundStatement body)
{
if (_addedLocals != null)
{
_addedStatements.Add(body);
body = new BoundBlock(body.Syntax, _addedLocals.ToImmutableAndFree(), _addedStatements.ToImmutableAndFree()) { WasCompilerGenerated = true };
_addedLocals = null;
_addedStatements = null;
}
else
{
Debug.Assert(_addedStatements == null);
}
return body;
}
protected override TypeMap TypeMap
{
get { return _currentLambdaBodyTypeMap; }
}
protected override MethodSymbol CurrentMethod
{
get { return _currentMethod; }
}
protected override NamedTypeSymbol ContainingType
{
get { return _topLevelMethod.ContainingType; }
}
/// <summary>
/// Check that the top-level node is well-defined, in the sense that all
/// locals that are used are defined in some enclosing scope.
/// </summary>
static partial void CheckLocalsDefined(BoundNode node);
/// <summary>
/// Adds <see cref="SynthesizedClosureEnvironment"/> synthesized types to the compilation state
/// and creates hoisted fields for all locals captured by the environments.
/// </summary>
private void SynthesizeClosureEnvironments(ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
{
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment is { } env)
{
Debug.Assert(!_frames.ContainsKey(scope.BoundNode));
var frame = MakeFrame(scope, env);
env.SynthesizedEnvironment = frame;
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(ContainingType, frame.GetCciAdapter());
if (frame.Constructor != null)
{
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, Diagnostics),
frame.Constructor));
}
_frames.Add(scope.BoundNode, env);
}
});
SynthesizedClosureEnvironment MakeFrame(Analysis.Scope scope, Analysis.ClosureEnvironment env)
{
var scopeBoundNode = scope.BoundNode;
var syntax = scopeBoundNode.Syntax;
Debug.Assert(syntax != null);
DebugId methodId = _analysis.GetTopLevelMethodId();
DebugId closureId = _analysis.GetClosureId(syntax, closureDebugInfo);
var containingMethod = scope.ContainingFunctionOpt?.OriginalMethodSymbol ?? _topLevelMethod;
if ((object)_substitutedSourceMethod != null && containingMethod == _topLevelMethod)
{
containingMethod = _substitutedSourceMethod;
}
var synthesizedEnv = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
env.IsStruct,
syntax,
methodId,
closureId);
foreach (var captured in env.CapturedVariables)
{
Debug.Assert(!proxies.ContainsKey(captured));
var hoistedField = LambdaCapturedVariable.Create(synthesizedEnv, captured, ref _synthesizedFieldNameIdDispenser);
proxies.Add(captured, new CapturedToFrameSymbolReplacement(hoistedField, isReusable: false));
synthesizedEnv.AddHoistedField(hoistedField);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(synthesizedEnv, hoistedField.GetCciAdapter());
}
return synthesizedEnv;
}
}
/// <summary>
/// Synthesize closure methods for all nested functions.
/// </summary>
private void SynthesizeClosureMethods()
{
Analysis.VisitNestedFunctions(_analysis.ScopeTree, (scope, nestedFunction) =>
{
var originalMethod = nestedFunction.OriginalMethodSymbol;
var syntax = originalMethod.DeclaringSyntaxReferences[0].GetSyntax();
int closureOrdinal;
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
DebugId topLevelMethodId;
DebugId lambdaId;
if (nestedFunction.ContainingEnvironmentOpt != null)
{
containerAsFrame = nestedFunction.ContainingEnvironmentOpt.SynthesizedEnvironment;
closureKind = ClosureKind.General;
translatedLambdaContainer = containerAsFrame;
closureOrdinal = containerAsFrame.ClosureOrdinal;
}
else if (nestedFunction.CapturesThis)
{
containerAsFrame = null;
translatedLambdaContainer = _topLevelMethod.ContainingType;
closureKind = ClosureKind.ThisOnly;
closureOrdinal = LambdaDebugInfo.ThisOnlyClosureOrdinal;
}
else if ((nestedFunction.CapturedEnvironments.Count == 0 &&
originalMethod.MethodKind == MethodKind.LambdaMethod &&
_analysis.MethodsConvertedToDelegates.Contains(originalMethod)) ||
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is object)
{
translatedLambdaContainer = containerAsFrame = GetStaticFrame(Diagnostics, syntax);
closureKind = ClosureKind.Singleton;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
else
{
// Lower directly onto the containing type
translatedLambdaContainer = _topLevelMethod.ContainingType;
containerAsFrame = null;
closureKind = ClosureKind.Static;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
Debug.Assert((object)translatedLambdaContainer != _topLevelMethod.ContainingType ||
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null);
// Move the body of the lambda to a freshly generated synthetic method on its frame.
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = GetLambdaId(syntax, closureKind, closureOrdinal);
var synthesizedMethod = new SynthesizedClosureMethod(
translatedLambdaContainer,
getStructEnvironments(nestedFunction),
closureKind,
_topLevelMethod,
topLevelMethodId,
originalMethod,
nestedFunction.BlockSyntax,
lambdaId,
CompilationState);
nestedFunction.SynthesizedLoweredMethod = synthesizedMethod;
});
static ImmutableArray<SynthesizedClosureEnvironment> getStructEnvironments(Analysis.NestedFunction function)
{
var environments = ArrayBuilder<SynthesizedClosureEnvironment>.GetInstance();
foreach (var env in function.CapturedEnvironments)
{
if (env.IsStruct)
{
environments.Add(env.SynthesizedEnvironment);
}
}
return environments.ToImmutableAndFree();
}
}
/// <summary>
/// Get the static container for closures or create one if one doesn't already exist.
/// </summary>
/// <param name="syntax">
/// associate the frame with the first lambda that caused it to exist.
/// we need to associate this with some syntax.
/// unfortunately either containing method or containing class could be synthetic
/// therefore could have no syntax.
/// </param>
private SynthesizedClosureEnvironment GetStaticFrame(BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
if ((object)_lazyStaticLambdaFrame == null)
{
var isNonGeneric = !_topLevelMethod.IsGenericMethod;
if (isNonGeneric)
{
_lazyStaticLambdaFrame = CompilationState.StaticLambdaFrame;
}
if ((object)_lazyStaticLambdaFrame == null)
{
DebugId methodId;
if (isNonGeneric)
{
methodId = new DebugId(DebugId.UndefinedOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
else
{
methodId = _analysis.GetTopLevelMethodId();
}
DebugId closureId = default(DebugId);
// using _topLevelMethod as containing member because the static frame does not have generic parameters, except for the top level method's
var containingMethod = isNonGeneric ? null : (_substitutedSourceMethod ?? _topLevelMethod);
_lazyStaticLambdaFrame = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
isStruct: false,
scopeSyntaxOpt: null,
methodId: methodId,
closureId: closureId);
// non-generic static lambdas can share the frame
if (isNonGeneric)
{
CompilationState.StaticLambdaFrame = _lazyStaticLambdaFrame;
}
var frame = _lazyStaticLambdaFrame;
// add frame type and cache field
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(this.ContainingType, frame.GetCciAdapter());
// add its ctor (note Constructor can be null if TypeKind.Struct is passed in to LambdaFrame.ctor, but Class is passed in above)
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, diagnostics),
frame.Constructor));
// add cctor
// Frame.inst = new Frame()
var F = new SyntheticBoundNodeFactory(frame.StaticConstructor, syntax, CompilationState, diagnostics);
var body = F.Block(
F.Assignment(
F.Field(null, frame.SingletonCache),
F.New(frame.Constructor)),
new BoundReturnStatement(syntax, RefKind.None, null));
AddSynthesizedMethod(frame.StaticConstructor, body);
}
}
return _lazyStaticLambdaFrame;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame type.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameType">The type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
private BoundExpression FrameOfType(SyntaxNode syntax, NamedTypeSymbol frameType)
{
BoundExpression result = FramePointer(syntax, frameType.OriginalDefinition);
Debug.Assert(TypeSymbol.Equals(result.Type, frameType, TypeCompareKind.ConsiderEverything2));
return result;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame class.
/// Note that for generic frames, the frameClass parameter is the generic definition, but
/// the resulting expression will be constructed with the current type parameters.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameClass">The class type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
protected override BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass)
{
Debug.Assert(frameClass.IsDefinition);
// If in an instance method of the right type, we can just return the "this" pointer.
if ((object)_currentFrameThis != null && TypeSymbol.Equals(_currentFrameThis.Type, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundThisReference(syntax, frameClass);
}
// If the current method has by-ref struct closure parameters, and one of them is correct, use it.
var lambda = _currentMethod as SynthesizedClosureMethod;
if (lambda != null)
{
var start = lambda.ParameterCount - lambda.ExtraSynthesizedParameterCount;
for (var i = start; i < lambda.ParameterCount; i++)
{
var potentialParameter = lambda.Parameters[i];
if (TypeSymbol.Equals(potentialParameter.Type.OriginalDefinition, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundParameter(syntax, potentialParameter);
}
}
}
// Otherwise we need to return the value from a frame pointer local variable...
Symbol framePointer = _framePointers[frameClass];
CapturedSymbolReplacement proxyField;
if (proxies.TryGetValue(framePointer, out proxyField))
{
// However, frame pointer local variables themselves can be "captured". In that case
// the inner frames contain pointers to the enclosing frames. That is, nested
// frame pointers are organized in a linked list.
return proxyField.Replacement(syntax, frameType => FramePointer(syntax, frameType));
}
var localFrame = (LocalSymbol)framePointer;
return new BoundLocal(syntax, localFrame, null, localFrame.Type);
}
private static void InsertAndFreePrologue<T>(ArrayBuilder<BoundStatement> result, ArrayBuilder<T> prologue) where T : BoundNode
{
foreach (var node in prologue)
{
if (node is BoundStatement stmt)
{
result.Add(stmt);
}
else
{
result.Add(new BoundExpressionStatement(node.Syntax, (BoundExpression)(BoundNode)node));
}
}
prologue.Free();
}
/// <summary>
/// Introduce a frame around the translation of the given node.
/// </summary>
/// <param name="node">The node whose translation should be translated to contain a frame</param>
/// <param name="env">The environment for the translated node</param>
/// <param name="F">A function that computes the translation of the node. It receives lists of added statements and added symbols</param>
/// <returns>The translated statement, as returned from F</returns>
private BoundNode IntroduceFrame(BoundNode node, Analysis.ClosureEnvironment env, Func<ArrayBuilder<BoundExpression>, ArrayBuilder<LocalSymbol>, BoundNode> F)
{
var frame = env.SynthesizedEnvironment;
var frameTypeParameters = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, frame.Arity);
NamedTypeSymbol frameType = frame.ConstructIfGeneric(frameTypeParameters);
Debug.Assert(frame.ScopeSyntaxOpt != null);
LocalSymbol framePointer = new SynthesizedLocal(_topLevelMethod, TypeWithAnnotations.Create(frameType), SynthesizedLocalKind.LambdaDisplayClass, frame.ScopeSyntaxOpt);
SyntaxNode syntax = node.Syntax;
// assign new frame to the frame variable
var prologue = ArrayBuilder<BoundExpression>.GetInstance();
if ((object)frame.Constructor != null)
{
MethodSymbol constructor = frame.Constructor.AsMember(frameType);
Debug.Assert(TypeSymbol.Equals(frameType, constructor.ContainingType, TypeCompareKind.ConsiderEverything2));
prologue.Add(new BoundAssignmentOperator(syntax,
new BoundLocal(syntax, framePointer, null, frameType),
new BoundObjectCreationExpression(syntax: syntax, constructor: constructor),
frameType));
}
CapturedSymbolReplacement oldInnermostFrameProxy = null;
if ((object)_innermostFramePointer != null)
{
proxies.TryGetValue(_innermostFramePointer, out oldInnermostFrameProxy);
if (env.CapturesParent)
{
var capturedFrame = LambdaCapturedVariable.Create(frame, _innermostFramePointer, ref _synthesizedFieldNameIdDispenser);
FieldSymbol frameParent = capturedFrame.AsMember(frameType);
BoundExpression left = new BoundFieldAccess(syntax, new BoundLocal(syntax, framePointer, null, frameType), frameParent, null);
BoundExpression right = FrameOfType(syntax, frameParent.Type as NamedTypeSymbol);
BoundExpression assignment = new BoundAssignmentOperator(syntax, left, right, left.Type);
prologue.Add(assignment);
if (CompilationState.Emitting)
{
Debug.Assert(capturedFrame.Type.IsReferenceType); // Make sure we're not accidentally capturing a struct by value
frame.AddHoistedField(capturedFrame);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, capturedFrame.GetCciAdapter());
}
proxies[_innermostFramePointer] = new CapturedToFrameSymbolReplacement(capturedFrame, isReusable: false);
}
}
// Capture any parameters of this block. This would typically occur
// at the top level of a method or lambda with captured parameters.
foreach (var variable in env.CapturedVariables)
{
InitVariableProxy(syntax, variable, framePointer, prologue);
}
Symbol oldInnermostFramePointer = _innermostFramePointer;
if (!framePointer.Type.IsValueType)
{
_innermostFramePointer = framePointer;
}
var addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
addedLocals.Add(framePointer);
_framePointers.Add(frame, framePointer);
var result = F(prologue, addedLocals);
_innermostFramePointer = oldInnermostFramePointer;
if ((object)_innermostFramePointer != null)
{
if (oldInnermostFrameProxy != null)
{
proxies[_innermostFramePointer] = oldInnermostFrameProxy;
}
else
{
proxies.Remove(_innermostFramePointer);
}
}
return result;
}
private void InitVariableProxy(SyntaxNode syntax, Symbol symbol, LocalSymbol framePointer, ArrayBuilder<BoundExpression> prologue)
{
CapturedSymbolReplacement proxy;
if (proxies.TryGetValue(symbol, out proxy))
{
BoundExpression value;
switch (symbol.Kind)
{
case SymbolKind.Parameter:
var parameter = (ParameterSymbol)symbol;
ParameterSymbol parameterToUse;
if (!_parameterMap.TryGetValue(parameter, out parameterToUse))
{
parameterToUse = parameter;
}
value = new BoundParameter(syntax, parameterToUse);
break;
case SymbolKind.Local:
var local = (LocalSymbol)symbol;
if (_assignLocals == null || !_assignLocals.Contains(local))
{
return;
}
LocalSymbol localToUse;
if (!localMap.TryGetValue(local, out localToUse))
{
localToUse = local;
}
value = new BoundLocal(syntax, localToUse, null, localToUse.Type);
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
var left = proxy.Replacement(syntax, frameType1 => new BoundLocal(syntax, framePointer, null, framePointer.Type));
var assignToProxy = new BoundAssignmentOperator(syntax, left, value, value.Type);
if (_currentMethod.MethodKind == MethodKind.Constructor &&
symbol == _currentMethod.ThisParameter &&
!_seenBaseCall)
{
// Containing method is a constructor
// Initialization statement for the "this" proxy must be inserted
// after the constructor initializer statement block
Debug.Assert(_thisProxyInitDeferred == null);
_thisProxyInitDeferred = assignToProxy;
}
else
{
prologue.Add(assignToProxy);
}
}
}
#region Visit Methods
protected override BoundNode VisitUnhoistedParameter(BoundParameter node)
{
ParameterSymbol replacementParameter;
if (_parameterMap.TryGetValue(node.ParameterSymbol, out replacementParameter))
{
return new BoundParameter(node.Syntax, replacementParameter, node.HasErrors);
}
return base.VisitUnhoistedParameter(node);
}
public override BoundNode VisitThisReference(BoundThisReference node)
{
// "topLevelMethod.ThisParameter == null" can occur in a delegate creation expression because the method group
// in the argument can have a "this" receiver even when "this"
// is not captured because a static method is selected. But we do preserve
// the method group and its receiver in the bound tree.
// No need to capture "this" in such case.
// TODO: Why don't we drop "this" while lowering if method is static?
// Actually, considering that method group expression does not evaluate to a particular value
// why do we have it in the lowered tree at all?
return (_currentMethod == _topLevelMethod || _topLevelMethod.ThisParameter == null ?
node :
FramePointer(node.Syntax, (NamedTypeSymbol)node.Type));
}
public override BoundNode VisitBaseReference(BoundBaseReference node)
{
return (!_currentMethod.IsStatic && TypeSymbol.Equals(_currentMethod.ContainingType, _topLevelMethod.ContainingType, TypeCompareKind.ConsiderEverything2))
? node
: FramePointer(node.Syntax, _topLevelMethod.ContainingType); // technically, not the correct static type
}
/// <summary>
/// Rewrites a reference to an unlowered local function to the newly
/// lowered local function.
/// </summary>
private void RemapLocalFunction(
SyntaxNode syntax,
MethodSymbol localFunc,
out BoundExpression receiver,
out MethodSymbol method,
ref ImmutableArray<BoundExpression> arguments,
ref ImmutableArray<RefKind> argRefKinds)
{
Debug.Assert(localFunc.MethodKind == MethodKind.LocalFunction);
var function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, localFunc.OriginalDefinition);
var loweredSymbol = function.SynthesizedLoweredMethod;
// If the local function captured variables then they will be stored
// in frames and the frames need to be passed as extra parameters.
var frameCount = loweredSymbol.ExtraSynthesizedParameterCount;
if (frameCount != 0)
{
Debug.Assert(!arguments.IsDefault);
// Build a new list of arguments to pass to the local function
// call that includes any necessary capture frames
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(loweredSymbol.ParameterCount);
argumentsBuilder.AddRange(arguments);
var start = loweredSymbol.ParameterCount - frameCount;
for (int i = start; i < loweredSymbol.ParameterCount; i++)
{
// will always be a LambdaFrame, it's always a capture frame
var frameType = (NamedTypeSymbol)loweredSymbol.Parameters[i].Type.OriginalDefinition;
Debug.Assert(frameType is SynthesizedClosureEnvironment);
if (frameType.Arity > 0)
{
var typeParameters = ((SynthesizedClosureEnvironment)frameType).ConstructedFromTypeParameters;
Debug.Assert(typeParameters.Length == frameType.Arity);
var subst = this.TypeMap.SubstituteTypeParameters(typeParameters);
frameType = frameType.Construct(subst);
}
var frame = FrameOfType(syntax, frameType);
argumentsBuilder.Add(frame);
}
// frame arguments are passed by ref
// add corresponding refkinds
var refkindsBuilder = ArrayBuilder<RefKind>.GetInstance(argumentsBuilder.Count);
if (!argRefKinds.IsDefault)
{
refkindsBuilder.AddRange(argRefKinds);
}
else
{
refkindsBuilder.AddMany(RefKind.None, arguments.Length);
}
refkindsBuilder.AddMany(RefKind.Ref, frameCount);
arguments = argumentsBuilder.ToImmutableAndFree();
argRefKinds = refkindsBuilder.ToImmutableAndFree();
}
method = loweredSymbol;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(syntax,
localFunc,
SubstituteTypeArguments(localFunc.TypeArgumentsWithAnnotations),
loweredSymbol.ClosureKind,
ref method,
out receiver,
out constructedFrame);
}
/// <summary>
/// Substitutes references from old type arguments to new type arguments
/// in the lowered methods.
/// </summary>
/// <example>
/// Consider the following method:
/// void M() {
/// void L<T>(T t) => Console.Write(t);
/// L("A");
/// }
///
/// In this example, L<T> is a local function that will be
/// lowered into its own method and the type parameter T will be
/// alpha renamed to something else (let's call it T'). In this case,
/// all references to the original type parameter T in L must be
/// rewritten to the renamed parameter, T'.
/// </example>
private ImmutableArray<TypeWithAnnotations> SubstituteTypeArguments(ImmutableArray<TypeWithAnnotations> typeArguments)
{
Debug.Assert(!typeArguments.IsDefault);
if (typeArguments.IsEmpty)
{
return typeArguments;
}
// We must perform this process repeatedly as local
// functions may nest inside one another and capture type
// parameters from the enclosing local functions. Each
// iteration of nesting will cause alpha-renaming of the captured
// parameters, meaning that we must replace until there are no
// more alpha-rename mappings.
//
// The method symbol references are different from all other
// substituted types in this context because the method symbol in
// local function references is not rewritten until all local
// functions have already been lowered. Everything else is rewritten
// by the visitors as the definition is lowered. This means that
// only one substitution happens per lowering, but we need to do
// N substitutions all at once, where N is the number of lowerings.
var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArguments.Length);
foreach (var typeArg in typeArguments)
{
TypeWithAnnotations oldTypeArg;
TypeWithAnnotations newTypeArg = typeArg;
do
{
oldTypeArg = newTypeArg;
newTypeArg = this.TypeMap.SubstituteType(oldTypeArg);
}
while (!TypeSymbol.Equals(oldTypeArg.Type, newTypeArg.Type, TypeCompareKind.ConsiderEverything));
// When type substitution does not change the type, it is expected to return the very same object.
// Therefore the loop is terminated when that type (as an object) does not change.
Debug.Assert((object)oldTypeArg.Type == newTypeArg.Type);
// The types are the same, so the last pass performed no substitutions.
// Therefore the annotations ought to be the same too.
Debug.Assert(oldTypeArg.NullableAnnotation == newTypeArg.NullableAnnotation);
builder.Add(newTypeArg);
}
return builder.ToImmutableAndFree();
}
private void RemapLambdaOrLocalFunction(
SyntaxNode syntax,
MethodSymbol originalMethod,
ImmutableArray<TypeWithAnnotations> typeArgumentsOpt,
ClosureKind closureKind,
ref MethodSymbol synthesizedMethod,
out BoundExpression receiver,
out NamedTypeSymbol constructedFrame)
{
var translatedLambdaContainer = synthesizedMethod.ContainingType;
var containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
// All of _currentTypeParameters might not be preserved here due to recursively calling upwards in the chain of local functions/lambdas
Debug.Assert((typeArgumentsOpt.IsDefault && !originalMethod.IsGenericMethod) || (typeArgumentsOpt.Length == originalMethod.Arity));
var totalTypeArgumentCount = (containerAsFrame?.Arity ?? 0) + synthesizedMethod.Arity;
var realTypeArguments = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, totalTypeArgumentCount - originalMethod.Arity);
if (!typeArgumentsOpt.IsDefault)
{
realTypeArguments = realTypeArguments.Concat(typeArgumentsOpt);
}
if ((object)containerAsFrame != null && containerAsFrame.Arity != 0)
{
var containerTypeArguments = ImmutableArray.Create(realTypeArguments, 0, containerAsFrame.Arity);
realTypeArguments = ImmutableArray.Create(realTypeArguments, containerAsFrame.Arity, realTypeArguments.Length - containerAsFrame.Arity);
constructedFrame = containerAsFrame.Construct(containerTypeArguments);
}
else
{
constructedFrame = translatedLambdaContainer;
}
synthesizedMethod = synthesizedMethod.AsMember(constructedFrame);
if (synthesizedMethod.IsGenericMethod)
{
synthesizedMethod = synthesizedMethod.Construct(realTypeArguments);
}
else
{
Debug.Assert(realTypeArguments.Length == 0);
}
// for instance lambdas, receiver is the frame
// for static lambdas, get the singleton receiver
if (closureKind == ClosureKind.Singleton)
{
var field = containerAsFrame.SingletonCache.AsMember(constructedFrame);
receiver = new BoundFieldAccess(syntax, null, field, constantValueOpt: null);
}
else if (closureKind == ClosureKind.Static)
{
receiver = new BoundTypeExpression(syntax, null, synthesizedMethod.ContainingType);
}
else // ThisOnly and General
{
receiver = FrameOfType(syntax, constructedFrame);
}
}
public override BoundNode VisitCall(BoundCall node)
{
if (node.Method.MethodKind == MethodKind.LocalFunction)
{
var args = VisitList(node.Arguments);
var argRefKinds = node.ArgumentRefKindsOpt;
var type = VisitType(node.Type);
Debug.Assert(node.ArgsToParamsOpt.IsDefault, "should be done with argument reordering by now");
RemapLocalFunction(
node.Syntax,
node.Method,
out var receiver,
out var method,
ref args,
ref argRefKinds);
return node.Update(
receiver,
method,
args,
node.ArgumentNamesOpt,
argRefKinds,
node.IsDelegateCall,
node.Expanded,
node.InvokedAsExtensionMethod,
node.ArgsToParamsOpt,
node.DefaultArguments,
node.ResultKind,
type);
}
var visited = base.VisitCall(node);
if (visited.Kind != BoundKind.Call)
{
return visited;
}
var rewritten = (BoundCall)visited;
// Check if we need to init the 'this' proxy in a ctor call
if (!_seenBaseCall)
{
if (_currentMethod == _topLevelMethod && node.IsConstructorInitializer())
{
_seenBaseCall = true;
if (_thisProxyInitDeferred != null)
{
// Insert the this proxy assignment after the ctor call.
// Create bound sequence: { ctor call, thisProxyInitDeferred }
return new BoundSequence(
syntax: node.Syntax,
locals: ImmutableArray<LocalSymbol>.Empty,
sideEffects: ImmutableArray.Create<BoundExpression>(rewritten),
value: _thisProxyInitDeferred,
type: rewritten.Type);
}
}
}
return rewritten;
}
private BoundSequence RewriteSequence(BoundSequence node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
foreach (var effect in node.SideEffects)
{
var replacement = (BoundExpression)this.Visit(effect);
if (replacement != null) prologue.Add(replacement);
}
var newValue = (BoundExpression)this.Visit(node.Value);
var newType = this.VisitType(node.Type);
return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), newValue, newType);
}
public override BoundNode VisitBlock(BoundBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
RewriteBlock(node, prologue, newLocals));
}
else
{
return RewriteBlock(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
if (prologue.Count > 0)
{
newStatements.Add(BoundSequencePoint.CreateHidden());
}
InsertAndFreePrologue(newStatements, prologue);
foreach (var statement in node.Statements)
{
var replacement = (BoundStatement)this.Visit(statement);
if (replacement != null)
{
newStatements.Add(replacement);
}
}
// TODO: we may not need to update if there was nothing to rewrite.
return node.Update(newLocals.ToImmutableAndFree(), node.LocalFunctions, newStatements.ToImmutableAndFree());
}
public override BoundNode VisitScope(BoundScope node)
{
Debug.Assert(!node.Locals.IsEmpty);
var newLocals = ArrayBuilder<LocalSymbol>.GetInstance();
RewriteLocals(node.Locals, newLocals);
var statements = VisitList(node.Statements);
if (newLocals.Count == 0)
{
newLocals.Free();
return new BoundStatementList(node.Syntax, statements);
}
return node.Update(newLocals.ToImmutableAndFree(), statements);
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteCatch(node, prologue, newLocals);
});
}
else
{
return RewriteCatch(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundNode RewriteCatch(BoundCatchBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var rewrittenCatchLocals = newLocals.ToImmutableAndFree();
// If exception variable got lifted, IntroduceFrame will give us frame init prologue.
// It needs to run before the exception variable is accessed.
// To ensure that, we will make exception variable a sequence that performs prologue as its side-effects.
BoundExpression rewrittenExceptionSource = null;
var rewrittenFilterPrologue = (BoundStatementList)this.Visit(node.ExceptionFilterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(node.ExceptionFilterOpt);
if (node.ExceptionSourceOpt != null)
{
rewrittenExceptionSource = (BoundExpression)Visit(node.ExceptionSourceOpt);
if (prologue.Count > 0)
{
rewrittenExceptionSource = new BoundSequence(
rewrittenExceptionSource.Syntax,
ImmutableArray.Create<LocalSymbol>(),
prologue.ToImmutable(),
rewrittenExceptionSource,
rewrittenExceptionSource.Type);
}
}
else if (prologue.Count > 0)
{
Debug.Assert(rewrittenFilter != null);
var prologueBuilder = ArrayBuilder<BoundStatement>.GetInstance(prologue.Count);
foreach (var p in prologue)
{
prologueBuilder.Add(new BoundExpressionStatement(p.Syntax, p) { WasCompilerGenerated = true });
}
if (rewrittenFilterPrologue != null)
{
prologueBuilder.AddRange(rewrittenFilterPrologue.Statements);
}
rewrittenFilterPrologue = new BoundStatementList(rewrittenFilter.Syntax, prologueBuilder.ToImmutableAndFree());
}
// done with this.
prologue.Free();
// rewrite filter and body
// NOTE: this will proxy all accesses to exception local if that got lifted.
var exceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
var rewrittenBlock = (BoundBlock)this.Visit(node.Body);
return node.Update(
rewrittenCatchLocals,
rewrittenExceptionSource,
exceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBlock,
node.IsSynthesizedAsyncCatchAll);
}
public override BoundNode VisitSequence(BoundSequence node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteSequence(node, prologue, newLocals);
});
}
else
{
return RewriteSequence(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
public override BoundNode VisitStatementList(BoundStatementList node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
// That can occur for a BoundStatementList if it is the body of a method with captured parameters.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
InsertAndFreePrologue(newStatements, prologue);
foreach (var s in node.Statements)
{
newStatements.Add((BoundStatement)this.Visit(s));
}
return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
});
}
else
{
return base.VisitStatementList(node);
}
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
// A delegate creation expression of the form "new Action( ()=>{} )" is treated exactly like
// (Action)(()=>{})
if (node.Argument.Kind == BoundKind.Lambda)
{
return RewriteLambdaConversion((BoundLambda)node.Argument);
}
if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction)
{
var arguments = default(ImmutableArray<BoundExpression>);
var argRefKinds = default(ImmutableArray<RefKind>);
RemapLocalFunction(
node.Syntax,
node.MethodOpt,
out var receiver,
out var method,
ref arguments,
ref argRefKinds);
return new BoundDelegateCreationExpression(
node.Syntax,
receiver,
method,
node.IsExtensionMethod,
VisitType(node.Type));
}
return base.VisitDelegateCreationExpression(node);
}
public override BoundNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node)
{
if (node.TargetMethod.MethodKind == MethodKind.LocalFunction)
{
Debug.Assert(node.TargetMethod is { RequiresInstanceReceiver: false, IsStatic: true });
ImmutableArray<BoundExpression> arguments = default;
ImmutableArray<RefKind> argRefKinds = default;
RemapLocalFunction(
node.Syntax,
node.TargetMethod,
out BoundExpression receiver,
out MethodSymbol remappedMethod,
ref arguments,
ref argRefKinds);
Debug.Assert(arguments.IsDefault &&
argRefKinds.IsDefault &&
receiver.Kind == BoundKind.TypeExpression &&
remappedMethod is { RequiresInstanceReceiver: false, IsStatic: true });
return node.Update(remappedMethod, constrainedToTypeOpt: node.ConstrainedToTypeOpt, node.Type);
}
return base.VisitFunctionPointerLoad(node);
}
public override BoundNode VisitConversion(BoundConversion conversion)
{
// a conversion with a method should have been rewritten, e.g. to an invocation
Debug.Assert(_inExpressionLambda || conversion.Conversion.MethodSymbol is null);
Debug.Assert(conversion.ConversionKind != ConversionKind.MethodGroup);
if (conversion.ConversionKind == ConversionKind.AnonymousFunction)
{
var result = (BoundExpression)RewriteLambdaConversion((BoundLambda)conversion.Operand);
if (_inExpressionLambda && conversion.ExplicitCastInCode)
{
result = new BoundConversion(
syntax: conversion.Syntax,
operand: result,
conversion: conversion.Conversion,
isBaseConversion: false,
@checked: false,
explicitCastInCode: true,
conversionGroupOpt: conversion.ConversionGroupOpt,
constantValueOpt: conversion.ConstantValueOpt,
type: conversion.Type);
}
return result;
}
return base.VisitConversion(conversion);
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
return new BoundNoOpStatement(node.Syntax, NoOpStatementFlavor.Default);
}
private DebugId GetLambdaId(SyntaxNode syntax, ClosureKind closureKind, int closureOrdinal)
{
Debug.Assert(syntax != null);
SyntaxNode lambdaOrLambdaBodySyntax;
bool isLambdaBody;
if (syntax is AnonymousFunctionExpressionSyntax anonymousFunction)
{
lambdaOrLambdaBodySyntax = anonymousFunction.Body;
isLambdaBody = true;
}
else if (syntax is LocalFunctionStatementSyntax localFunction)
{
lambdaOrLambdaBodySyntax = (SyntaxNode)localFunction.Body ?? localFunction.ExpressionBody?.Expression;
if (lambdaOrLambdaBodySyntax is null)
{
lambdaOrLambdaBodySyntax = localFunction;
isLambdaBody = false;
}
else
{
isLambdaBody = true;
}
}
else if (LambdaUtilities.IsQueryPairLambda(syntax))
{
// "pair" query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = false;
Debug.Assert(closureKind == ClosureKind.Singleton);
}
else
{
// query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = true;
}
Debug.Assert(!isLambdaBody || LambdaUtilities.IsLambdaBody(lambdaOrLambdaBodySyntax));
// determine lambda ordinal and calculate syntax offset
DebugId lambdaId;
DebugId previousLambdaId;
if (slotAllocatorOpt != null && slotAllocatorOpt.TryGetPreviousLambda(lambdaOrLambdaBodySyntax, isLambdaBody, out previousLambdaId))
{
lambdaId = previousLambdaId;
}
else
{
lambdaId = new DebugId(_lambdaDebugInfoBuilder.Count, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(lambdaOrLambdaBodySyntax), lambdaOrLambdaBodySyntax.SyntaxTree);
_lambdaDebugInfoBuilder.Add(new LambdaDebugInfo(syntaxOffset, lambdaId, closureOrdinal));
return lambdaId;
}
private SynthesizedClosureMethod RewriteLambdaOrLocalFunction(
IBoundLambdaOrFunction node,
out ClosureKind closureKind,
out NamedTypeSymbol translatedLambdaContainer,
out SynthesizedClosureEnvironment containerAsFrame,
out BoundNode lambdaScope,
out DebugId topLevelMethodId,
out DebugId lambdaId)
{
Analysis.NestedFunction function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, node.Symbol);
var synthesizedMethod = function.SynthesizedLoweredMethod;
Debug.Assert(synthesizedMethod != null);
closureKind = synthesizedMethod.ClosureKind;
translatedLambdaContainer = synthesizedMethod.ContainingType;
containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = synthesizedMethod.LambdaId;
if (function.ContainingEnvironmentOpt != null)
{
// Find the scope of the containing environment
BoundNode tmpScope = null;
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment == function.ContainingEnvironmentOpt)
{
tmpScope = scope.BoundNode;
}
});
Debug.Assert(tmpScope != null);
lambdaScope = tmpScope;
}
else
{
lambdaScope = null;
}
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, synthesizedMethod.GetCciAdapter());
foreach (var parameter in node.Symbol.Parameters)
{
_parameterMap.Add(parameter, synthesizedMethod.Parameters[parameter.Ordinal]);
}
// rewrite the lambda body as the generated method's body
var oldMethod = _currentMethod;
var oldFrameThis = _currentFrameThis;
var oldTypeParameters = _currentTypeParameters;
var oldInnermostFramePointer = _innermostFramePointer;
var oldTypeMap = _currentLambdaBodyTypeMap;
var oldAddedStatements = _addedStatements;
var oldAddedLocals = _addedLocals;
_addedStatements = null;
_addedLocals = null;
// switch to the generated method
_currentMethod = synthesizedMethod;
if (closureKind == ClosureKind.Static || closureKind == ClosureKind.Singleton)
{
// no link from a static lambda to its container
_innermostFramePointer = _currentFrameThis = null;
}
else
{
_currentFrameThis = synthesizedMethod.ThisParameter;
_framePointers.TryGetValue(translatedLambdaContainer, out _innermostFramePointer);
}
_currentTypeParameters = containerAsFrame?.TypeParameters.Concat(synthesizedMethod.TypeParameters) ?? synthesizedMethod.TypeParameters;
_currentLambdaBodyTypeMap = synthesizedMethod.TypeMap;
if (node.Body is BoundBlock block)
{
var body = AddStatementsIfNeeded((BoundStatement)VisitBlock(block));
CheckLocalsDefined(body);
AddSynthesizedMethod(synthesizedMethod, body);
}
// return to the old method
_currentMethod = oldMethod;
_currentFrameThis = oldFrameThis;
_currentTypeParameters = oldTypeParameters;
_innermostFramePointer = oldInnermostFramePointer;
_currentLambdaBodyTypeMap = oldTypeMap;
_addedLocals = oldAddedLocals;
_addedStatements = oldAddedStatements;
return synthesizedMethod;
}
private void AddSynthesizedMethod(MethodSymbol method, BoundStatement body)
{
if (_synthesizedMethods == null)
{
_synthesizedMethods = ArrayBuilder<TypeCompilationState.MethodWithBody>.GetInstance();
}
_synthesizedMethods.Add(
new TypeCompilationState.MethodWithBody(
method,
body,
CompilationState.CurrentImportChain));
}
private BoundNode RewriteLambdaConversion(BoundLambda node)
{
var wasInExpressionLambda = _inExpressionLambda;
_inExpressionLambda = _inExpressionLambda || node.Type.IsExpressionTree();
if (_inExpressionLambda)
{
var newType = VisitType(node.Type);
var newBody = (BoundBlock)Visit(node.Body);
node = node.Update(node.UnboundLambda, node.Symbol, newBody, node.Diagnostics, node.Binder, newType);
var result0 = wasInExpressionLambda ? node : ExpressionLambdaRewriter.RewriteLambda(node, CompilationState, TypeMap, RecursionDepth, Diagnostics);
_inExpressionLambda = wasInExpressionLambda;
return result0;
}
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
SynthesizedClosureMethod synthesizedMethod = RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
MethodSymbol referencedMethod = synthesizedMethod;
BoundExpression receiver;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(node.Syntax, node.Symbol, default(ImmutableArray<TypeWithAnnotations>), closureKind, ref referencedMethod, out receiver, out constructedFrame);
// Rewrite the lambda expression (and the enclosing anonymous method conversion) as a delegate creation expression
TypeSymbol type = this.VisitType(node.Type);
// static lambdas are emitted as instance methods on a singleton receiver
// delegates invoke dispatch is optimized for instance delegates so
// it is preferable to emit lambdas as instance methods even when lambdas
// do not capture anything
BoundExpression result = new BoundDelegateCreationExpression(
node.Syntax,
receiver,
referencedMethod,
isExtensionMethod: false,
type: type);
// if the block containing the lambda is not the innermost block,
// or the lambda is static, then the lambda object should be cached in its frame.
// NOTE: we are not caching static lambdas in static ctors - cannot reuse such cache.
var shouldCacheForStaticMethod = closureKind == ClosureKind.Singleton &&
_currentMethod.MethodKind != MethodKind.StaticConstructor &&
!referencedMethod.IsGenericMethod;
// NOTE: We require "lambdaScope != null".
// We do not want to introduce a field into an actual user's class (not a synthetic frame).
var shouldCacheInLoop = lambdaScope != null &&
lambdaScope != Analysis.GetScopeParent(_analysis.ScopeTree, node.Body).BoundNode &&
InLoopOrLambda(node.Syntax, lambdaScope.Syntax);
if (shouldCacheForStaticMethod || shouldCacheInLoop)
{
// replace the expression "new Delegate(frame.M)" with "frame.cache ?? (frame.cache = new Delegate(frame.M));
var F = new SyntheticBoundNodeFactory(_currentMethod, node.Syntax, CompilationState, Diagnostics);
try
{
BoundExpression cache;
if (shouldCacheForStaticMethod || shouldCacheInLoop && (object)containerAsFrame != null)
{
// Since the cache variable will be in a container with possibly alpha-rewritten generic parameters, we need to
// substitute the original type according to the type map for that container. That substituted type may be
// different from the local variable `type`, which has the node's type substituted for the current container.
var cacheVariableType = containerAsFrame.TypeMap.SubstituteType(node.Type).Type;
var hasTypeParametersFromAnyMethod = cacheVariableType.ContainsMethodTypeParameter();
// If we want to cache a variable by moving its value into a field,
// the variable cannot use any type parameter from the method it is currently declared within.
if (!hasTypeParametersFromAnyMethod)
{
var cacheVariableName = GeneratedNames.MakeLambdaCacheFieldName(
// If we are generating the field into a display class created exclusively for the lambda the lambdaOrdinal itself is unique already,
// no need to include the top-level method ordinal in the field name.
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
var cacheField = new SynthesizedLambdaCacheFieldSymbol(translatedLambdaContainer, cacheVariableType, cacheVariableName, _topLevelMethod, isReadOnly: false, isStatic: closureKind == ClosureKind.Singleton);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, cacheField.GetCciAdapter());
cache = F.Field(receiver, cacheField.AsMember(constructedFrame)); //NOTE: the field was added to the unconstructed frame type.
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
else
{
// the lambda captures at most the "this" of the enclosing method. We cache its delegate in a local variable.
var cacheLocal = F.SynthesizedLocal(type, kind: SynthesizedLocalKind.CachedAnonymousMethodDelegate);
if (_addedLocals == null) _addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
_addedLocals.Add(cacheLocal);
if (_addedStatements == null) _addedStatements = ArrayBuilder<BoundStatement>.GetInstance();
cache = F.Local(cacheLocal);
_addedStatements.Add(F.Assignment(cache, F.Null(type)));
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
Diagnostics.Add(ex.Diagnostic);
return new BoundBadExpression(F.Syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(node), node.Type);
}
}
return result;
}
// This helper checks syntactically whether there is a loop or lambda expression
// between given lambda syntax and the syntax that corresponds to its closure.
// we use this heuristic as a hint that the lambda delegate may be created
// multiple times with same closure.
// In such cases it makes sense to cache the delegate.
//
// Examples:
// int x = 123;
// for (int i = 1; i< 10; i++)
// {
// if (i< 2)
// {
// arr[i].Execute(arg => arg + x); // delegate should be cached
// }
// }
// for (int i = 1; i< 10; i++)
// {
// var val = i;
// if (i< 2)
// {
// int y = i + i;
// System.Console.WriteLine(y);
// arr[i].Execute(arg => arg + val); // delegate should NOT be cached (closure created inside the loop)
// }
// }
//
private static bool InLoopOrLambda(SyntaxNode lambdaSyntax, SyntaxNode scopeSyntax)
{
var curSyntax = lambdaSyntax.Parent;
while (curSyntax != null && curSyntax != scopeSyntax)
{
switch (curSyntax.Kind())
{
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
return true;
}
curSyntax = curSyntax.Parent;
}
return false;
}
public override BoundNode VisitLambda(BoundLambda node)
{
// these nodes have been handled in the context of the enclosing anonymous method conversion.
throw ExceptionUtilities.Unreachable;
}
#endregion
#if CHECK_LOCALS
/// <summary>
/// Ensure that local variables are always in scope where used in bound trees
/// </summary>
/// <param name="node"></param>
static partial void CheckLocalsDefined(BoundNode node)
{
LocalsDefinedScanner.INSTANCE.Visit(node);
}
class LocalsDefinedScanner : BoundTreeWalker
{
internal static LocalsDefinedScanner INSTANCE = new LocalsDefinedScanner();
HashSet<Symbol> localsDefined = new HashSet<Symbol>();
public override BoundNode VisitLocal(BoundLocal node)
{
Debug.Assert(node.LocalSymbol.IsConst || localsDefined.Contains(node.LocalSymbol));
return base.VisitLocal(node);
}
public override BoundNode VisitSequence(BoundSequence node)
{
try
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Add(l);
return base.VisitSequence(node);
}
finally
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Remove(l);
}
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
try
{
if ((object)node.LocalOpt != null) localsDefined.Add(node.LocalOpt);
return base.VisitCatchBlock(node);
}
finally
{
if ((object)node.LocalOpt != null) localsDefined.Remove(node.LocalOpt);
}
}
public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitSwitchStatement(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
public override BoundNode VisitBlock(BoundBlock node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitBlock(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#if DEBUG
//#define CHECK_LOCALS // define CHECK_LOCALS to help debug some rewriting problems that would otherwise cause code-gen failures
#endif
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The rewriter for removing lambda expressions from method bodies and introducing closure classes
/// as containers for captured variables along the lines of the example in section 6.5.3 of the
/// C# language specification. A closure is the lowered form of a nested function, consisting of a
/// synthesized method and a set of environments containing the captured variables.
///
/// The entry point is the public method <see cref="Rewrite"/>. It operates as follows:
///
/// First, an analysis of the whole method body is performed that determines which variables are
/// captured, what their scopes are, and what the nesting relationship is between scopes that
/// have captured variables. The result of this analysis is left in <see cref="_analysis"/>.
///
/// Then we make a frame, or compiler-generated class, represented by an instance of
/// <see cref="SynthesizedClosureEnvironment"/> for each scope with captured variables. The generated frames are kept
/// in <see cref="_frames"/>. Each frame is given a single field for each captured
/// variable in the corresponding scope. These are maintained in <see cref="MethodToClassRewriter.proxies"/>.
///
/// Next, we walk and rewrite the input bound tree, keeping track of the following:
/// (1) The current set of active frame pointers, in <see cref="_framePointers"/>
/// (2) The current method being processed (this changes within a lambda's body), in <see cref="_currentMethod"/>
/// (3) The "this" symbol for the current method in <see cref="_currentFrameThis"/>, and
/// (4) The symbol that is used to access the innermost frame pointer (it could be a local variable or "this" parameter)
///
/// Lastly, we visit the top-level method and each of the lowered methods
/// to rewrite references (e.g., calls and delegate conversions) to local
/// functions. We visit references to local functions separately from
/// lambdas because we may see the reference before we lower the target
/// local function. Lambdas, on the other hand, are always convertible as
/// they are being lowered.
///
/// There are a few key transformations done in the rewriting.
/// (1) Lambda expressions are turned into delegate creation expressions, and the body of the lambda is
/// moved into a new, compiler-generated method of a selected frame class.
/// (2) On entry to a scope with captured variables, we create a frame object and store it in a local variable.
/// (3) References to captured variables are transformed into references to fields of a frame class.
///
/// In addition, the rewriting deposits into <see cref="TypeCompilationState.SynthesizedMethods"/>
/// a (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pair for each generated method.
///
/// <see cref="Rewrite"/> produces its output in two forms. First, it returns a new bound statement
/// for the caller to use for the body of the original method. Second, it returns a collection of
/// (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pairs for additional methods that the lambda rewriter produced.
/// These additional methods contain the bodies of the lambdas moved into ordinary methods of their
/// respective frame classes, and the caller is responsible for processing them just as it does with
/// the returned bound node. For example, the caller will typically perform iterator method and
/// asynchronous method transformations, and emit IL instructions into an assembly.
/// </summary>
internal sealed partial class ClosureConversion : MethodToClassRewriter
{
private readonly Analysis _analysis;
private readonly MethodSymbol _topLevelMethod;
private readonly MethodSymbol _substitutedSourceMethod;
private readonly int _topLevelMethodOrdinal;
// lambda frame for static lambdas.
// initialized lazily and could be null if there are no static lambdas
private SynthesizedClosureEnvironment _lazyStaticLambdaFrame;
// A mapping from every lambda parameter to its corresponding method's parameter.
private readonly Dictionary<ParameterSymbol, ParameterSymbol> _parameterMap = new Dictionary<ParameterSymbol, ParameterSymbol>();
// for each block with lifted (captured) variables, the corresponding frame type
private readonly Dictionary<BoundNode, Analysis.ClosureEnvironment> _frames = new Dictionary<BoundNode, Analysis.ClosureEnvironment>();
// the current set of frame pointers in scope. Each is either a local variable (where introduced),
// or the "this" parameter when at the top level. Keys in this map are never constructed types.
private readonly Dictionary<NamedTypeSymbol, Symbol> _framePointers = new Dictionary<NamedTypeSymbol, Symbol>();
// The set of original locals that should be assigned to proxies
// if lifted. This is useful for the expression evaluator where
// the original locals are left as is.
private readonly HashSet<LocalSymbol> _assignLocals;
// The current method or lambda being processed.
private MethodSymbol _currentMethod;
// The "this" symbol for the current method.
private ParameterSymbol _currentFrameThis;
private readonly ArrayBuilder<LambdaDebugInfo> _lambdaDebugInfoBuilder;
// ID dispenser for field names of frame references
private int _synthesizedFieldNameIdDispenser;
// The symbol (field or local) holding the innermost frame
private Symbol _innermostFramePointer;
// The mapping of type parameters for the current lambda body
private TypeMap _currentLambdaBodyTypeMap;
// The current set of type parameters (mapped from the enclosing method's type parameters)
private ImmutableArray<TypeParameterSymbol> _currentTypeParameters;
// Initialization for the proxy of the upper frame if it needs to be deferred.
// Such situation happens when lifting this in a ctor.
private BoundExpression _thisProxyInitDeferred;
// Set to true once we've seen the base (or self) constructor invocation in a constructor
private bool _seenBaseCall;
// Set to true while translating code inside of an expression lambda.
private bool _inExpressionLambda;
// When a lambda captures only 'this' of the enclosing method, we cache it in a local
// variable. This is the set of such local variables that must be added to the enclosing
// method's top-level block.
private ArrayBuilder<LocalSymbol> _addedLocals;
// Similarly, this is the set of statements that must be added to the enclosing method's
// top-level block initializing those variables to null.
private ArrayBuilder<BoundStatement> _addedStatements;
/// <summary>
/// Temporary bag for methods synthesized by the rewriting. Added to
/// <see cref="TypeCompilationState.SynthesizedMethods"/> at the end of rewriting.
/// </summary>
private ArrayBuilder<TypeCompilationState.MethodWithBody> _synthesizedMethods;
/// <summary>
/// TODO(https://github.com/dotnet/roslyn/projects/26): Delete this.
/// This should only be used by <see cref="NeedsProxy(Symbol)"/> which
/// hasn't had logic to move the proxy analysis into <see cref="Analysis"/>,
/// where the <see cref="Analysis.ScopeTree"/> could be walked to build
/// the proxy list.
/// </summary>
private readonly ImmutableHashSet<Symbol> _allCapturedVariables;
#nullable enable
private ClosureConversion(
Analysis analysis,
NamedTypeSymbol thisType,
ParameterSymbol thisParameterOpt,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
: base(slotAllocatorOpt, compilationState, diagnostics)
{
RoslynDebug.Assert(analysis != null);
RoslynDebug.Assert((object)thisType != null);
RoslynDebug.Assert(method != null);
RoslynDebug.Assert(compilationState != null);
RoslynDebug.Assert(diagnostics != null);
_topLevelMethod = method;
_substitutedSourceMethod = substitutedSourceMethod;
_topLevelMethodOrdinal = methodOrdinal;
_lambdaDebugInfoBuilder = lambdaDebugInfoBuilder;
_currentMethod = method;
_analysis = analysis;
_assignLocals = assignLocals;
_currentTypeParameters = method.TypeParameters;
_currentLambdaBodyTypeMap = TypeMap.Empty;
_innermostFramePointer = _currentFrameThis = thisParameterOpt;
_framePointers[thisType] = thisParameterOpt;
_seenBaseCall = method.MethodKind != MethodKind.Constructor; // only used for ctors
_synthesizedFieldNameIdDispenser = 1;
var allCapturedVars = ImmutableHashSet.CreateBuilder<Symbol>();
Analysis.VisitNestedFunctions(analysis.ScopeTree, (scope, function) =>
{
allCapturedVars.UnionWith(function.CapturedVariables);
});
_allCapturedVariables = allCapturedVars.ToImmutable();
}
#nullable disable
protected override bool NeedsProxy(Symbol localOrParameter)
{
Debug.Assert(localOrParameter is LocalSymbol || localOrParameter is ParameterSymbol ||
(localOrParameter as MethodSymbol)?.MethodKind == MethodKind.LocalFunction);
return _allCapturedVariables.Contains(localOrParameter);
}
/// <summary>
/// Rewrite the given node to eliminate lambda expressions. Also returned are the method symbols and their
/// bound bodies for the extracted lambda bodies. These would typically be emitted by the caller such as
/// MethodBodyCompiler. See this class' documentation
/// for a more thorough explanation of the algorithm and its use by clients.
/// </summary>
/// <param name="loweredBody">The bound node to be rewritten</param>
/// <param name="thisType">The type of the top-most frame</param>
/// <param name="thisParameter">The "this" parameter in the top-most frame, or null if static method</param>
/// <param name="method">The containing method of the node to be rewritten</param>
/// <param name="methodOrdinal">Index of the method symbol in its containing type member list.</param>
/// <param name="substitutedSourceMethod">If this is non-null, then <paramref name="method"/> will be treated as this for uses of parent symbols. For use in EE.</param>
/// <param name="lambdaDebugInfoBuilder">Information on lambdas defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="closureDebugInfoBuilder">Information on closures defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="slotAllocatorOpt">Slot allocator.</param>
/// <param name="compilationState">The caller's buffer into which we produce additional methods to be emitted by the caller</param>
/// <param name="diagnostics">Diagnostic bag for diagnostics</param>
/// <param name="assignLocals">The set of original locals that should be assigned to proxies if lifted</param>
public static BoundStatement Rewrite(
BoundStatement loweredBody,
NamedTypeSymbol thisType,
ParameterSymbol thisParameter,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
{
Debug.Assert((object)thisType != null);
Debug.Assert(((object)thisParameter == null) || (TypeSymbol.Equals(thisParameter.Type, thisType, TypeCompareKind.ConsiderEverything2)));
Debug.Assert(compilationState.ModuleBuilderOpt != null);
Debug.Assert(diagnostics.DiagnosticBag is object);
var analysis = Analysis.Analyze(
loweredBody,
method,
methodOrdinal,
substitutedSourceMethod,
slotAllocatorOpt,
compilationState,
closureDebugInfoBuilder,
diagnostics.DiagnosticBag);
CheckLocalsDefined(loweredBody);
var rewriter = new ClosureConversion(
analysis,
thisType,
thisParameter,
method,
methodOrdinal,
substitutedSourceMethod,
lambdaDebugInfoBuilder,
slotAllocatorOpt,
compilationState,
diagnostics,
assignLocals);
rewriter.SynthesizeClosureEnvironments(closureDebugInfoBuilder);
rewriter.SynthesizeClosureMethods();
var body = rewriter.AddStatementsIfNeeded(
(BoundStatement)rewriter.Visit(loweredBody));
// Add the completed methods to the compilation state
if (rewriter._synthesizedMethods != null)
{
if (compilationState.SynthesizedMethods == null)
{
compilationState.SynthesizedMethods = rewriter._synthesizedMethods;
}
else
{
compilationState.SynthesizedMethods.AddRange(rewriter._synthesizedMethods);
rewriter._synthesizedMethods.Free();
}
}
CheckLocalsDefined(body);
analysis.Free();
return body;
}
private BoundStatement AddStatementsIfNeeded(BoundStatement body)
{
if (_addedLocals != null)
{
_addedStatements.Add(body);
body = new BoundBlock(body.Syntax, _addedLocals.ToImmutableAndFree(), _addedStatements.ToImmutableAndFree()) { WasCompilerGenerated = true };
_addedLocals = null;
_addedStatements = null;
}
else
{
Debug.Assert(_addedStatements == null);
}
return body;
}
protected override TypeMap TypeMap
{
get { return _currentLambdaBodyTypeMap; }
}
protected override MethodSymbol CurrentMethod
{
get { return _currentMethod; }
}
protected override NamedTypeSymbol ContainingType
{
get { return _topLevelMethod.ContainingType; }
}
/// <summary>
/// Check that the top-level node is well-defined, in the sense that all
/// locals that are used are defined in some enclosing scope.
/// </summary>
static partial void CheckLocalsDefined(BoundNode node);
/// <summary>
/// Adds <see cref="SynthesizedClosureEnvironment"/> synthesized types to the compilation state
/// and creates hoisted fields for all locals captured by the environments.
/// </summary>
private void SynthesizeClosureEnvironments(ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
{
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment is { } env)
{
Debug.Assert(!_frames.ContainsKey(scope.BoundNode));
var frame = MakeFrame(scope, env);
env.SynthesizedEnvironment = frame;
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(ContainingType, frame.GetCciAdapter());
if (frame.Constructor != null)
{
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, Diagnostics),
frame.Constructor));
}
_frames.Add(scope.BoundNode, env);
}
});
SynthesizedClosureEnvironment MakeFrame(Analysis.Scope scope, Analysis.ClosureEnvironment env)
{
var scopeBoundNode = scope.BoundNode;
var syntax = scopeBoundNode.Syntax;
Debug.Assert(syntax != null);
DebugId methodId = _analysis.GetTopLevelMethodId();
DebugId closureId = _analysis.GetClosureId(syntax, closureDebugInfo);
var containingMethod = scope.ContainingFunctionOpt?.OriginalMethodSymbol ?? _topLevelMethod;
if ((object)_substitutedSourceMethod != null && containingMethod == _topLevelMethod)
{
containingMethod = _substitutedSourceMethod;
}
var synthesizedEnv = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
env.IsStruct,
syntax,
methodId,
closureId);
foreach (var captured in env.CapturedVariables)
{
Debug.Assert(!proxies.ContainsKey(captured));
var hoistedField = LambdaCapturedVariable.Create(synthesizedEnv, captured, ref _synthesizedFieldNameIdDispenser);
proxies.Add(captured, new CapturedToFrameSymbolReplacement(hoistedField, isReusable: false));
synthesizedEnv.AddHoistedField(hoistedField);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(synthesizedEnv, hoistedField.GetCciAdapter());
}
return synthesizedEnv;
}
}
/// <summary>
/// Synthesize closure methods for all nested functions.
/// </summary>
private void SynthesizeClosureMethods()
{
Analysis.VisitNestedFunctions(_analysis.ScopeTree, (scope, nestedFunction) =>
{
var originalMethod = nestedFunction.OriginalMethodSymbol;
var syntax = originalMethod.DeclaringSyntaxReferences[0].GetSyntax();
int closureOrdinal;
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
DebugId topLevelMethodId;
DebugId lambdaId;
if (nestedFunction.ContainingEnvironmentOpt != null)
{
containerAsFrame = nestedFunction.ContainingEnvironmentOpt.SynthesizedEnvironment;
closureKind = ClosureKind.General;
translatedLambdaContainer = containerAsFrame;
closureOrdinal = containerAsFrame.ClosureOrdinal;
}
else if (nestedFunction.CapturesThis)
{
containerAsFrame = null;
translatedLambdaContainer = _topLevelMethod.ContainingType;
closureKind = ClosureKind.ThisOnly;
closureOrdinal = LambdaDebugInfo.ThisOnlyClosureOrdinal;
}
else if ((nestedFunction.CapturedEnvironments.Count == 0 &&
originalMethod.MethodKind == MethodKind.LambdaMethod &&
_analysis.MethodsConvertedToDelegates.Contains(originalMethod)) ||
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is object)
{
translatedLambdaContainer = containerAsFrame = GetStaticFrame(Diagnostics, syntax);
closureKind = ClosureKind.Singleton;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
else
{
// Lower directly onto the containing type
translatedLambdaContainer = _topLevelMethod.ContainingType;
containerAsFrame = null;
closureKind = ClosureKind.Static;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
Debug.Assert((object)translatedLambdaContainer != _topLevelMethod.ContainingType ||
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null);
// Move the body of the lambda to a freshly generated synthetic method on its frame.
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = GetLambdaId(syntax, closureKind, closureOrdinal);
var synthesizedMethod = new SynthesizedClosureMethod(
translatedLambdaContainer,
getStructEnvironments(nestedFunction),
closureKind,
_topLevelMethod,
topLevelMethodId,
originalMethod,
nestedFunction.BlockSyntax,
lambdaId,
CompilationState);
nestedFunction.SynthesizedLoweredMethod = synthesizedMethod;
});
static ImmutableArray<SynthesizedClosureEnvironment> getStructEnvironments(Analysis.NestedFunction function)
{
var environments = ArrayBuilder<SynthesizedClosureEnvironment>.GetInstance();
foreach (var env in function.CapturedEnvironments)
{
if (env.IsStruct)
{
environments.Add(env.SynthesizedEnvironment);
}
}
return environments.ToImmutableAndFree();
}
}
/// <summary>
/// Get the static container for closures or create one if one doesn't already exist.
/// </summary>
/// <param name="syntax">
/// associate the frame with the first lambda that caused it to exist.
/// we need to associate this with some syntax.
/// unfortunately either containing method or containing class could be synthetic
/// therefore could have no syntax.
/// </param>
private SynthesizedClosureEnvironment GetStaticFrame(BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
if ((object)_lazyStaticLambdaFrame == null)
{
var isNonGeneric = !_topLevelMethod.IsGenericMethod;
if (isNonGeneric)
{
_lazyStaticLambdaFrame = CompilationState.StaticLambdaFrame;
}
if ((object)_lazyStaticLambdaFrame == null)
{
DebugId methodId;
if (isNonGeneric)
{
methodId = new DebugId(DebugId.UndefinedOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
else
{
methodId = _analysis.GetTopLevelMethodId();
}
DebugId closureId = default(DebugId);
// using _topLevelMethod as containing member because the static frame does not have generic parameters, except for the top level method's
var containingMethod = isNonGeneric ? null : (_substitutedSourceMethod ?? _topLevelMethod);
_lazyStaticLambdaFrame = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
isStruct: false,
scopeSyntaxOpt: null,
methodId: methodId,
closureId: closureId);
// non-generic static lambdas can share the frame
if (isNonGeneric)
{
CompilationState.StaticLambdaFrame = _lazyStaticLambdaFrame;
}
var frame = _lazyStaticLambdaFrame;
// add frame type and cache field
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(this.ContainingType, frame.GetCciAdapter());
// add its ctor (note Constructor can be null if TypeKind.Struct is passed in to LambdaFrame.ctor, but Class is passed in above)
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, diagnostics),
frame.Constructor));
// add cctor
// Frame.inst = new Frame()
var F = new SyntheticBoundNodeFactory(frame.StaticConstructor, syntax, CompilationState, diagnostics);
var body = F.Block(
F.Assignment(
F.Field(null, frame.SingletonCache),
F.New(frame.Constructor)),
new BoundReturnStatement(syntax, RefKind.None, null));
AddSynthesizedMethod(frame.StaticConstructor, body);
}
}
return _lazyStaticLambdaFrame;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame type.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameType">The type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
private BoundExpression FrameOfType(SyntaxNode syntax, NamedTypeSymbol frameType)
{
BoundExpression result = FramePointer(syntax, frameType.OriginalDefinition);
Debug.Assert(TypeSymbol.Equals(result.Type, frameType, TypeCompareKind.ConsiderEverything2));
return result;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame class.
/// Note that for generic frames, the frameClass parameter is the generic definition, but
/// the resulting expression will be constructed with the current type parameters.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameClass">The class type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
protected override BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass)
{
Debug.Assert(frameClass.IsDefinition);
// If in an instance method of the right type, we can just return the "this" pointer.
if ((object)_currentFrameThis != null && TypeSymbol.Equals(_currentFrameThis.Type, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundThisReference(syntax, frameClass);
}
// If the current method has by-ref struct closure parameters, and one of them is correct, use it.
var lambda = _currentMethod as SynthesizedClosureMethod;
if (lambda != null)
{
var start = lambda.ParameterCount - lambda.ExtraSynthesizedParameterCount;
for (var i = start; i < lambda.ParameterCount; i++)
{
var potentialParameter = lambda.Parameters[i];
if (TypeSymbol.Equals(potentialParameter.Type.OriginalDefinition, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundParameter(syntax, potentialParameter);
}
}
}
// Otherwise we need to return the value from a frame pointer local variable...
Symbol framePointer = _framePointers[frameClass];
CapturedSymbolReplacement proxyField;
if (proxies.TryGetValue(framePointer, out proxyField))
{
// However, frame pointer local variables themselves can be "captured". In that case
// the inner frames contain pointers to the enclosing frames. That is, nested
// frame pointers are organized in a linked list.
return proxyField.Replacement(syntax, frameType => FramePointer(syntax, frameType));
}
var localFrame = (LocalSymbol)framePointer;
return new BoundLocal(syntax, localFrame, null, localFrame.Type);
}
private static void InsertAndFreePrologue<T>(ArrayBuilder<BoundStatement> result, ArrayBuilder<T> prologue) where T : BoundNode
{
foreach (var node in prologue)
{
if (node is BoundStatement stmt)
{
result.Add(stmt);
}
else
{
result.Add(new BoundExpressionStatement(node.Syntax, (BoundExpression)(BoundNode)node));
}
}
prologue.Free();
}
/// <summary>
/// Introduce a frame around the translation of the given node.
/// </summary>
/// <param name="node">The node whose translation should be translated to contain a frame</param>
/// <param name="env">The environment for the translated node</param>
/// <param name="F">A function that computes the translation of the node. It receives lists of added statements and added symbols</param>
/// <returns>The translated statement, as returned from F</returns>
private BoundNode IntroduceFrame(BoundNode node, Analysis.ClosureEnvironment env, Func<ArrayBuilder<BoundExpression>, ArrayBuilder<LocalSymbol>, BoundNode> F)
{
var frame = env.SynthesizedEnvironment;
var frameTypeParameters = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, frame.Arity);
NamedTypeSymbol frameType = frame.ConstructIfGeneric(frameTypeParameters);
Debug.Assert(frame.ScopeSyntaxOpt != null);
LocalSymbol framePointer = new SynthesizedLocal(_topLevelMethod, TypeWithAnnotations.Create(frameType), SynthesizedLocalKind.LambdaDisplayClass, frame.ScopeSyntaxOpt);
SyntaxNode syntax = node.Syntax;
// assign new frame to the frame variable
var prologue = ArrayBuilder<BoundExpression>.GetInstance();
if ((object)frame.Constructor != null)
{
MethodSymbol constructor = frame.Constructor.AsMember(frameType);
Debug.Assert(TypeSymbol.Equals(frameType, constructor.ContainingType, TypeCompareKind.ConsiderEverything2));
prologue.Add(new BoundAssignmentOperator(syntax,
new BoundLocal(syntax, framePointer, null, frameType),
new BoundObjectCreationExpression(syntax: syntax, constructor: constructor),
frameType));
}
CapturedSymbolReplacement oldInnermostFrameProxy = null;
if ((object)_innermostFramePointer != null)
{
proxies.TryGetValue(_innermostFramePointer, out oldInnermostFrameProxy);
if (env.CapturesParent)
{
var capturedFrame = LambdaCapturedVariable.Create(frame, _innermostFramePointer, ref _synthesizedFieldNameIdDispenser);
FieldSymbol frameParent = capturedFrame.AsMember(frameType);
BoundExpression left = new BoundFieldAccess(syntax, new BoundLocal(syntax, framePointer, null, frameType), frameParent, null);
BoundExpression right = FrameOfType(syntax, frameParent.Type as NamedTypeSymbol);
BoundExpression assignment = new BoundAssignmentOperator(syntax, left, right, left.Type);
prologue.Add(assignment);
if (CompilationState.Emitting)
{
Debug.Assert(capturedFrame.Type.IsReferenceType); // Make sure we're not accidentally capturing a struct by value
frame.AddHoistedField(capturedFrame);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, capturedFrame.GetCciAdapter());
}
proxies[_innermostFramePointer] = new CapturedToFrameSymbolReplacement(capturedFrame, isReusable: false);
}
}
// Capture any parameters of this block. This would typically occur
// at the top level of a method or lambda with captured parameters.
foreach (var variable in env.CapturedVariables)
{
InitVariableProxy(syntax, variable, framePointer, prologue);
}
Symbol oldInnermostFramePointer = _innermostFramePointer;
if (!framePointer.Type.IsValueType)
{
_innermostFramePointer = framePointer;
}
var addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
addedLocals.Add(framePointer);
_framePointers.Add(frame, framePointer);
var result = F(prologue, addedLocals);
_innermostFramePointer = oldInnermostFramePointer;
if ((object)_innermostFramePointer != null)
{
if (oldInnermostFrameProxy != null)
{
proxies[_innermostFramePointer] = oldInnermostFrameProxy;
}
else
{
proxies.Remove(_innermostFramePointer);
}
}
return result;
}
private void InitVariableProxy(SyntaxNode syntax, Symbol symbol, LocalSymbol framePointer, ArrayBuilder<BoundExpression> prologue)
{
CapturedSymbolReplacement proxy;
if (proxies.TryGetValue(symbol, out proxy))
{
BoundExpression value;
switch (symbol.Kind)
{
case SymbolKind.Parameter:
var parameter = (ParameterSymbol)symbol;
ParameterSymbol parameterToUse;
if (!_parameterMap.TryGetValue(parameter, out parameterToUse))
{
parameterToUse = parameter;
}
value = new BoundParameter(syntax, parameterToUse);
break;
case SymbolKind.Local:
var local = (LocalSymbol)symbol;
if (_assignLocals == null || !_assignLocals.Contains(local))
{
return;
}
LocalSymbol localToUse;
if (!localMap.TryGetValue(local, out localToUse))
{
localToUse = local;
}
value = new BoundLocal(syntax, localToUse, null, localToUse.Type);
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
var left = proxy.Replacement(syntax, frameType1 => new BoundLocal(syntax, framePointer, null, framePointer.Type));
var assignToProxy = new BoundAssignmentOperator(syntax, left, value, value.Type);
if (_currentMethod.MethodKind == MethodKind.Constructor &&
symbol == _currentMethod.ThisParameter &&
!_seenBaseCall)
{
// Containing method is a constructor
// Initialization statement for the "this" proxy must be inserted
// after the constructor initializer statement block
Debug.Assert(_thisProxyInitDeferred == null);
_thisProxyInitDeferred = assignToProxy;
}
else
{
prologue.Add(assignToProxy);
}
}
}
#region Visit Methods
protected override BoundNode VisitUnhoistedParameter(BoundParameter node)
{
ParameterSymbol replacementParameter;
if (_parameterMap.TryGetValue(node.ParameterSymbol, out replacementParameter))
{
return new BoundParameter(node.Syntax, replacementParameter, node.HasErrors);
}
return base.VisitUnhoistedParameter(node);
}
public override BoundNode VisitThisReference(BoundThisReference node)
{
// "topLevelMethod.ThisParameter == null" can occur in a delegate creation expression because the method group
// in the argument can have a "this" receiver even when "this"
// is not captured because a static method is selected. But we do preserve
// the method group and its receiver in the bound tree.
// No need to capture "this" in such case.
// TODO: Why don't we drop "this" while lowering if method is static?
// Actually, considering that method group expression does not evaluate to a particular value
// why do we have it in the lowered tree at all?
return (_currentMethod == _topLevelMethod || _topLevelMethod.ThisParameter == null ?
node :
FramePointer(node.Syntax, (NamedTypeSymbol)node.Type));
}
public override BoundNode VisitBaseReference(BoundBaseReference node)
{
return (!_currentMethod.IsStatic && TypeSymbol.Equals(_currentMethod.ContainingType, _topLevelMethod.ContainingType, TypeCompareKind.ConsiderEverything2))
? node
: FramePointer(node.Syntax, _topLevelMethod.ContainingType); // technically, not the correct static type
}
/// <summary>
/// Rewrites a reference to an unlowered local function to the newly
/// lowered local function.
/// </summary>
private void RemapLocalFunction(
SyntaxNode syntax,
MethodSymbol localFunc,
out BoundExpression receiver,
out MethodSymbol method,
ref ImmutableArray<BoundExpression> arguments,
ref ImmutableArray<RefKind> argRefKinds)
{
Debug.Assert(localFunc.MethodKind == MethodKind.LocalFunction);
var function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, localFunc.OriginalDefinition);
var loweredSymbol = function.SynthesizedLoweredMethod;
// If the local function captured variables then they will be stored
// in frames and the frames need to be passed as extra parameters.
var frameCount = loweredSymbol.ExtraSynthesizedParameterCount;
if (frameCount != 0)
{
Debug.Assert(!arguments.IsDefault);
// Build a new list of arguments to pass to the local function
// call that includes any necessary capture frames
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(loweredSymbol.ParameterCount);
argumentsBuilder.AddRange(arguments);
var start = loweredSymbol.ParameterCount - frameCount;
for (int i = start; i < loweredSymbol.ParameterCount; i++)
{
// will always be a LambdaFrame, it's always a capture frame
var frameType = (NamedTypeSymbol)loweredSymbol.Parameters[i].Type.OriginalDefinition;
Debug.Assert(frameType is SynthesizedClosureEnvironment);
if (frameType.Arity > 0)
{
var typeParameters = ((SynthesizedClosureEnvironment)frameType).ConstructedFromTypeParameters;
Debug.Assert(typeParameters.Length == frameType.Arity);
var subst = this.TypeMap.SubstituteTypeParameters(typeParameters);
frameType = frameType.Construct(subst);
}
var frame = FrameOfType(syntax, frameType);
argumentsBuilder.Add(frame);
}
// frame arguments are passed by ref
// add corresponding refkinds
var refkindsBuilder = ArrayBuilder<RefKind>.GetInstance(argumentsBuilder.Count);
if (!argRefKinds.IsDefault)
{
refkindsBuilder.AddRange(argRefKinds);
}
else
{
refkindsBuilder.AddMany(RefKind.None, arguments.Length);
}
refkindsBuilder.AddMany(RefKind.Ref, frameCount);
arguments = argumentsBuilder.ToImmutableAndFree();
argRefKinds = refkindsBuilder.ToImmutableAndFree();
}
method = loweredSymbol;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(syntax,
localFunc,
SubstituteTypeArguments(localFunc.TypeArgumentsWithAnnotations),
loweredSymbol.ClosureKind,
ref method,
out receiver,
out constructedFrame);
}
/// <summary>
/// Substitutes references from old type arguments to new type arguments
/// in the lowered methods.
/// </summary>
/// <example>
/// Consider the following method:
/// void M() {
/// void L<T>(T t) => Console.Write(t);
/// L("A");
/// }
///
/// In this example, L<T> is a local function that will be
/// lowered into its own method and the type parameter T will be
/// alpha renamed to something else (let's call it T'). In this case,
/// all references to the original type parameter T in L must be
/// rewritten to the renamed parameter, T'.
/// </example>
private ImmutableArray<TypeWithAnnotations> SubstituteTypeArguments(ImmutableArray<TypeWithAnnotations> typeArguments)
{
Debug.Assert(!typeArguments.IsDefault);
if (typeArguments.IsEmpty)
{
return typeArguments;
}
// We must perform this process repeatedly as local
// functions may nest inside one another and capture type
// parameters from the enclosing local functions. Each
// iteration of nesting will cause alpha-renaming of the captured
// parameters, meaning that we must replace until there are no
// more alpha-rename mappings.
//
// The method symbol references are different from all other
// substituted types in this context because the method symbol in
// local function references is not rewritten until all local
// functions have already been lowered. Everything else is rewritten
// by the visitors as the definition is lowered. This means that
// only one substitution happens per lowering, but we need to do
// N substitutions all at once, where N is the number of lowerings.
var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArguments.Length);
foreach (var typeArg in typeArguments)
{
TypeWithAnnotations oldTypeArg;
TypeWithAnnotations newTypeArg = typeArg;
do
{
oldTypeArg = newTypeArg;
newTypeArg = this.TypeMap.SubstituteType(oldTypeArg);
}
while (!TypeSymbol.Equals(oldTypeArg.Type, newTypeArg.Type, TypeCompareKind.ConsiderEverything));
// When type substitution does not change the type, it is expected to return the very same object.
// Therefore the loop is terminated when that type (as an object) does not change.
Debug.Assert((object)oldTypeArg.Type == newTypeArg.Type);
// The types are the same, so the last pass performed no substitutions.
// Therefore the annotations ought to be the same too.
Debug.Assert(oldTypeArg.NullableAnnotation == newTypeArg.NullableAnnotation);
builder.Add(newTypeArg);
}
return builder.ToImmutableAndFree();
}
private void RemapLambdaOrLocalFunction(
SyntaxNode syntax,
MethodSymbol originalMethod,
ImmutableArray<TypeWithAnnotations> typeArgumentsOpt,
ClosureKind closureKind,
ref MethodSymbol synthesizedMethod,
out BoundExpression receiver,
out NamedTypeSymbol constructedFrame)
{
var translatedLambdaContainer = synthesizedMethod.ContainingType;
var containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
// All of _currentTypeParameters might not be preserved here due to recursively calling upwards in the chain of local functions/lambdas
Debug.Assert((typeArgumentsOpt.IsDefault && !originalMethod.IsGenericMethod) || (typeArgumentsOpt.Length == originalMethod.Arity));
var totalTypeArgumentCount = (containerAsFrame?.Arity ?? 0) + synthesizedMethod.Arity;
var realTypeArguments = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, totalTypeArgumentCount - originalMethod.Arity);
if (!typeArgumentsOpt.IsDefault)
{
realTypeArguments = realTypeArguments.Concat(typeArgumentsOpt);
}
if ((object)containerAsFrame != null && containerAsFrame.Arity != 0)
{
var containerTypeArguments = ImmutableArray.Create(realTypeArguments, 0, containerAsFrame.Arity);
realTypeArguments = ImmutableArray.Create(realTypeArguments, containerAsFrame.Arity, realTypeArguments.Length - containerAsFrame.Arity);
constructedFrame = containerAsFrame.Construct(containerTypeArguments);
}
else
{
constructedFrame = translatedLambdaContainer;
}
synthesizedMethod = synthesizedMethod.AsMember(constructedFrame);
if (synthesizedMethod.IsGenericMethod)
{
synthesizedMethod = synthesizedMethod.Construct(realTypeArguments);
}
else
{
Debug.Assert(realTypeArguments.Length == 0);
}
// for instance lambdas, receiver is the frame
// for static lambdas, get the singleton receiver
if (closureKind == ClosureKind.Singleton)
{
var field = containerAsFrame.SingletonCache.AsMember(constructedFrame);
receiver = new BoundFieldAccess(syntax, null, field, constantValueOpt: null);
}
else if (closureKind == ClosureKind.Static)
{
receiver = new BoundTypeExpression(syntax, null, synthesizedMethod.ContainingType);
}
else // ThisOnly and General
{
receiver = FrameOfType(syntax, constructedFrame);
}
}
public override BoundNode VisitCall(BoundCall node)
{
if (node.Method.MethodKind == MethodKind.LocalFunction)
{
var args = VisitList(node.Arguments);
var argRefKinds = node.ArgumentRefKindsOpt;
var type = VisitType(node.Type);
Debug.Assert(node.ArgsToParamsOpt.IsDefault, "should be done with argument reordering by now");
RemapLocalFunction(
node.Syntax,
node.Method,
out var receiver,
out var method,
ref args,
ref argRefKinds);
return node.Update(
receiver,
method,
args,
node.ArgumentNamesOpt,
argRefKinds,
node.IsDelegateCall,
node.Expanded,
node.InvokedAsExtensionMethod,
node.ArgsToParamsOpt,
node.DefaultArguments,
node.ResultKind,
type);
}
var visited = base.VisitCall(node);
if (visited.Kind != BoundKind.Call)
{
return visited;
}
var rewritten = (BoundCall)visited;
// Check if we need to init the 'this' proxy in a ctor call
if (!_seenBaseCall)
{
if (_currentMethod == _topLevelMethod && node.IsConstructorInitializer())
{
_seenBaseCall = true;
if (_thisProxyInitDeferred != null)
{
// Insert the this proxy assignment after the ctor call.
// Create bound sequence: { ctor call, thisProxyInitDeferred }
return new BoundSequence(
syntax: node.Syntax,
locals: ImmutableArray<LocalSymbol>.Empty,
sideEffects: ImmutableArray.Create<BoundExpression>(rewritten),
value: _thisProxyInitDeferred,
type: rewritten.Type);
}
}
}
return rewritten;
}
private BoundSequence RewriteSequence(BoundSequence node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
foreach (var effect in node.SideEffects)
{
var replacement = (BoundExpression)this.Visit(effect);
if (replacement != null) prologue.Add(replacement);
}
var newValue = (BoundExpression)this.Visit(node.Value);
var newType = this.VisitType(node.Type);
return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), newValue, newType);
}
public override BoundNode VisitBlock(BoundBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
RewriteBlock(node, prologue, newLocals));
}
else
{
return RewriteBlock(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
if (prologue.Count > 0)
{
newStatements.Add(BoundSequencePoint.CreateHidden());
}
InsertAndFreePrologue(newStatements, prologue);
foreach (var statement in node.Statements)
{
var replacement = (BoundStatement)this.Visit(statement);
if (replacement != null)
{
newStatements.Add(replacement);
}
}
// TODO: we may not need to update if there was nothing to rewrite.
return node.Update(newLocals.ToImmutableAndFree(), node.LocalFunctions, newStatements.ToImmutableAndFree());
}
public override BoundNode VisitScope(BoundScope node)
{
Debug.Assert(!node.Locals.IsEmpty);
var newLocals = ArrayBuilder<LocalSymbol>.GetInstance();
RewriteLocals(node.Locals, newLocals);
var statements = VisitList(node.Statements);
if (newLocals.Count == 0)
{
newLocals.Free();
return new BoundStatementList(node.Syntax, statements);
}
return node.Update(newLocals.ToImmutableAndFree(), statements);
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteCatch(node, prologue, newLocals);
});
}
else
{
return RewriteCatch(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundNode RewriteCatch(BoundCatchBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var rewrittenCatchLocals = newLocals.ToImmutableAndFree();
// If exception variable got lifted, IntroduceFrame will give us frame init prologue.
// It needs to run before the exception variable is accessed.
// To ensure that, we will make exception variable a sequence that performs prologue as its side-effects.
BoundExpression rewrittenExceptionSource = null;
var rewrittenFilterPrologue = (BoundStatementList)this.Visit(node.ExceptionFilterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(node.ExceptionFilterOpt);
if (node.ExceptionSourceOpt != null)
{
rewrittenExceptionSource = (BoundExpression)Visit(node.ExceptionSourceOpt);
if (prologue.Count > 0)
{
rewrittenExceptionSource = new BoundSequence(
rewrittenExceptionSource.Syntax,
ImmutableArray.Create<LocalSymbol>(),
prologue.ToImmutable(),
rewrittenExceptionSource,
rewrittenExceptionSource.Type);
}
}
else if (prologue.Count > 0)
{
Debug.Assert(rewrittenFilter != null);
var prologueBuilder = ArrayBuilder<BoundStatement>.GetInstance(prologue.Count);
foreach (var p in prologue)
{
prologueBuilder.Add(new BoundExpressionStatement(p.Syntax, p) { WasCompilerGenerated = true });
}
if (rewrittenFilterPrologue != null)
{
prologueBuilder.AddRange(rewrittenFilterPrologue.Statements);
}
rewrittenFilterPrologue = new BoundStatementList(rewrittenFilter.Syntax, prologueBuilder.ToImmutableAndFree());
}
// done with this.
prologue.Free();
// rewrite filter and body
// NOTE: this will proxy all accesses to exception local if that got lifted.
var exceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
var rewrittenBlock = (BoundBlock)this.Visit(node.Body);
return node.Update(
rewrittenCatchLocals,
rewrittenExceptionSource,
exceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBlock,
node.IsSynthesizedAsyncCatchAll);
}
public override BoundNode VisitSequence(BoundSequence node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteSequence(node, prologue, newLocals);
});
}
else
{
return RewriteSequence(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
public override BoundNode VisitStatementList(BoundStatementList node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
// That can occur for a BoundStatementList if it is the body of a method with captured parameters.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
InsertAndFreePrologue(newStatements, prologue);
foreach (var s in node.Statements)
{
newStatements.Add((BoundStatement)this.Visit(s));
}
return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
});
}
else
{
return base.VisitStatementList(node);
}
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
// A delegate creation expression of the form "new Action( ()=>{} )" is treated exactly like
// (Action)(()=>{})
if (node.Argument.Kind == BoundKind.Lambda)
{
return RewriteLambdaConversion((BoundLambda)node.Argument);
}
if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction)
{
var arguments = default(ImmutableArray<BoundExpression>);
var argRefKinds = default(ImmutableArray<RefKind>);
RemapLocalFunction(
node.Syntax,
node.MethodOpt,
out var receiver,
out var method,
ref arguments,
ref argRefKinds);
return new BoundDelegateCreationExpression(
node.Syntax,
receiver,
method,
node.IsExtensionMethod,
VisitType(node.Type));
}
return base.VisitDelegateCreationExpression(node);
}
public override BoundNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node)
{
if (node.TargetMethod.MethodKind == MethodKind.LocalFunction)
{
Debug.Assert(node.TargetMethod is { RequiresInstanceReceiver: false, IsStatic: true });
ImmutableArray<BoundExpression> arguments = default;
ImmutableArray<RefKind> argRefKinds = default;
RemapLocalFunction(
node.Syntax,
node.TargetMethod,
out BoundExpression receiver,
out MethodSymbol remappedMethod,
ref arguments,
ref argRefKinds);
Debug.Assert(arguments.IsDefault &&
argRefKinds.IsDefault &&
receiver.Kind == BoundKind.TypeExpression &&
remappedMethod is { RequiresInstanceReceiver: false, IsStatic: true });
return node.Update(remappedMethod, constrainedToTypeOpt: node.ConstrainedToTypeOpt, node.Type);
}
return base.VisitFunctionPointerLoad(node);
}
public override BoundNode VisitConversion(BoundConversion conversion)
{
// a conversion with a method should have been rewritten, e.g. to an invocation
Debug.Assert(_inExpressionLambda || conversion.Conversion.MethodSymbol is null);
Debug.Assert(conversion.ConversionKind != ConversionKind.MethodGroup);
if (conversion.ConversionKind == ConversionKind.AnonymousFunction)
{
var result = (BoundExpression)RewriteLambdaConversion((BoundLambda)conversion.Operand);
if (_inExpressionLambda && conversion.ExplicitCastInCode)
{
result = new BoundConversion(
syntax: conversion.Syntax,
operand: result,
conversion: conversion.Conversion,
isBaseConversion: false,
@checked: false,
explicitCastInCode: true,
conversionGroupOpt: conversion.ConversionGroupOpt,
constantValueOpt: conversion.ConstantValueOpt,
type: conversion.Type);
}
return result;
}
return base.VisitConversion(conversion);
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
return new BoundNoOpStatement(node.Syntax, NoOpStatementFlavor.Default);
}
private DebugId GetLambdaId(SyntaxNode syntax, ClosureKind closureKind, int closureOrdinal)
{
Debug.Assert(syntax != null);
SyntaxNode lambdaOrLambdaBodySyntax;
bool isLambdaBody;
if (syntax is AnonymousFunctionExpressionSyntax anonymousFunction)
{
lambdaOrLambdaBodySyntax = anonymousFunction.Body;
isLambdaBody = true;
}
else if (syntax is LocalFunctionStatementSyntax localFunction)
{
lambdaOrLambdaBodySyntax = (SyntaxNode)localFunction.Body ?? localFunction.ExpressionBody?.Expression;
if (lambdaOrLambdaBodySyntax is null)
{
lambdaOrLambdaBodySyntax = localFunction;
isLambdaBody = false;
}
else
{
isLambdaBody = true;
}
}
else if (LambdaUtilities.IsQueryPairLambda(syntax))
{
// "pair" query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = false;
Debug.Assert(closureKind == ClosureKind.Singleton);
}
else
{
// query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = true;
}
Debug.Assert(!isLambdaBody || LambdaUtilities.IsLambdaBody(lambdaOrLambdaBodySyntax));
// determine lambda ordinal and calculate syntax offset
DebugId lambdaId;
DebugId previousLambdaId;
if (slotAllocatorOpt != null && slotAllocatorOpt.TryGetPreviousLambda(lambdaOrLambdaBodySyntax, isLambdaBody, out previousLambdaId))
{
lambdaId = previousLambdaId;
}
else
{
lambdaId = new DebugId(_lambdaDebugInfoBuilder.Count, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(lambdaOrLambdaBodySyntax), lambdaOrLambdaBodySyntax.SyntaxTree);
_lambdaDebugInfoBuilder.Add(new LambdaDebugInfo(syntaxOffset, lambdaId, closureOrdinal));
return lambdaId;
}
private SynthesizedClosureMethod RewriteLambdaOrLocalFunction(
IBoundLambdaOrFunction node,
out ClosureKind closureKind,
out NamedTypeSymbol translatedLambdaContainer,
out SynthesizedClosureEnvironment containerAsFrame,
out BoundNode lambdaScope,
out DebugId topLevelMethodId,
out DebugId lambdaId)
{
Analysis.NestedFunction function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, node.Symbol);
var synthesizedMethod = function.SynthesizedLoweredMethod;
Debug.Assert(synthesizedMethod != null);
closureKind = synthesizedMethod.ClosureKind;
translatedLambdaContainer = synthesizedMethod.ContainingType;
containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = synthesizedMethod.LambdaId;
if (function.ContainingEnvironmentOpt != null)
{
// Find the scope of the containing environment
BoundNode tmpScope = null;
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment == function.ContainingEnvironmentOpt)
{
tmpScope = scope.BoundNode;
}
});
Debug.Assert(tmpScope != null);
lambdaScope = tmpScope;
}
else
{
lambdaScope = null;
}
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, synthesizedMethod.GetCciAdapter());
foreach (var parameter in node.Symbol.Parameters)
{
_parameterMap.Add(parameter, synthesizedMethod.Parameters[parameter.Ordinal]);
}
// rewrite the lambda body as the generated method's body
var oldMethod = _currentMethod;
var oldFrameThis = _currentFrameThis;
var oldTypeParameters = _currentTypeParameters;
var oldInnermostFramePointer = _innermostFramePointer;
var oldTypeMap = _currentLambdaBodyTypeMap;
var oldAddedStatements = _addedStatements;
var oldAddedLocals = _addedLocals;
_addedStatements = null;
_addedLocals = null;
// switch to the generated method
_currentMethod = synthesizedMethod;
if (closureKind == ClosureKind.Static || closureKind == ClosureKind.Singleton)
{
// no link from a static lambda to its container
_innermostFramePointer = _currentFrameThis = null;
}
else
{
_currentFrameThis = synthesizedMethod.ThisParameter;
_framePointers.TryGetValue(translatedLambdaContainer, out _innermostFramePointer);
}
_currentTypeParameters = containerAsFrame?.TypeParameters.Concat(synthesizedMethod.TypeParameters) ?? synthesizedMethod.TypeParameters;
_currentLambdaBodyTypeMap = synthesizedMethod.TypeMap;
if (node.Body is BoundBlock block)
{
var body = AddStatementsIfNeeded((BoundStatement)VisitBlock(block));
CheckLocalsDefined(body);
AddSynthesizedMethod(synthesizedMethod, body);
}
// return to the old method
_currentMethod = oldMethod;
_currentFrameThis = oldFrameThis;
_currentTypeParameters = oldTypeParameters;
_innermostFramePointer = oldInnermostFramePointer;
_currentLambdaBodyTypeMap = oldTypeMap;
_addedLocals = oldAddedLocals;
_addedStatements = oldAddedStatements;
return synthesizedMethod;
}
private void AddSynthesizedMethod(MethodSymbol method, BoundStatement body)
{
if (_synthesizedMethods == null)
{
_synthesizedMethods = ArrayBuilder<TypeCompilationState.MethodWithBody>.GetInstance();
}
_synthesizedMethods.Add(
new TypeCompilationState.MethodWithBody(
method,
body,
CompilationState.CurrentImportChain));
}
private BoundNode RewriteLambdaConversion(BoundLambda node)
{
var wasInExpressionLambda = _inExpressionLambda;
_inExpressionLambda = _inExpressionLambda || node.Type.IsExpressionTree();
if (_inExpressionLambda)
{
var newType = VisitType(node.Type);
var newBody = (BoundBlock)Visit(node.Body);
node = node.Update(node.UnboundLambda, node.Symbol, newBody, node.Diagnostics, node.Binder, newType);
var result0 = wasInExpressionLambda ? node : ExpressionLambdaRewriter.RewriteLambda(node, CompilationState, TypeMap, RecursionDepth, Diagnostics);
_inExpressionLambda = wasInExpressionLambda;
return result0;
}
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
SynthesizedClosureMethod synthesizedMethod = RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
MethodSymbol referencedMethod = synthesizedMethod;
BoundExpression receiver;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(node.Syntax, node.Symbol, default(ImmutableArray<TypeWithAnnotations>), closureKind, ref referencedMethod, out receiver, out constructedFrame);
// Rewrite the lambda expression (and the enclosing anonymous method conversion) as a delegate creation expression
TypeSymbol type = this.VisitType(node.Type);
// static lambdas are emitted as instance methods on a singleton receiver
// delegates invoke dispatch is optimized for instance delegates so
// it is preferable to emit lambdas as instance methods even when lambdas
// do not capture anything
BoundExpression result = new BoundDelegateCreationExpression(
node.Syntax,
receiver,
referencedMethod,
isExtensionMethod: false,
type: type);
// if the block containing the lambda is not the innermost block,
// or the lambda is static, then the lambda object should be cached in its frame.
// NOTE: we are not caching static lambdas in static ctors - cannot reuse such cache.
var shouldCacheForStaticMethod = closureKind == ClosureKind.Singleton &&
_currentMethod.MethodKind != MethodKind.StaticConstructor &&
!referencedMethod.IsGenericMethod;
// NOTE: We require "lambdaScope != null".
// We do not want to introduce a field into an actual user's class (not a synthetic frame).
var shouldCacheInLoop = lambdaScope != null &&
lambdaScope != Analysis.GetScopeParent(_analysis.ScopeTree, node.Body).BoundNode &&
InLoopOrLambda(node.Syntax, lambdaScope.Syntax);
if (shouldCacheForStaticMethod || shouldCacheInLoop)
{
// replace the expression "new Delegate(frame.M)" with "frame.cache ?? (frame.cache = new Delegate(frame.M));
var F = new SyntheticBoundNodeFactory(_currentMethod, node.Syntax, CompilationState, Diagnostics);
try
{
BoundExpression cache;
if (shouldCacheForStaticMethod || shouldCacheInLoop && (object)containerAsFrame != null)
{
// Since the cache variable will be in a container with possibly alpha-rewritten generic parameters, we need to
// substitute the original type according to the type map for that container. That substituted type may be
// different from the local variable `type`, which has the node's type substituted for the current container.
var cacheVariableType = containerAsFrame.TypeMap.SubstituteType(node.Type).Type;
var hasTypeParametersFromAnyMethod = cacheVariableType.ContainsMethodTypeParameter();
// If we want to cache a variable by moving its value into a field,
// the variable cannot use any type parameter from the method it is currently declared within.
if (!hasTypeParametersFromAnyMethod)
{
var cacheVariableName = GeneratedNames.MakeLambdaCacheFieldName(
// If we are generating the field into a display class created exclusively for the lambda the lambdaOrdinal itself is unique already,
// no need to include the top-level method ordinal in the field name.
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
var cacheField = new SynthesizedLambdaCacheFieldSymbol(translatedLambdaContainer, cacheVariableType, cacheVariableName, _topLevelMethod, isReadOnly: false, isStatic: closureKind == ClosureKind.Singleton);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, cacheField.GetCciAdapter());
cache = F.Field(receiver, cacheField.AsMember(constructedFrame)); //NOTE: the field was added to the unconstructed frame type.
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
else
{
// the lambda captures at most the "this" of the enclosing method. We cache its delegate in a local variable.
var cacheLocal = F.SynthesizedLocal(type, kind: SynthesizedLocalKind.CachedAnonymousMethodDelegate);
if (_addedLocals == null) _addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
_addedLocals.Add(cacheLocal);
if (_addedStatements == null) _addedStatements = ArrayBuilder<BoundStatement>.GetInstance();
cache = F.Local(cacheLocal);
_addedStatements.Add(F.Assignment(cache, F.Null(type)));
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
Diagnostics.Add(ex.Diagnostic);
return new BoundBadExpression(F.Syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(node), node.Type);
}
}
return result;
}
// This helper checks syntactically whether there is a loop or lambda expression
// between given lambda syntax and the syntax that corresponds to its closure.
// we use this heuristic as a hint that the lambda delegate may be created
// multiple times with same closure.
// In such cases it makes sense to cache the delegate.
//
// Examples:
// int x = 123;
// for (int i = 1; i< 10; i++)
// {
// if (i< 2)
// {
// arr[i].Execute(arg => arg + x); // delegate should be cached
// }
// }
// for (int i = 1; i< 10; i++)
// {
// var val = i;
// if (i< 2)
// {
// int y = i + i;
// System.Console.WriteLine(y);
// arr[i].Execute(arg => arg + val); // delegate should NOT be cached (closure created inside the loop)
// }
// }
//
private static bool InLoopOrLambda(SyntaxNode lambdaSyntax, SyntaxNode scopeSyntax)
{
var curSyntax = lambdaSyntax.Parent;
while (curSyntax != null && curSyntax != scopeSyntax)
{
switch (curSyntax.Kind())
{
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
return true;
}
curSyntax = curSyntax.Parent;
}
return false;
}
public override BoundNode VisitLambda(BoundLambda node)
{
// these nodes have been handled in the context of the enclosing anonymous method conversion.
throw ExceptionUtilities.Unreachable;
}
#endregion
#if CHECK_LOCALS
/// <summary>
/// Ensure that local variables are always in scope where used in bound trees
/// </summary>
/// <param name="node"></param>
static partial void CheckLocalsDefined(BoundNode node)
{
LocalsDefinedScanner.INSTANCE.Visit(node);
}
class LocalsDefinedScanner : BoundTreeWalker
{
internal static LocalsDefinedScanner INSTANCE = new LocalsDefinedScanner();
HashSet<Symbol> localsDefined = new HashSet<Symbol>();
public override BoundNode VisitLocal(BoundLocal node)
{
Debug.Assert(node.LocalSymbol.IsConst || localsDefined.Contains(node.LocalSymbol));
return base.VisitLocal(node);
}
public override BoundNode VisitSequence(BoundSequence node)
{
try
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Add(l);
return base.VisitSequence(node);
}
finally
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Remove(l);
}
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
try
{
if ((object)node.LocalOpt != null) localsDefined.Add(node.LocalOpt);
return base.VisitCatchBlock(node);
}
finally
{
if ((object)node.LocalOpt != null) localsDefined.Remove(node.LocalOpt);
}
}
public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitSwitchStatement(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
public override BoundNode VisitBlock(BoundBlock node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitBlock(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
}
#endif
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicMoveDeclarationNearReferenceService.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.MoveDeclarationNearReference
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.MoveDeclarationNearReference
<ExportLanguageService(GetType(IMoveDeclarationNearReferenceService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicMoveDeclarationNearReferenceService
Inherits AbstractMoveDeclarationNearReferenceService(Of
VisualBasicMoveDeclarationNearReferenceService,
StatementSyntax,
LocalDeclarationStatementSyntax,
VariableDeclaratorSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function IsMeaningfulBlock(node As SyntaxNode) As Boolean
Return TypeOf node Is LambdaExpressionSyntax OrElse
TypeOf node Is ForOrForEachBlockSyntax OrElse
TypeOf node Is WhileStatementSyntax OrElse
TypeOf node Is DoStatementSyntax OrElse
TypeOf node Is LoopStatementSyntax
End Function
Protected Overrides Function GetVariableDeclaratorSymbolNode(variableDeclarator As VariableDeclaratorSyntax) As SyntaxNode
Return variableDeclarator.Names(0)
End Function
Protected Overrides Function IsValidVariableDeclarator(variableDeclarator As VariableDeclaratorSyntax) As Boolean
Return variableDeclarator.Names.Count = 1
End Function
Protected Overrides Function GetIdentifierOfVariableDeclarator(variableDeclarator As VariableDeclaratorSyntax) As SyntaxToken
Return variableDeclarator.Names(0).Identifier
End Function
Protected Overrides Function TypesAreCompatibleAsync(document As Document, localSymbol As ILocalSymbol, declarationStatement As LocalDeclarationStatementSyntax, right As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Boolean)
Return SpecializedTasks.True
End Function
Protected Overrides Function CanMoveToBlock(localSymbol As ILocalSymbol, currentBlock As SyntaxNode, destinationBlock As SyntaxNode) As Boolean
Return 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 System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.MoveDeclarationNearReference
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.MoveDeclarationNearReference
<ExportLanguageService(GetType(IMoveDeclarationNearReferenceService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicMoveDeclarationNearReferenceService
Inherits AbstractMoveDeclarationNearReferenceService(Of
VisualBasicMoveDeclarationNearReferenceService,
StatementSyntax,
LocalDeclarationStatementSyntax,
VariableDeclaratorSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function IsMeaningfulBlock(node As SyntaxNode) As Boolean
Return TypeOf node Is LambdaExpressionSyntax OrElse
TypeOf node Is ForOrForEachBlockSyntax OrElse
TypeOf node Is WhileStatementSyntax OrElse
TypeOf node Is DoStatementSyntax OrElse
TypeOf node Is LoopStatementSyntax
End Function
Protected Overrides Function GetVariableDeclaratorSymbolNode(variableDeclarator As VariableDeclaratorSyntax) As SyntaxNode
Return variableDeclarator.Names(0)
End Function
Protected Overrides Function IsValidVariableDeclarator(variableDeclarator As VariableDeclaratorSyntax) As Boolean
Return variableDeclarator.Names.Count = 1
End Function
Protected Overrides Function GetIdentifierOfVariableDeclarator(variableDeclarator As VariableDeclaratorSyntax) As SyntaxToken
Return variableDeclarator.Names(0).Identifier
End Function
Protected Overrides Function TypesAreCompatibleAsync(document As Document, localSymbol As ILocalSymbol, declarationStatement As LocalDeclarationStatementSyntax, right As SyntaxNode, cancellationToken As CancellationToken) As Task(Of Boolean)
Return SpecializedTasks.True
End Function
Protected Overrides Function CanMoveToBlock(localSymbol As ILocalSymbol, currentBlock As SyntaxNode, destinationBlock As SyntaxNode) As Boolean
Return True
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/CSharp/Portable/Syntax/SyntaxNormalizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
internal class SyntaxNormalizer : CSharpSyntaxRewriter
{
private readonly TextSpan _consideredSpan;
private readonly int _initialDepth;
private readonly string _indentWhitespace;
private readonly bool _useElasticTrivia;
private readonly SyntaxTrivia _eolTrivia;
private bool _isInStructuredTrivia;
private SyntaxToken _previousToken;
private bool _afterLineBreak;
private bool _afterIndentation;
private bool _inSingleLineInterpolation;
// CONSIDER: if we become concerned about space, we shouldn't actually need any
// of the values between indentations[0] and indentations[initialDepth] (exclusive).
private ArrayBuilder<SyntaxTrivia>? _indentations;
private SyntaxNormalizer(TextSpan consideredSpan, int initialDepth, string indentWhitespace, string eolWhitespace, bool useElasticTrivia)
: base(visitIntoStructuredTrivia: true)
{
_consideredSpan = consideredSpan;
_initialDepth = initialDepth;
_indentWhitespace = indentWhitespace;
_useElasticTrivia = useElasticTrivia;
_eolTrivia = useElasticTrivia ? SyntaxFactory.ElasticEndOfLine(eolWhitespace) : SyntaxFactory.EndOfLine(eolWhitespace);
_afterLineBreak = true;
}
internal static TNode Normalize<TNode>(TNode node, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false)
where TNode : SyntaxNode
{
var normalizer = new SyntaxNormalizer(node.FullSpan, GetDeclarationDepth(node), indentWhitespace, eolWhitespace, useElasticTrivia);
var result = (TNode)normalizer.Visit(node);
normalizer.Free();
return result;
}
internal static SyntaxToken Normalize(SyntaxToken token, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false)
{
var normalizer = new SyntaxNormalizer(token.FullSpan, GetDeclarationDepth(token), indentWhitespace, eolWhitespace, useElasticTrivia);
var result = normalizer.VisitToken(token);
normalizer.Free();
return result;
}
internal static SyntaxTriviaList Normalize(SyntaxTriviaList trivia, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false)
{
var normalizer = new SyntaxNormalizer(trivia.FullSpan, GetDeclarationDepth(trivia.Token), indentWhitespace, eolWhitespace, useElasticTrivia);
var result = normalizer.RewriteTrivia(
trivia,
GetDeclarationDepth((SyntaxToken)trivia.ElementAt(0).Token),
isTrailing: false,
indentAfterLineBreak: false,
mustHaveSeparator: false,
lineBreaksAfter: 0);
normalizer.Free();
return result;
}
private void Free()
{
if (_indentations != null)
{
_indentations.Free();
}
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.None || (token.IsMissing && token.FullWidth == 0))
{
return token;
}
try
{
var tk = token;
var depth = GetDeclarationDepth(token);
tk = tk.WithLeadingTrivia(RewriteTrivia(
token.LeadingTrivia,
depth,
isTrailing: false,
indentAfterLineBreak: NeedsIndentAfterLineBreak(token),
mustHaveSeparator: false,
lineBreaksAfter: 0));
var nextToken = this.GetNextRelevantToken(token);
_afterLineBreak = IsLineBreak(token);
_afterIndentation = false;
var lineBreaksAfter = LineBreaksAfter(token, nextToken);
var needsSeparatorAfter = NeedsSeparator(token, nextToken);
tk = tk.WithTrailingTrivia(RewriteTrivia(
token.TrailingTrivia,
depth,
isTrailing: true,
indentAfterLineBreak: false,
mustHaveSeparator: needsSeparatorAfter,
lineBreaksAfter: lineBreaksAfter));
return tk;
}
finally
{
// to help debugging
_previousToken = token;
}
}
private SyntaxToken GetNextRelevantToken(SyntaxToken token)
{
// get next token, skipping zero width tokens except for end-of-directive tokens
var nextToken = token.GetNextToken(
t => SyntaxToken.NonZeroWidth(t) || t.Kind() == SyntaxKind.EndOfDirectiveToken,
t => t.Kind() == SyntaxKind.SkippedTokensTrivia);
if (_consideredSpan.Contains(nextToken.FullSpan))
{
return nextToken;
}
else
{
return default(SyntaxToken);
}
}
private SyntaxTrivia GetIndentation(int count)
{
count = Math.Max(count - _initialDepth, 0);
int capacity = count + 1;
if (_indentations == null)
{
_indentations = ArrayBuilder<SyntaxTrivia>.GetInstance(capacity);
}
else
{
_indentations.EnsureCapacity(capacity);
}
// grow indentation collection if necessary
for (int i = _indentations.Count; i <= count; i++)
{
string text = i == 0
? ""
: _indentations[i - 1].ToString() + _indentWhitespace;
_indentations.Add(_useElasticTrivia ? SyntaxFactory.ElasticWhitespace(text) : SyntaxFactory.Whitespace(text));
}
return _indentations[count];
}
private static bool NeedsIndentAfterLineBreak(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.EndOfFileToken);
}
private int LineBreaksAfter(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (_inSingleLineInterpolation)
{
return 0;
}
if (currentToken.IsKind(SyntaxKind.EndOfDirectiveToken))
{
return 1;
}
if (nextToken.Kind() == SyntaxKind.None)
{
return 0;
}
// none of the following tests currently have meaning for structured trivia
if (_isInStructuredTrivia)
{
return 0;
}
if (nextToken.IsKind(SyntaxKind.CloseBraceToken) &&
IsAccessorListWithoutAccessorsWithBlockBody(currentToken.Parent?.Parent))
{
return 0;
}
switch (currentToken.Kind())
{
case SyntaxKind.None:
return 0;
case SyntaxKind.OpenBraceToken:
return LineBreaksAfterOpenBrace(currentToken, nextToken);
case SyntaxKind.FinallyKeyword:
return 1;
case SyntaxKind.CloseBraceToken:
return LineBreaksAfterCloseBrace(currentToken, nextToken);
case SyntaxKind.CloseParenToken:
if (currentToken.Parent is PositionalPatternClauseSyntax)
{
//don't break inside a recursive pattern
return 0;
}
// Note: the `where` case handles constraints on method declarations
// and also `where` clauses (consistently with other LINQ cases below)
return (((currentToken.Parent is StatementSyntax) && nextToken.Parent != currentToken.Parent)
|| nextToken.Kind() == SyntaxKind.OpenBraceToken
|| nextToken.Kind() == SyntaxKind.WhereKeyword) ? 1 : 0;
case SyntaxKind.CloseBracketToken:
if (currentToken.Parent is AttributeListSyntax && !(currentToken.Parent.Parent is ParameterSyntax))
{
return 1;
}
break;
case SyntaxKind.SemicolonToken:
return LineBreaksAfterSemicolon(currentToken, nextToken);
case SyntaxKind.CommaToken:
return currentToken.Parent is EnumDeclarationSyntax or SwitchExpressionSyntax ? 1 : 0;
case SyntaxKind.ElseKeyword:
return nextToken.Kind() != SyntaxKind.IfKeyword ? 1 : 0;
case SyntaxKind.ColonToken:
if (currentToken.Parent is LabeledStatementSyntax || currentToken.Parent is SwitchLabelSyntax)
{
return 1;
}
break;
case SyntaxKind.SwitchKeyword when currentToken.Parent is SwitchExpressionSyntax:
return 1;
}
if ((nextToken.IsKind(SyntaxKind.FromKeyword) && nextToken.Parent.IsKind(SyntaxKind.FromClause)) ||
(nextToken.IsKind(SyntaxKind.LetKeyword) && nextToken.Parent.IsKind(SyntaxKind.LetClause)) ||
(nextToken.IsKind(SyntaxKind.WhereKeyword) && nextToken.Parent.IsKind(SyntaxKind.WhereClause)) ||
(nextToken.IsKind(SyntaxKind.JoinKeyword) && nextToken.Parent.IsKind(SyntaxKind.JoinClause)) ||
(nextToken.IsKind(SyntaxKind.JoinKeyword) && nextToken.Parent.IsKind(SyntaxKind.JoinIntoClause)) ||
(nextToken.IsKind(SyntaxKind.OrderByKeyword) && nextToken.Parent.IsKind(SyntaxKind.OrderByClause)) ||
(nextToken.IsKind(SyntaxKind.SelectKeyword) && nextToken.Parent.IsKind(SyntaxKind.SelectClause)) ||
(nextToken.IsKind(SyntaxKind.GroupKeyword) && nextToken.Parent.IsKind(SyntaxKind.GroupClause)))
{
return 1;
}
switch (nextToken.Kind())
{
case SyntaxKind.OpenBraceToken:
return LineBreaksBeforeOpenBrace(nextToken);
case SyntaxKind.CloseBraceToken:
return LineBreaksBeforeCloseBrace(nextToken);
case SyntaxKind.ElseKeyword:
case SyntaxKind.FinallyKeyword:
return 1;
case SyntaxKind.OpenBracketToken:
return (nextToken.Parent is AttributeListSyntax && !(nextToken.Parent.Parent is ParameterSyntax)) ? 1 : 0;
case SyntaxKind.WhereKeyword:
return currentToken.Parent is TypeParameterListSyntax ? 1 : 0;
}
return 0;
}
private static bool IsAccessorListWithoutAccessorsWithBlockBody(SyntaxNode? node)
=> node is AccessorListSyntax accessorList &&
accessorList.Accessors.All(a => a.Body == null);
private static bool IsAccessorListFollowedByInitializer([NotNullWhen(true)] SyntaxNode? node)
=> node is AccessorListSyntax accessorList &&
node.Parent is PropertyDeclarationSyntax property &&
property.Initializer != null;
private static int LineBreaksBeforeOpenBrace(SyntaxToken openBraceToken)
{
Debug.Assert(openBraceToken.IsKind(SyntaxKind.OpenBraceToken));
if (openBraceToken.Parent.IsKind(SyntaxKind.Interpolation) ||
openBraceToken.Parent is InitializerExpressionSyntax or PropertyPatternClauseSyntax ||
IsAccessorListWithoutAccessorsWithBlockBody(openBraceToken.Parent))
{
return 0;
}
else
{
return 1;
}
}
private static int LineBreaksBeforeCloseBrace(SyntaxToken closeBraceToken)
{
Debug.Assert(closeBraceToken.IsKind(SyntaxKind.CloseBraceToken));
if (closeBraceToken.Parent.IsKind(SyntaxKind.Interpolation) ||
closeBraceToken.Parent is InitializerExpressionSyntax or PropertyPatternClauseSyntax)
{
return 0;
}
else
{
return 1;
}
}
private static int LineBreaksAfterOpenBrace(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (currentToken.Parent is InitializerExpressionSyntax or PropertyPatternClauseSyntax ||
currentToken.Parent.IsKind(SyntaxKind.Interpolation) ||
IsAccessorListWithoutAccessorsWithBlockBody(currentToken.Parent))
{
return 0;
}
else
{
return 1;
}
}
private static int LineBreaksAfterCloseBrace(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (currentToken.Parent is InitializerExpressionSyntax or SwitchExpressionSyntax or PropertyPatternClauseSyntax ||
currentToken.Parent.IsKind(SyntaxKind.Interpolation) ||
currentToken.Parent?.Parent is AnonymousFunctionExpressionSyntax ||
IsAccessorListFollowedByInitializer(currentToken.Parent))
{
return 0;
}
var kind = nextToken.Kind();
switch (kind)
{
case SyntaxKind.EndOfFileToken:
case SyntaxKind.CloseBraceToken:
case SyntaxKind.CatchKeyword:
case SyntaxKind.FinallyKeyword:
case SyntaxKind.ElseKeyword:
return 1;
default:
if (kind == SyntaxKind.WhileKeyword &&
nextToken.Parent.IsKind(SyntaxKind.DoStatement))
{
return 1;
}
else
{
return 2;
}
}
}
private static int LineBreaksAfterSemicolon(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (currentToken.Parent.IsKind(SyntaxKind.ForStatement))
{
return 0;
}
else if (nextToken.Kind() == SyntaxKind.CloseBraceToken)
{
return 1;
}
else if (currentToken.Parent.IsKind(SyntaxKind.UsingDirective))
{
return nextToken.Parent.IsKind(SyntaxKind.UsingDirective) ? 1 : 2;
}
else if (currentToken.Parent.IsKind(SyntaxKind.ExternAliasDirective))
{
return nextToken.Parent.IsKind(SyntaxKind.ExternAliasDirective) ? 1 : 2;
}
else if (currentToken.Parent is AccessorDeclarationSyntax &&
IsAccessorListWithoutAccessorsWithBlockBody(currentToken.Parent.Parent))
{
return 0;
}
else
{
return 1;
}
}
private static bool NeedsSeparatorForPropertyPattern(SyntaxToken token, SyntaxToken next)
{
PropertyPatternClauseSyntax? propPattern;
if (token.Parent.IsKind(SyntaxKind.PropertyPatternClause))
{
propPattern = (PropertyPatternClauseSyntax)token.Parent;
}
else if (next.Parent.IsKind(SyntaxKind.PropertyPatternClause))
{
propPattern = (PropertyPatternClauseSyntax)next.Parent;
}
else
{
return false;
}
var tokenIsOpenBrace = token.IsKind(SyntaxKind.OpenBraceToken);
var nextIsOpenBrace = next.IsKind(SyntaxKind.OpenBraceToken);
var tokenIsCloseBrace = token.IsKind(SyntaxKind.CloseBraceToken);
var nextIsCloseBrace = next.IsKind(SyntaxKind.CloseBraceToken);
//inner
if (tokenIsOpenBrace)
{
return true;
}
if (nextIsCloseBrace)
{
return true;
}
if (propPattern.Parent is RecursivePatternSyntax rps)
{
//outer
if (nextIsOpenBrace)
{
if (rps.Type != null || rps.PositionalPatternClause != null)
{
return true;
}
else
{
return false;
}
}
if (tokenIsCloseBrace)
{
if (rps.Designation is null)
{
return false;
}
else
{
return true;
}
}
}
return false;
}
private static bool NeedsSeparatorForPositionalPattern(SyntaxToken token, SyntaxToken next)
{
PositionalPatternClauseSyntax? posPattern;
if (token.Parent.IsKind(SyntaxKind.PositionalPatternClause))
{
posPattern = (PositionalPatternClauseSyntax)token.Parent;
}
else if (next.Parent.IsKind(SyntaxKind.PositionalPatternClause))
{
posPattern = (PositionalPatternClauseSyntax)next.Parent;
}
else
{
return false;
}
var tokenIsOpenParen = token.IsKind(SyntaxKind.OpenParenToken);
var nextIsOpenParen = next.IsKind(SyntaxKind.OpenParenToken);
var tokenIsCloseParen = token.IsKind(SyntaxKind.CloseParenToken);
var nextIsCloseParen = next.IsKind(SyntaxKind.CloseParenToken);
//inner
if (tokenIsOpenParen)
{
return false;
}
if (nextIsCloseParen)
{
return false;
}
if (posPattern.Parent is RecursivePatternSyntax rps)
{
//outer
if (nextIsOpenParen)
{
if (rps.Type != null)
{
return true;
}
else
{
return false;
}
}
if (tokenIsCloseParen)
{
if (rps.PropertyPatternClause is not null)
{
return false;
}
if (rps.Designation is null)
{
return false;
}
else
{
return true;
}
}
}
return false;
}
private static bool NeedsSeparator(SyntaxToken token, SyntaxToken next)
{
if (token.Parent == null || next.Parent == null)
{
return false;
}
if (IsAccessorListWithoutAccessorsWithBlockBody(next.Parent) ||
IsAccessorListWithoutAccessorsWithBlockBody(next.Parent.Parent))
{
// when the accessors are formatted inline, the separator is needed
// unless there is a semicolon. For example: "{ get; set; }"
return !next.IsKind(SyntaxKind.SemicolonToken);
}
if (IsXmlTextToken(token.Kind()) || IsXmlTextToken(next.Kind()))
{
return false;
}
if (next.Kind() == SyntaxKind.EndOfDirectiveToken)
{
// In a directive, there's often no token between the directive keyword and
// the end-of-directive, so we may need a separator.
return IsKeyword(token.Kind()) && next.LeadingWidth > 0;
}
if ((token.Parent is AssignmentExpressionSyntax && AssignmentTokenNeedsSeparator(token.Kind())) ||
(next.Parent is AssignmentExpressionSyntax && AssignmentTokenNeedsSeparator(next.Kind())) ||
(token.Parent is BinaryExpressionSyntax && BinaryTokenNeedsSeparator(token.Kind())) ||
(next.Parent is BinaryExpressionSyntax && BinaryTokenNeedsSeparator(next.Kind())))
{
return true;
}
if (token.IsKind(SyntaxKind.GreaterThanToken) && token.Parent.IsKind(SyntaxKind.TypeArgumentList))
{
if (!SyntaxFacts.IsPunctuation(next.Kind()))
{
return true;
}
}
if (token.IsKind(SyntaxKind.GreaterThanToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList))
{
return true;
}
if (token.IsKind(SyntaxKind.CommaToken) &&
!next.IsKind(SyntaxKind.CommaToken) &&
!token.Parent.IsKind(SyntaxKind.EnumDeclaration))
{
return true;
}
if (token.Kind() == SyntaxKind.SemicolonToken
&& !(next.Kind() == SyntaxKind.SemicolonToken || next.Kind() == SyntaxKind.CloseParenToken))
{
return true;
}
if (next.IsKind(SyntaxKind.SwitchKeyword) && next.Parent is SwitchExpressionSyntax)
{
return true;
}
if (token.IsKind(SyntaxKind.QuestionToken)
&& (token.Parent.IsKind(SyntaxKind.ConditionalExpression) || token.Parent is TypeSyntax)
&& !token.Parent.Parent.IsKind(SyntaxKind.TypeArgumentList))
{
return true;
}
if (token.IsKind(SyntaxKind.ColonToken))
{
return !token.Parent.IsKind(SyntaxKind.InterpolationFormatClause) &&
!token.Parent.IsKind(SyntaxKind.XmlPrefix);
}
if (next.IsKind(SyntaxKind.ColonToken))
{
if (next.Parent.IsKind(SyntaxKind.BaseList) ||
next.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause) ||
next.Parent is ConstructorInitializerSyntax)
{
return true;
}
}
if (token.IsKind(SyntaxKind.CloseBracketToken) && IsWord(next.Kind()))
{
return true;
}
// We don't want to add extra space after cast, we want space only after tuple
if (token.IsKind(SyntaxKind.CloseParenToken) && IsWord(next.Kind()) && token.Parent.IsKind(SyntaxKind.TupleType) == true)
{
return true;
}
if ((next.IsKind(SyntaxKind.QuestionToken) || next.IsKind(SyntaxKind.ColonToken))
&& (next.Parent.IsKind(SyntaxKind.ConditionalExpression)))
{
return true;
}
if (token.IsKind(SyntaxKind.EqualsToken))
{
return !token.Parent.IsKind(SyntaxKind.XmlTextAttribute);
}
if (next.IsKind(SyntaxKind.EqualsToken))
{
return !next.Parent.IsKind(SyntaxKind.XmlTextAttribute);
}
// Rules for function pointer below are taken from:
// https://github.com/dotnet/roslyn/blob/1cca63b5d8ea170f8d8e88e1574aa3ebe354c23b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs#L321-L413
if (token.Parent.IsKind(SyntaxKind.FunctionPointerType))
{
// No spacing between delegate and *
if (next.IsKind(SyntaxKind.AsteriskToken) && token.IsKind(SyntaxKind.DelegateKeyword))
{
return false;
}
// Force a space between * and the calling convention
if (token.IsKind(SyntaxKind.AsteriskToken) && next.Parent.IsKind(SyntaxKind.FunctionPointerCallingConvention))
{
switch (next.Kind())
{
case SyntaxKind.IdentifierToken:
case SyntaxKind.ManagedKeyword:
case SyntaxKind.UnmanagedKeyword:
return true;
}
}
}
if (next.Parent.IsKind(SyntaxKind.FunctionPointerParameterList) && next.IsKind(SyntaxKind.LessThanToken))
{
switch (token.Kind())
{
// No spacing between the * and < tokens if there is no calling convention
case SyntaxKind.AsteriskToken:
// No spacing between the calling convention and opening angle bracket of function pointer types:
// delegate* managed<
case SyntaxKind.ManagedKeyword:
case SyntaxKind.UnmanagedKeyword:
// No spacing between the calling convention specifier and the opening angle
// delegate* unmanaged[Cdecl]<
case SyntaxKind.CloseBracketToken when token.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList):
return false;
}
}
// No space between unmanaged and the [
// delegate* unmanaged[
if (token.Parent.IsKind(SyntaxKind.FunctionPointerCallingConvention) && next.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList) &&
next.IsKind(SyntaxKind.OpenBracketToken))
{
return false;
}
// Function pointer calling convention adjustments
if (next.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList) && token.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList))
{
if (next.IsKind(SyntaxKind.IdentifierToken))
{
if (token.IsKind(SyntaxKind.OpenBracketToken))
{
return false;
}
// Space after the ,
// unmanaged[Cdecl, Thiscall
else if (token.IsKind(SyntaxKind.CommaToken))
{
return true;
}
}
// No space between identifier and comma
// unmanaged[Cdecl,
if (next.IsKind(SyntaxKind.CommaToken))
{
return false;
}
// No space before the ]
// unmanaged[Cdecl]
if (next.IsKind(SyntaxKind.CloseBracketToken))
{
return false;
}
}
// No space after the < in function pointer parameter lists
// delegate*<void
if (token.IsKind(SyntaxKind.LessThanToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList))
{
return false;
}
// No space before the > in function pointer parameter lists
// delegate*<void>
if (next.IsKind(SyntaxKind.GreaterThanToken) && next.Parent.IsKind(SyntaxKind.FunctionPointerParameterList))
{
return false;
}
if (token.IsKind(SyntaxKind.EqualsGreaterThanToken) || next.IsKind(SyntaxKind.EqualsGreaterThanToken))
{
return true;
}
// Can happen in directives (e.g. #line 1 "file")
if (SyntaxFacts.IsLiteral(token.Kind()) && SyntaxFacts.IsLiteral(next.Kind()))
{
return true;
}
// No space before an asterisk that's part of a PointerTypeSyntax.
if (next.IsKind(SyntaxKind.AsteriskToken) && next.Parent is PointerTypeSyntax)
{
return false;
}
// The last asterisk of a pointer declaration should be followed by a space.
if (token.IsKind(SyntaxKind.AsteriskToken) && token.Parent is PointerTypeSyntax &&
(next.IsKind(SyntaxKind.IdentifierToken) || next.Parent.IsKind(SyntaxKind.IndexerDeclaration)))
{
return true;
}
if (IsKeyword(token.Kind()))
{
if (!next.IsKind(SyntaxKind.ColonToken) &&
!next.IsKind(SyntaxKind.DotToken) &&
!next.IsKind(SyntaxKind.QuestionToken) &&
!next.IsKind(SyntaxKind.SemicolonToken) &&
!next.IsKind(SyntaxKind.OpenBracketToken) &&
(!next.IsKind(SyntaxKind.OpenParenToken) || KeywordNeedsSeparatorBeforeOpenParen(token.Kind()) || next.Parent.IsKind(SyntaxKind.TupleType)) &&
!next.IsKind(SyntaxKind.CloseParenToken) &&
!next.IsKind(SyntaxKind.CloseBraceToken) &&
!next.IsKind(SyntaxKind.ColonColonToken) &&
!next.IsKind(SyntaxKind.GreaterThanToken) &&
!next.IsKind(SyntaxKind.CommaToken))
{
return true;
}
}
if (IsWord(token.Kind()) && IsWord(next.Kind()))
{
return true;
}
else if (token.Width > 1 && next.Width > 1)
{
var tokenLastChar = token.Text.Last();
var nextFirstChar = next.Text.First();
if (tokenLastChar == nextFirstChar && TokenCharacterCanBeDoubled(tokenLastChar))
{
return true;
}
}
if (token.Parent is RelationalPatternSyntax)
{
//>, >=, <, <=
return true;
}
switch (next.Kind())
{
case SyntaxKind.AndKeyword:
case SyntaxKind.OrKeyword:
return true;
}
switch (token.Kind())
{
case SyntaxKind.AndKeyword:
case SyntaxKind.OrKeyword:
case SyntaxKind.NotKeyword:
return true;
}
if (NeedsSeparatorForPropertyPattern(token, next))
{
return true;
}
if (NeedsSeparatorForPositionalPattern(token, next))
{
return true;
}
return false;
}
private static bool KeywordNeedsSeparatorBeforeOpenParen(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.NewKeyword:
case SyntaxKind.BaseKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.CheckedKeyword:
case SyntaxKind.UncheckedKeyword:
case SyntaxKind.SizeOfKeyword:
case SyntaxKind.ArgListKeyword:
return false;
default:
return true;
}
}
private static bool IsXmlTextToken(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.XmlTextLiteralNewLineToken:
case SyntaxKind.XmlTextLiteralToken:
return true;
default:
return false;
}
}
private static bool BinaryTokenNeedsSeparator(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return false;
default:
return SyntaxFacts.GetBinaryExpression(kind) != SyntaxKind.None;
}
}
private static bool AssignmentTokenNeedsSeparator(SyntaxKind kind)
{
return SyntaxFacts.GetAssignmentExpression(kind) != SyntaxKind.None;
}
private SyntaxTriviaList RewriteTrivia(
SyntaxTriviaList triviaList,
int depth,
bool isTrailing,
bool indentAfterLineBreak,
bool mustHaveSeparator,
int lineBreaksAfter)
{
ArrayBuilder<SyntaxTrivia> currentTriviaList = ArrayBuilder<SyntaxTrivia>.GetInstance(triviaList.Count);
try
{
foreach (var trivia in triviaList)
{
if (trivia.IsKind(SyntaxKind.WhitespaceTrivia) ||
trivia.IsKind(SyntaxKind.EndOfLineTrivia) ||
trivia.FullWidth == 0)
{
continue;
}
var needsSeparator =
(currentTriviaList.Count > 0 && NeedsSeparatorBetween(currentTriviaList.Last())) ||
(currentTriviaList.Count == 0 && isTrailing);
var needsLineBreak = NeedsLineBreakBefore(trivia, isTrailing)
|| (currentTriviaList.Count > 0 && NeedsLineBreakBetween(currentTriviaList.Last(), trivia, isTrailing));
if (needsLineBreak && !_afterLineBreak)
{
currentTriviaList.Add(GetEndOfLine());
_afterLineBreak = true;
_afterIndentation = false;
}
if (_afterLineBreak)
{
if (!_afterIndentation && NeedsIndentAfterLineBreak(trivia))
{
currentTriviaList.Add(this.GetIndentation(GetDeclarationDepth(trivia)));
_afterIndentation = true;
}
}
else if (needsSeparator)
{
currentTriviaList.Add(GetSpace());
_afterLineBreak = false;
_afterIndentation = false;
}
if (trivia.HasStructure)
{
var tr = this.VisitStructuredTrivia(trivia);
currentTriviaList.Add(tr);
}
else if (trivia.IsKind(SyntaxKind.DocumentationCommentExteriorTrivia))
{
// recreate exterior to remove any leading whitespace
currentTriviaList.Add(s_trimmedDocCommentExterior);
}
else
{
currentTriviaList.Add(trivia);
}
if (NeedsLineBreakAfter(trivia, isTrailing)
&& (currentTriviaList.Count == 0 || !EndsInLineBreak(currentTriviaList.Last())))
{
currentTriviaList.Add(GetEndOfLine());
_afterLineBreak = true;
_afterIndentation = false;
}
}
if (lineBreaksAfter > 0)
{
if (currentTriviaList.Count > 0
&& EndsInLineBreak(currentTriviaList.Last()))
{
lineBreaksAfter--;
}
for (int i = 0; i < lineBreaksAfter; i++)
{
currentTriviaList.Add(GetEndOfLine());
_afterLineBreak = true;
_afterIndentation = false;
}
}
else if (indentAfterLineBreak && _afterLineBreak && !_afterIndentation)
{
currentTriviaList.Add(this.GetIndentation(depth));
_afterIndentation = true;
}
else if (mustHaveSeparator)
{
currentTriviaList.Add(GetSpace());
_afterLineBreak = false;
_afterIndentation = false;
}
if (currentTriviaList.Count == 0)
{
return default(SyntaxTriviaList);
}
else if (currentTriviaList.Count == 1)
{
return SyntaxFactory.TriviaList(currentTriviaList.First());
}
else
{
return SyntaxFactory.TriviaList(currentTriviaList);
}
}
finally
{
currentTriviaList.Free();
}
}
private static readonly SyntaxTrivia s_trimmedDocCommentExterior = SyntaxFactory.DocumentationCommentExterior("///");
private SyntaxTrivia GetSpace()
{
return _useElasticTrivia ? SyntaxFactory.ElasticSpace : SyntaxFactory.Space;
}
private SyntaxTrivia GetEndOfLine()
{
return _eolTrivia;
}
private SyntaxTrivia VisitStructuredTrivia(SyntaxTrivia trivia)
{
bool oldIsInStructuredTrivia = _isInStructuredTrivia;
_isInStructuredTrivia = true;
SyntaxToken oldPreviousToken = _previousToken;
_previousToken = default(SyntaxToken);
SyntaxTrivia result = VisitTrivia(trivia);
_isInStructuredTrivia = oldIsInStructuredTrivia;
_previousToken = oldPreviousToken;
return result;
}
private static bool NeedsSeparatorBetween(SyntaxTrivia trivia)
{
switch (trivia.Kind())
{
case SyntaxKind.None:
case SyntaxKind.WhitespaceTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
return false;
default:
return !SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
}
}
private static bool NeedsLineBreakBetween(SyntaxTrivia trivia, SyntaxTrivia next, bool isTrailingTrivia)
{
return NeedsLineBreakAfter(trivia, isTrailingTrivia)
|| NeedsLineBreakBefore(next, isTrailingTrivia);
}
private static bool NeedsLineBreakBefore(SyntaxTrivia trivia, bool isTrailingTrivia)
{
var kind = trivia.Kind();
switch (kind)
{
case SyntaxKind.DocumentationCommentExteriorTrivia:
return !isTrailingTrivia;
default:
return SyntaxFacts.IsPreprocessorDirective(kind);
}
}
private static bool NeedsLineBreakAfter(SyntaxTrivia trivia, bool isTrailingTrivia)
{
var kind = trivia.Kind();
switch (kind)
{
case SyntaxKind.SingleLineCommentTrivia:
return true;
case SyntaxKind.MultiLineCommentTrivia:
return !isTrailingTrivia;
default:
return SyntaxFacts.IsPreprocessorDirective(kind);
}
}
private static bool NeedsIndentAfterLineBreak(SyntaxTrivia trivia)
{
switch (trivia.Kind())
{
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
case SyntaxKind.SingleLineDocumentationCommentTrivia:
case SyntaxKind.MultiLineDocumentationCommentTrivia:
return true;
default:
return false;
}
}
private static bool IsLineBreak(SyntaxToken token)
{
return token.Kind() == SyntaxKind.XmlTextLiteralNewLineToken;
}
private static bool EndsInLineBreak(SyntaxTrivia trivia)
{
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return true;
}
if (trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia || trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
var text = trivia.ToFullString();
return text.Length > 0 && SyntaxFacts.IsNewLine(text.Last());
}
if (trivia.HasStructure)
{
var node = trivia.GetStructure()!;
var trailing = node.GetTrailingTrivia();
if (trailing.Count > 0)
{
return EndsInLineBreak(trailing.Last());
}
else
{
return IsLineBreak(node.GetLastToken());
}
}
return false;
}
private static bool IsWord(SyntaxKind kind)
{
return kind == SyntaxKind.IdentifierToken || IsKeyword(kind);
}
private static bool IsKeyword(SyntaxKind kind)
{
return SyntaxFacts.IsKeywordKind(kind) || SyntaxFacts.IsPreprocessorKeyword(kind);
}
private static bool TokenCharacterCanBeDoubled(char c)
{
switch (c)
{
case '+':
case '-':
case '<':
case ':':
case '?':
case '=':
case '"':
return true;
default:
return false;
}
}
private static int GetDeclarationDepth(SyntaxToken token)
{
return GetDeclarationDepth(token.Parent);
}
private static int GetDeclarationDepth(SyntaxTrivia trivia)
{
if (SyntaxFacts.IsPreprocessorDirective(trivia.Kind()))
{
return 0;
}
return GetDeclarationDepth((SyntaxToken)trivia.Token);
}
private static int GetDeclarationDepth(SyntaxNode? node)
{
if (node != null)
{
if (node.IsStructuredTrivia)
{
var tr = ((StructuredTriviaSyntax)node).ParentTrivia;
return GetDeclarationDepth(tr);
}
else if (node.Parent != null)
{
if (node.Parent.IsKind(SyntaxKind.CompilationUnit))
{
return 0;
}
int parentDepth = GetDeclarationDepth(node.Parent);
if (node.Parent.Kind() is SyntaxKind.GlobalStatement or SyntaxKind.FileScopedNamespaceDeclaration)
{
return parentDepth;
}
if (node.IsKind(SyntaxKind.IfStatement) && node.Parent.IsKind(SyntaxKind.ElseClause))
{
return parentDepth;
}
if (node.Parent is BlockSyntax ||
(node is StatementSyntax && !(node is BlockSyntax)))
{
// all nested statements are indented one level
return parentDepth + 1;
}
if (node is MemberDeclarationSyntax ||
node is AccessorDeclarationSyntax ||
node is TypeParameterConstraintClauseSyntax ||
node is SwitchSectionSyntax ||
node is SwitchExpressionArmSyntax ||
node is UsingDirectiveSyntax ||
node is ExternAliasDirectiveSyntax ||
node is QueryExpressionSyntax ||
node is QueryContinuationSyntax)
{
return parentDepth + 1;
}
return parentDepth;
}
}
return 0;
}
public override SyntaxNode? VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node)
{
if (node.StringStartToken.Kind() == SyntaxKind.InterpolatedStringStartToken)
{
//Just for non verbatim strings we want to make sure that the formatting of interpolations does not emit line breaks.
//See: https://github.com/dotnet/roslyn/issues/50742
//
//The flag _inSingleLineInterpolation is set to true while visiting InterpolatedStringExpressionSyntax and checked in LineBreaksAfter
//to suppress adding newlines.
var old = _inSingleLineInterpolation;
_inSingleLineInterpolation = true;
try
{
return base.VisitInterpolatedStringExpression(node);
}
finally
{
_inSingleLineInterpolation = old;
}
}
return base.VisitInterpolatedStringExpression(node);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
internal class SyntaxNormalizer : CSharpSyntaxRewriter
{
private readonly TextSpan _consideredSpan;
private readonly int _initialDepth;
private readonly string _indentWhitespace;
private readonly bool _useElasticTrivia;
private readonly SyntaxTrivia _eolTrivia;
private bool _isInStructuredTrivia;
private SyntaxToken _previousToken;
private bool _afterLineBreak;
private bool _afterIndentation;
private bool _inSingleLineInterpolation;
// CONSIDER: if we become concerned about space, we shouldn't actually need any
// of the values between indentations[0] and indentations[initialDepth] (exclusive).
private ArrayBuilder<SyntaxTrivia>? _indentations;
private SyntaxNormalizer(TextSpan consideredSpan, int initialDepth, string indentWhitespace, string eolWhitespace, bool useElasticTrivia)
: base(visitIntoStructuredTrivia: true)
{
_consideredSpan = consideredSpan;
_initialDepth = initialDepth;
_indentWhitespace = indentWhitespace;
_useElasticTrivia = useElasticTrivia;
_eolTrivia = useElasticTrivia ? SyntaxFactory.ElasticEndOfLine(eolWhitespace) : SyntaxFactory.EndOfLine(eolWhitespace);
_afterLineBreak = true;
}
internal static TNode Normalize<TNode>(TNode node, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false)
where TNode : SyntaxNode
{
var normalizer = new SyntaxNormalizer(node.FullSpan, GetDeclarationDepth(node), indentWhitespace, eolWhitespace, useElasticTrivia);
var result = (TNode)normalizer.Visit(node);
normalizer.Free();
return result;
}
internal static SyntaxToken Normalize(SyntaxToken token, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false)
{
var normalizer = new SyntaxNormalizer(token.FullSpan, GetDeclarationDepth(token), indentWhitespace, eolWhitespace, useElasticTrivia);
var result = normalizer.VisitToken(token);
normalizer.Free();
return result;
}
internal static SyntaxTriviaList Normalize(SyntaxTriviaList trivia, string indentWhitespace, string eolWhitespace, bool useElasticTrivia = false)
{
var normalizer = new SyntaxNormalizer(trivia.FullSpan, GetDeclarationDepth(trivia.Token), indentWhitespace, eolWhitespace, useElasticTrivia);
var result = normalizer.RewriteTrivia(
trivia,
GetDeclarationDepth((SyntaxToken)trivia.ElementAt(0).Token),
isTrailing: false,
indentAfterLineBreak: false,
mustHaveSeparator: false,
lineBreaksAfter: 0);
normalizer.Free();
return result;
}
private void Free()
{
if (_indentations != null)
{
_indentations.Free();
}
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
if (token.Kind() == SyntaxKind.None || (token.IsMissing && token.FullWidth == 0))
{
return token;
}
try
{
var tk = token;
var depth = GetDeclarationDepth(token);
tk = tk.WithLeadingTrivia(RewriteTrivia(
token.LeadingTrivia,
depth,
isTrailing: false,
indentAfterLineBreak: NeedsIndentAfterLineBreak(token),
mustHaveSeparator: false,
lineBreaksAfter: 0));
var nextToken = this.GetNextRelevantToken(token);
_afterLineBreak = IsLineBreak(token);
_afterIndentation = false;
var lineBreaksAfter = LineBreaksAfter(token, nextToken);
var needsSeparatorAfter = NeedsSeparator(token, nextToken);
tk = tk.WithTrailingTrivia(RewriteTrivia(
token.TrailingTrivia,
depth,
isTrailing: true,
indentAfterLineBreak: false,
mustHaveSeparator: needsSeparatorAfter,
lineBreaksAfter: lineBreaksAfter));
return tk;
}
finally
{
// to help debugging
_previousToken = token;
}
}
private SyntaxToken GetNextRelevantToken(SyntaxToken token)
{
// get next token, skipping zero width tokens except for end-of-directive tokens
var nextToken = token.GetNextToken(
t => SyntaxToken.NonZeroWidth(t) || t.Kind() == SyntaxKind.EndOfDirectiveToken,
t => t.Kind() == SyntaxKind.SkippedTokensTrivia);
if (_consideredSpan.Contains(nextToken.FullSpan))
{
return nextToken;
}
else
{
return default(SyntaxToken);
}
}
private SyntaxTrivia GetIndentation(int count)
{
count = Math.Max(count - _initialDepth, 0);
int capacity = count + 1;
if (_indentations == null)
{
_indentations = ArrayBuilder<SyntaxTrivia>.GetInstance(capacity);
}
else
{
_indentations.EnsureCapacity(capacity);
}
// grow indentation collection if necessary
for (int i = _indentations.Count; i <= count; i++)
{
string text = i == 0
? ""
: _indentations[i - 1].ToString() + _indentWhitespace;
_indentations.Add(_useElasticTrivia ? SyntaxFactory.ElasticWhitespace(text) : SyntaxFactory.Whitespace(text));
}
return _indentations[count];
}
private static bool NeedsIndentAfterLineBreak(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.EndOfFileToken);
}
private int LineBreaksAfter(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (_inSingleLineInterpolation)
{
return 0;
}
if (currentToken.IsKind(SyntaxKind.EndOfDirectiveToken))
{
return 1;
}
if (nextToken.Kind() == SyntaxKind.None)
{
return 0;
}
// none of the following tests currently have meaning for structured trivia
if (_isInStructuredTrivia)
{
return 0;
}
if (nextToken.IsKind(SyntaxKind.CloseBraceToken) &&
IsAccessorListWithoutAccessorsWithBlockBody(currentToken.Parent?.Parent))
{
return 0;
}
switch (currentToken.Kind())
{
case SyntaxKind.None:
return 0;
case SyntaxKind.OpenBraceToken:
return LineBreaksAfterOpenBrace(currentToken, nextToken);
case SyntaxKind.FinallyKeyword:
return 1;
case SyntaxKind.CloseBraceToken:
return LineBreaksAfterCloseBrace(currentToken, nextToken);
case SyntaxKind.CloseParenToken:
if (currentToken.Parent is PositionalPatternClauseSyntax)
{
//don't break inside a recursive pattern
return 0;
}
// Note: the `where` case handles constraints on method declarations
// and also `where` clauses (consistently with other LINQ cases below)
return (((currentToken.Parent is StatementSyntax) && nextToken.Parent != currentToken.Parent)
|| nextToken.Kind() == SyntaxKind.OpenBraceToken
|| nextToken.Kind() == SyntaxKind.WhereKeyword) ? 1 : 0;
case SyntaxKind.CloseBracketToken:
if (currentToken.Parent is AttributeListSyntax && !(currentToken.Parent.Parent is ParameterSyntax))
{
return 1;
}
break;
case SyntaxKind.SemicolonToken:
return LineBreaksAfterSemicolon(currentToken, nextToken);
case SyntaxKind.CommaToken:
return currentToken.Parent is EnumDeclarationSyntax or SwitchExpressionSyntax ? 1 : 0;
case SyntaxKind.ElseKeyword:
return nextToken.Kind() != SyntaxKind.IfKeyword ? 1 : 0;
case SyntaxKind.ColonToken:
if (currentToken.Parent is LabeledStatementSyntax || currentToken.Parent is SwitchLabelSyntax)
{
return 1;
}
break;
case SyntaxKind.SwitchKeyword when currentToken.Parent is SwitchExpressionSyntax:
return 1;
}
if ((nextToken.IsKind(SyntaxKind.FromKeyword) && nextToken.Parent.IsKind(SyntaxKind.FromClause)) ||
(nextToken.IsKind(SyntaxKind.LetKeyword) && nextToken.Parent.IsKind(SyntaxKind.LetClause)) ||
(nextToken.IsKind(SyntaxKind.WhereKeyword) && nextToken.Parent.IsKind(SyntaxKind.WhereClause)) ||
(nextToken.IsKind(SyntaxKind.JoinKeyword) && nextToken.Parent.IsKind(SyntaxKind.JoinClause)) ||
(nextToken.IsKind(SyntaxKind.JoinKeyword) && nextToken.Parent.IsKind(SyntaxKind.JoinIntoClause)) ||
(nextToken.IsKind(SyntaxKind.OrderByKeyword) && nextToken.Parent.IsKind(SyntaxKind.OrderByClause)) ||
(nextToken.IsKind(SyntaxKind.SelectKeyword) && nextToken.Parent.IsKind(SyntaxKind.SelectClause)) ||
(nextToken.IsKind(SyntaxKind.GroupKeyword) && nextToken.Parent.IsKind(SyntaxKind.GroupClause)))
{
return 1;
}
switch (nextToken.Kind())
{
case SyntaxKind.OpenBraceToken:
return LineBreaksBeforeOpenBrace(nextToken);
case SyntaxKind.CloseBraceToken:
return LineBreaksBeforeCloseBrace(nextToken);
case SyntaxKind.ElseKeyword:
case SyntaxKind.FinallyKeyword:
return 1;
case SyntaxKind.OpenBracketToken:
return (nextToken.Parent is AttributeListSyntax && !(nextToken.Parent.Parent is ParameterSyntax)) ? 1 : 0;
case SyntaxKind.WhereKeyword:
return currentToken.Parent is TypeParameterListSyntax ? 1 : 0;
}
return 0;
}
private static bool IsAccessorListWithoutAccessorsWithBlockBody(SyntaxNode? node)
=> node is AccessorListSyntax accessorList &&
accessorList.Accessors.All(a => a.Body == null);
private static bool IsAccessorListFollowedByInitializer([NotNullWhen(true)] SyntaxNode? node)
=> node is AccessorListSyntax accessorList &&
node.Parent is PropertyDeclarationSyntax property &&
property.Initializer != null;
private static int LineBreaksBeforeOpenBrace(SyntaxToken openBraceToken)
{
Debug.Assert(openBraceToken.IsKind(SyntaxKind.OpenBraceToken));
if (openBraceToken.Parent.IsKind(SyntaxKind.Interpolation) ||
openBraceToken.Parent is InitializerExpressionSyntax or PropertyPatternClauseSyntax ||
IsAccessorListWithoutAccessorsWithBlockBody(openBraceToken.Parent))
{
return 0;
}
else
{
return 1;
}
}
private static int LineBreaksBeforeCloseBrace(SyntaxToken closeBraceToken)
{
Debug.Assert(closeBraceToken.IsKind(SyntaxKind.CloseBraceToken));
if (closeBraceToken.Parent.IsKind(SyntaxKind.Interpolation) ||
closeBraceToken.Parent is InitializerExpressionSyntax or PropertyPatternClauseSyntax)
{
return 0;
}
else
{
return 1;
}
}
private static int LineBreaksAfterOpenBrace(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (currentToken.Parent is InitializerExpressionSyntax or PropertyPatternClauseSyntax ||
currentToken.Parent.IsKind(SyntaxKind.Interpolation) ||
IsAccessorListWithoutAccessorsWithBlockBody(currentToken.Parent))
{
return 0;
}
else
{
return 1;
}
}
private static int LineBreaksAfterCloseBrace(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (currentToken.Parent is InitializerExpressionSyntax or SwitchExpressionSyntax or PropertyPatternClauseSyntax ||
currentToken.Parent.IsKind(SyntaxKind.Interpolation) ||
currentToken.Parent?.Parent is AnonymousFunctionExpressionSyntax ||
IsAccessorListFollowedByInitializer(currentToken.Parent))
{
return 0;
}
var kind = nextToken.Kind();
switch (kind)
{
case SyntaxKind.EndOfFileToken:
case SyntaxKind.CloseBraceToken:
case SyntaxKind.CatchKeyword:
case SyntaxKind.FinallyKeyword:
case SyntaxKind.ElseKeyword:
return 1;
default:
if (kind == SyntaxKind.WhileKeyword &&
nextToken.Parent.IsKind(SyntaxKind.DoStatement))
{
return 1;
}
else
{
return 2;
}
}
}
private static int LineBreaksAfterSemicolon(SyntaxToken currentToken, SyntaxToken nextToken)
{
if (currentToken.Parent.IsKind(SyntaxKind.ForStatement))
{
return 0;
}
else if (nextToken.Kind() == SyntaxKind.CloseBraceToken)
{
return 1;
}
else if (currentToken.Parent.IsKind(SyntaxKind.UsingDirective))
{
return nextToken.Parent.IsKind(SyntaxKind.UsingDirective) ? 1 : 2;
}
else if (currentToken.Parent.IsKind(SyntaxKind.ExternAliasDirective))
{
return nextToken.Parent.IsKind(SyntaxKind.ExternAliasDirective) ? 1 : 2;
}
else if (currentToken.Parent is AccessorDeclarationSyntax &&
IsAccessorListWithoutAccessorsWithBlockBody(currentToken.Parent.Parent))
{
return 0;
}
else
{
return 1;
}
}
private static bool NeedsSeparatorForPropertyPattern(SyntaxToken token, SyntaxToken next)
{
PropertyPatternClauseSyntax? propPattern;
if (token.Parent.IsKind(SyntaxKind.PropertyPatternClause))
{
propPattern = (PropertyPatternClauseSyntax)token.Parent;
}
else if (next.Parent.IsKind(SyntaxKind.PropertyPatternClause))
{
propPattern = (PropertyPatternClauseSyntax)next.Parent;
}
else
{
return false;
}
var tokenIsOpenBrace = token.IsKind(SyntaxKind.OpenBraceToken);
var nextIsOpenBrace = next.IsKind(SyntaxKind.OpenBraceToken);
var tokenIsCloseBrace = token.IsKind(SyntaxKind.CloseBraceToken);
var nextIsCloseBrace = next.IsKind(SyntaxKind.CloseBraceToken);
//inner
if (tokenIsOpenBrace)
{
return true;
}
if (nextIsCloseBrace)
{
return true;
}
if (propPattern.Parent is RecursivePatternSyntax rps)
{
//outer
if (nextIsOpenBrace)
{
if (rps.Type != null || rps.PositionalPatternClause != null)
{
return true;
}
else
{
return false;
}
}
if (tokenIsCloseBrace)
{
if (rps.Designation is null)
{
return false;
}
else
{
return true;
}
}
}
return false;
}
private static bool NeedsSeparatorForPositionalPattern(SyntaxToken token, SyntaxToken next)
{
PositionalPatternClauseSyntax? posPattern;
if (token.Parent.IsKind(SyntaxKind.PositionalPatternClause))
{
posPattern = (PositionalPatternClauseSyntax)token.Parent;
}
else if (next.Parent.IsKind(SyntaxKind.PositionalPatternClause))
{
posPattern = (PositionalPatternClauseSyntax)next.Parent;
}
else
{
return false;
}
var tokenIsOpenParen = token.IsKind(SyntaxKind.OpenParenToken);
var nextIsOpenParen = next.IsKind(SyntaxKind.OpenParenToken);
var tokenIsCloseParen = token.IsKind(SyntaxKind.CloseParenToken);
var nextIsCloseParen = next.IsKind(SyntaxKind.CloseParenToken);
//inner
if (tokenIsOpenParen)
{
return false;
}
if (nextIsCloseParen)
{
return false;
}
if (posPattern.Parent is RecursivePatternSyntax rps)
{
//outer
if (nextIsOpenParen)
{
if (rps.Type != null)
{
return true;
}
else
{
return false;
}
}
if (tokenIsCloseParen)
{
if (rps.PropertyPatternClause is not null)
{
return false;
}
if (rps.Designation is null)
{
return false;
}
else
{
return true;
}
}
}
return false;
}
private static bool NeedsSeparator(SyntaxToken token, SyntaxToken next)
{
if (token.Parent == null || next.Parent == null)
{
return false;
}
if (IsAccessorListWithoutAccessorsWithBlockBody(next.Parent) ||
IsAccessorListWithoutAccessorsWithBlockBody(next.Parent.Parent))
{
// when the accessors are formatted inline, the separator is needed
// unless there is a semicolon. For example: "{ get; set; }"
return !next.IsKind(SyntaxKind.SemicolonToken);
}
if (IsXmlTextToken(token.Kind()) || IsXmlTextToken(next.Kind()))
{
return false;
}
if (next.Kind() == SyntaxKind.EndOfDirectiveToken)
{
// In a directive, there's often no token between the directive keyword and
// the end-of-directive, so we may need a separator.
return IsKeyword(token.Kind()) && next.LeadingWidth > 0;
}
if ((token.Parent is AssignmentExpressionSyntax && AssignmentTokenNeedsSeparator(token.Kind())) ||
(next.Parent is AssignmentExpressionSyntax && AssignmentTokenNeedsSeparator(next.Kind())) ||
(token.Parent is BinaryExpressionSyntax && BinaryTokenNeedsSeparator(token.Kind())) ||
(next.Parent is BinaryExpressionSyntax && BinaryTokenNeedsSeparator(next.Kind())))
{
return true;
}
if (token.IsKind(SyntaxKind.GreaterThanToken) && token.Parent.IsKind(SyntaxKind.TypeArgumentList))
{
if (!SyntaxFacts.IsPunctuation(next.Kind()))
{
return true;
}
}
if (token.IsKind(SyntaxKind.GreaterThanToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList))
{
return true;
}
if (token.IsKind(SyntaxKind.CommaToken) &&
!next.IsKind(SyntaxKind.CommaToken) &&
!token.Parent.IsKind(SyntaxKind.EnumDeclaration))
{
return true;
}
if (token.Kind() == SyntaxKind.SemicolonToken
&& !(next.Kind() == SyntaxKind.SemicolonToken || next.Kind() == SyntaxKind.CloseParenToken))
{
return true;
}
if (next.IsKind(SyntaxKind.SwitchKeyword) && next.Parent is SwitchExpressionSyntax)
{
return true;
}
if (token.IsKind(SyntaxKind.QuestionToken)
&& (token.Parent.IsKind(SyntaxKind.ConditionalExpression) || token.Parent is TypeSyntax)
&& !token.Parent.Parent.IsKind(SyntaxKind.TypeArgumentList))
{
return true;
}
if (token.IsKind(SyntaxKind.ColonToken))
{
return !token.Parent.IsKind(SyntaxKind.InterpolationFormatClause) &&
!token.Parent.IsKind(SyntaxKind.XmlPrefix);
}
if (next.IsKind(SyntaxKind.ColonToken))
{
if (next.Parent.IsKind(SyntaxKind.BaseList) ||
next.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause) ||
next.Parent is ConstructorInitializerSyntax)
{
return true;
}
}
if (token.IsKind(SyntaxKind.CloseBracketToken) && IsWord(next.Kind()))
{
return true;
}
// We don't want to add extra space after cast, we want space only after tuple
if (token.IsKind(SyntaxKind.CloseParenToken) && IsWord(next.Kind()) && token.Parent.IsKind(SyntaxKind.TupleType) == true)
{
return true;
}
if ((next.IsKind(SyntaxKind.QuestionToken) || next.IsKind(SyntaxKind.ColonToken))
&& (next.Parent.IsKind(SyntaxKind.ConditionalExpression)))
{
return true;
}
if (token.IsKind(SyntaxKind.EqualsToken))
{
return !token.Parent.IsKind(SyntaxKind.XmlTextAttribute);
}
if (next.IsKind(SyntaxKind.EqualsToken))
{
return !next.Parent.IsKind(SyntaxKind.XmlTextAttribute);
}
// Rules for function pointer below are taken from:
// https://github.com/dotnet/roslyn/blob/1cca63b5d8ea170f8d8e88e1574aa3ebe354c23b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/SpacingFormattingRule.cs#L321-L413
if (token.Parent.IsKind(SyntaxKind.FunctionPointerType))
{
// No spacing between delegate and *
if (next.IsKind(SyntaxKind.AsteriskToken) && token.IsKind(SyntaxKind.DelegateKeyword))
{
return false;
}
// Force a space between * and the calling convention
if (token.IsKind(SyntaxKind.AsteriskToken) && next.Parent.IsKind(SyntaxKind.FunctionPointerCallingConvention))
{
switch (next.Kind())
{
case SyntaxKind.IdentifierToken:
case SyntaxKind.ManagedKeyword:
case SyntaxKind.UnmanagedKeyword:
return true;
}
}
}
if (next.Parent.IsKind(SyntaxKind.FunctionPointerParameterList) && next.IsKind(SyntaxKind.LessThanToken))
{
switch (token.Kind())
{
// No spacing between the * and < tokens if there is no calling convention
case SyntaxKind.AsteriskToken:
// No spacing between the calling convention and opening angle bracket of function pointer types:
// delegate* managed<
case SyntaxKind.ManagedKeyword:
case SyntaxKind.UnmanagedKeyword:
// No spacing between the calling convention specifier and the opening angle
// delegate* unmanaged[Cdecl]<
case SyntaxKind.CloseBracketToken when token.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList):
return false;
}
}
// No space between unmanaged and the [
// delegate* unmanaged[
if (token.Parent.IsKind(SyntaxKind.FunctionPointerCallingConvention) && next.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList) &&
next.IsKind(SyntaxKind.OpenBracketToken))
{
return false;
}
// Function pointer calling convention adjustments
if (next.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList) && token.Parent.IsKind(SyntaxKind.FunctionPointerUnmanagedCallingConventionList))
{
if (next.IsKind(SyntaxKind.IdentifierToken))
{
if (token.IsKind(SyntaxKind.OpenBracketToken))
{
return false;
}
// Space after the ,
// unmanaged[Cdecl, Thiscall
else if (token.IsKind(SyntaxKind.CommaToken))
{
return true;
}
}
// No space between identifier and comma
// unmanaged[Cdecl,
if (next.IsKind(SyntaxKind.CommaToken))
{
return false;
}
// No space before the ]
// unmanaged[Cdecl]
if (next.IsKind(SyntaxKind.CloseBracketToken))
{
return false;
}
}
// No space after the < in function pointer parameter lists
// delegate*<void
if (token.IsKind(SyntaxKind.LessThanToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList))
{
return false;
}
// No space before the > in function pointer parameter lists
// delegate*<void>
if (next.IsKind(SyntaxKind.GreaterThanToken) && next.Parent.IsKind(SyntaxKind.FunctionPointerParameterList))
{
return false;
}
if (token.IsKind(SyntaxKind.EqualsGreaterThanToken) || next.IsKind(SyntaxKind.EqualsGreaterThanToken))
{
return true;
}
// Can happen in directives (e.g. #line 1 "file")
if (SyntaxFacts.IsLiteral(token.Kind()) && SyntaxFacts.IsLiteral(next.Kind()))
{
return true;
}
// No space before an asterisk that's part of a PointerTypeSyntax.
if (next.IsKind(SyntaxKind.AsteriskToken) && next.Parent is PointerTypeSyntax)
{
return false;
}
// The last asterisk of a pointer declaration should be followed by a space.
if (token.IsKind(SyntaxKind.AsteriskToken) && token.Parent is PointerTypeSyntax &&
(next.IsKind(SyntaxKind.IdentifierToken) || next.Parent.IsKind(SyntaxKind.IndexerDeclaration)))
{
return true;
}
if (IsKeyword(token.Kind()))
{
if (!next.IsKind(SyntaxKind.ColonToken) &&
!next.IsKind(SyntaxKind.DotToken) &&
!next.IsKind(SyntaxKind.QuestionToken) &&
!next.IsKind(SyntaxKind.SemicolonToken) &&
!next.IsKind(SyntaxKind.OpenBracketToken) &&
(!next.IsKind(SyntaxKind.OpenParenToken) || KeywordNeedsSeparatorBeforeOpenParen(token.Kind()) || next.Parent.IsKind(SyntaxKind.TupleType)) &&
!next.IsKind(SyntaxKind.CloseParenToken) &&
!next.IsKind(SyntaxKind.CloseBraceToken) &&
!next.IsKind(SyntaxKind.ColonColonToken) &&
!next.IsKind(SyntaxKind.GreaterThanToken) &&
!next.IsKind(SyntaxKind.CommaToken))
{
return true;
}
}
if (IsWord(token.Kind()) && IsWord(next.Kind()))
{
return true;
}
else if (token.Width > 1 && next.Width > 1)
{
var tokenLastChar = token.Text.Last();
var nextFirstChar = next.Text.First();
if (tokenLastChar == nextFirstChar && TokenCharacterCanBeDoubled(tokenLastChar))
{
return true;
}
}
if (token.Parent is RelationalPatternSyntax)
{
//>, >=, <, <=
return true;
}
switch (next.Kind())
{
case SyntaxKind.AndKeyword:
case SyntaxKind.OrKeyword:
return true;
}
switch (token.Kind())
{
case SyntaxKind.AndKeyword:
case SyntaxKind.OrKeyword:
case SyntaxKind.NotKeyword:
return true;
}
if (NeedsSeparatorForPropertyPattern(token, next))
{
return true;
}
if (NeedsSeparatorForPositionalPattern(token, next))
{
return true;
}
return false;
}
private static bool KeywordNeedsSeparatorBeforeOpenParen(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.NewKeyword:
case SyntaxKind.BaseKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.CheckedKeyword:
case SyntaxKind.UncheckedKeyword:
case SyntaxKind.SizeOfKeyword:
case SyntaxKind.ArgListKeyword:
return false;
default:
return true;
}
}
private static bool IsXmlTextToken(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.XmlTextLiteralNewLineToken:
case SyntaxKind.XmlTextLiteralToken:
return true;
default:
return false;
}
}
private static bool BinaryTokenNeedsSeparator(SyntaxKind kind)
{
switch (kind)
{
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return false;
default:
return SyntaxFacts.GetBinaryExpression(kind) != SyntaxKind.None;
}
}
private static bool AssignmentTokenNeedsSeparator(SyntaxKind kind)
{
return SyntaxFacts.GetAssignmentExpression(kind) != SyntaxKind.None;
}
private SyntaxTriviaList RewriteTrivia(
SyntaxTriviaList triviaList,
int depth,
bool isTrailing,
bool indentAfterLineBreak,
bool mustHaveSeparator,
int lineBreaksAfter)
{
ArrayBuilder<SyntaxTrivia> currentTriviaList = ArrayBuilder<SyntaxTrivia>.GetInstance(triviaList.Count);
try
{
foreach (var trivia in triviaList)
{
if (trivia.IsKind(SyntaxKind.WhitespaceTrivia) ||
trivia.IsKind(SyntaxKind.EndOfLineTrivia) ||
trivia.FullWidth == 0)
{
continue;
}
var needsSeparator =
(currentTriviaList.Count > 0 && NeedsSeparatorBetween(currentTriviaList.Last())) ||
(currentTriviaList.Count == 0 && isTrailing);
var needsLineBreak = NeedsLineBreakBefore(trivia, isTrailing)
|| (currentTriviaList.Count > 0 && NeedsLineBreakBetween(currentTriviaList.Last(), trivia, isTrailing));
if (needsLineBreak && !_afterLineBreak)
{
currentTriviaList.Add(GetEndOfLine());
_afterLineBreak = true;
_afterIndentation = false;
}
if (_afterLineBreak)
{
if (!_afterIndentation && NeedsIndentAfterLineBreak(trivia))
{
currentTriviaList.Add(this.GetIndentation(GetDeclarationDepth(trivia)));
_afterIndentation = true;
}
}
else if (needsSeparator)
{
currentTriviaList.Add(GetSpace());
_afterLineBreak = false;
_afterIndentation = false;
}
if (trivia.HasStructure)
{
var tr = this.VisitStructuredTrivia(trivia);
currentTriviaList.Add(tr);
}
else if (trivia.IsKind(SyntaxKind.DocumentationCommentExteriorTrivia))
{
// recreate exterior to remove any leading whitespace
currentTriviaList.Add(s_trimmedDocCommentExterior);
}
else
{
currentTriviaList.Add(trivia);
}
if (NeedsLineBreakAfter(trivia, isTrailing)
&& (currentTriviaList.Count == 0 || !EndsInLineBreak(currentTriviaList.Last())))
{
currentTriviaList.Add(GetEndOfLine());
_afterLineBreak = true;
_afterIndentation = false;
}
}
if (lineBreaksAfter > 0)
{
if (currentTriviaList.Count > 0
&& EndsInLineBreak(currentTriviaList.Last()))
{
lineBreaksAfter--;
}
for (int i = 0; i < lineBreaksAfter; i++)
{
currentTriviaList.Add(GetEndOfLine());
_afterLineBreak = true;
_afterIndentation = false;
}
}
else if (indentAfterLineBreak && _afterLineBreak && !_afterIndentation)
{
currentTriviaList.Add(this.GetIndentation(depth));
_afterIndentation = true;
}
else if (mustHaveSeparator)
{
currentTriviaList.Add(GetSpace());
_afterLineBreak = false;
_afterIndentation = false;
}
if (currentTriviaList.Count == 0)
{
return default(SyntaxTriviaList);
}
else if (currentTriviaList.Count == 1)
{
return SyntaxFactory.TriviaList(currentTriviaList.First());
}
else
{
return SyntaxFactory.TriviaList(currentTriviaList);
}
}
finally
{
currentTriviaList.Free();
}
}
private static readonly SyntaxTrivia s_trimmedDocCommentExterior = SyntaxFactory.DocumentationCommentExterior("///");
private SyntaxTrivia GetSpace()
{
return _useElasticTrivia ? SyntaxFactory.ElasticSpace : SyntaxFactory.Space;
}
private SyntaxTrivia GetEndOfLine()
{
return _eolTrivia;
}
private SyntaxTrivia VisitStructuredTrivia(SyntaxTrivia trivia)
{
bool oldIsInStructuredTrivia = _isInStructuredTrivia;
_isInStructuredTrivia = true;
SyntaxToken oldPreviousToken = _previousToken;
_previousToken = default(SyntaxToken);
SyntaxTrivia result = VisitTrivia(trivia);
_isInStructuredTrivia = oldIsInStructuredTrivia;
_previousToken = oldPreviousToken;
return result;
}
private static bool NeedsSeparatorBetween(SyntaxTrivia trivia)
{
switch (trivia.Kind())
{
case SyntaxKind.None:
case SyntaxKind.WhitespaceTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
return false;
default:
return !SyntaxFacts.IsPreprocessorDirective(trivia.Kind());
}
}
private static bool NeedsLineBreakBetween(SyntaxTrivia trivia, SyntaxTrivia next, bool isTrailingTrivia)
{
return NeedsLineBreakAfter(trivia, isTrailingTrivia)
|| NeedsLineBreakBefore(next, isTrailingTrivia);
}
private static bool NeedsLineBreakBefore(SyntaxTrivia trivia, bool isTrailingTrivia)
{
var kind = trivia.Kind();
switch (kind)
{
case SyntaxKind.DocumentationCommentExteriorTrivia:
return !isTrailingTrivia;
default:
return SyntaxFacts.IsPreprocessorDirective(kind);
}
}
private static bool NeedsLineBreakAfter(SyntaxTrivia trivia, bool isTrailingTrivia)
{
var kind = trivia.Kind();
switch (kind)
{
case SyntaxKind.SingleLineCommentTrivia:
return true;
case SyntaxKind.MultiLineCommentTrivia:
return !isTrailingTrivia;
default:
return SyntaxFacts.IsPreprocessorDirective(kind);
}
}
private static bool NeedsIndentAfterLineBreak(SyntaxTrivia trivia)
{
switch (trivia.Kind())
{
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
case SyntaxKind.SingleLineDocumentationCommentTrivia:
case SyntaxKind.MultiLineDocumentationCommentTrivia:
return true;
default:
return false;
}
}
private static bool IsLineBreak(SyntaxToken token)
{
return token.Kind() == SyntaxKind.XmlTextLiteralNewLineToken;
}
private static bool EndsInLineBreak(SyntaxTrivia trivia)
{
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return true;
}
if (trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia || trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
var text = trivia.ToFullString();
return text.Length > 0 && SyntaxFacts.IsNewLine(text.Last());
}
if (trivia.HasStructure)
{
var node = trivia.GetStructure()!;
var trailing = node.GetTrailingTrivia();
if (trailing.Count > 0)
{
return EndsInLineBreak(trailing.Last());
}
else
{
return IsLineBreak(node.GetLastToken());
}
}
return false;
}
private static bool IsWord(SyntaxKind kind)
{
return kind == SyntaxKind.IdentifierToken || IsKeyword(kind);
}
private static bool IsKeyword(SyntaxKind kind)
{
return SyntaxFacts.IsKeywordKind(kind) || SyntaxFacts.IsPreprocessorKeyword(kind);
}
private static bool TokenCharacterCanBeDoubled(char c)
{
switch (c)
{
case '+':
case '-':
case '<':
case ':':
case '?':
case '=':
case '"':
return true;
default:
return false;
}
}
private static int GetDeclarationDepth(SyntaxToken token)
{
return GetDeclarationDepth(token.Parent);
}
private static int GetDeclarationDepth(SyntaxTrivia trivia)
{
if (SyntaxFacts.IsPreprocessorDirective(trivia.Kind()))
{
return 0;
}
return GetDeclarationDepth((SyntaxToken)trivia.Token);
}
private static int GetDeclarationDepth(SyntaxNode? node)
{
if (node != null)
{
if (node.IsStructuredTrivia)
{
var tr = ((StructuredTriviaSyntax)node).ParentTrivia;
return GetDeclarationDepth(tr);
}
else if (node.Parent != null)
{
if (node.Parent.IsKind(SyntaxKind.CompilationUnit))
{
return 0;
}
int parentDepth = GetDeclarationDepth(node.Parent);
if (node.Parent.Kind() is SyntaxKind.GlobalStatement or SyntaxKind.FileScopedNamespaceDeclaration)
{
return parentDepth;
}
if (node.IsKind(SyntaxKind.IfStatement) && node.Parent.IsKind(SyntaxKind.ElseClause))
{
return parentDepth;
}
if (node.Parent is BlockSyntax ||
(node is StatementSyntax && !(node is BlockSyntax)))
{
// all nested statements are indented one level
return parentDepth + 1;
}
if (node is MemberDeclarationSyntax ||
node is AccessorDeclarationSyntax ||
node is TypeParameterConstraintClauseSyntax ||
node is SwitchSectionSyntax ||
node is SwitchExpressionArmSyntax ||
node is UsingDirectiveSyntax ||
node is ExternAliasDirectiveSyntax ||
node is QueryExpressionSyntax ||
node is QueryContinuationSyntax)
{
return parentDepth + 1;
}
return parentDepth;
}
}
return 0;
}
public override SyntaxNode? VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node)
{
if (node.StringStartToken.Kind() == SyntaxKind.InterpolatedStringStartToken)
{
//Just for non verbatim strings we want to make sure that the formatting of interpolations does not emit line breaks.
//See: https://github.com/dotnet/roslyn/issues/50742
//
//The flag _inSingleLineInterpolation is set to true while visiting InterpolatedStringExpressionSyntax and checked in LineBreaksAfter
//to suppress adding newlines.
var old = _inSingleLineInterpolation;
_inSingleLineInterpolation = true;
try
{
return base.VisitInterpolatedStringExpression(node);
}
finally
{
_inSingleLineInterpolation = old;
}
}
return base.VisitInterpolatedStringExpression(node);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SemanticModelExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SemanticModelExtensions
{
public static IEnumerable<ITypeSymbol> LookupTypeRegardlessOfArity(
this SemanticModel semanticModel,
SyntaxToken name,
CancellationToken cancellationToken)
{
if (name.Parent is ExpressionSyntax expression)
{
var results = semanticModel.LookupName(expression, cancellationToken: cancellationToken);
if (results.Length > 0)
{
return results.OfType<ITypeSymbol>();
}
}
return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
}
public static ImmutableArray<ISymbol> LookupName(
this SemanticModel semanticModel,
SyntaxToken name,
CancellationToken cancellationToken)
{
if (name.Parent is ExpressionSyntax expression)
{
return semanticModel.LookupName(expression, cancellationToken);
}
return ImmutableArray.Create<ISymbol>();
}
/// <summary>
/// Decomposes a name or member access expression into its component parts.
/// </summary>
/// <param name="expression">The name or member access expression.</param>
/// <param name="qualifier">The qualifier (or left-hand-side) of the name expression. This may be null if there is no qualifier.</param>
/// <param name="name">The name of the expression.</param>
/// <param name="arity">The number of generic type parameters.</param>
private static void DecomposeName(ExpressionSyntax expression, out ExpressionSyntax qualifier, out string name, out int arity)
{
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
var max = (MemberAccessExpressionSyntax)expression;
qualifier = max.Expression;
name = max.Name.Identifier.ValueText;
arity = max.Name.Arity;
break;
case SyntaxKind.QualifiedName:
var qn = (QualifiedNameSyntax)expression;
qualifier = qn.Left;
name = qn.Right.Identifier.ValueText;
arity = qn.Arity;
break;
case SyntaxKind.AliasQualifiedName:
var aq = (AliasQualifiedNameSyntax)expression;
qualifier = aq.Alias;
name = aq.Name.Identifier.ValueText;
arity = aq.Name.Arity;
break;
case SyntaxKind.GenericName:
var gx = (GenericNameSyntax)expression;
qualifier = null;
name = gx.Identifier.ValueText;
arity = gx.Arity;
break;
case SyntaxKind.IdentifierName:
var nx = (IdentifierNameSyntax)expression;
qualifier = null;
name = nx.Identifier.ValueText;
arity = 0;
break;
default:
qualifier = null;
name = null;
arity = 0;
break;
}
}
public static ImmutableArray<ISymbol> LookupName(
this SemanticModel semanticModel,
ExpressionSyntax expression,
CancellationToken cancellationToken)
{
var expr = SyntaxFactory.GetStandaloneExpression(expression);
DecomposeName(expr, out var qualifier, out var name, out _);
INamespaceOrTypeSymbol symbol = null;
if (qualifier != null)
{
var typeInfo = semanticModel.GetTypeInfo(qualifier, cancellationToken);
var symbolInfo = semanticModel.GetSymbolInfo(qualifier, cancellationToken);
if (typeInfo.Type != null)
{
symbol = typeInfo.Type;
}
else if (symbolInfo.Symbol != null)
{
symbol = symbolInfo.Symbol as INamespaceOrTypeSymbol;
}
}
return semanticModel.LookupSymbols(expr.SpanStart, container: symbol, name: name, includeReducedExtensionMethods: true);
}
public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token)
{
if (!CanBindToken(token))
{
return default;
}
switch (token.Parent)
{
case ExpressionSyntax expression:
return semanticModel.GetSymbolInfo(expression);
case AttributeSyntax attribute:
return semanticModel.GetSymbolInfo(attribute);
case ConstructorInitializerSyntax constructorInitializer:
return semanticModel.GetSymbolInfo(constructorInitializer);
}
return default;
}
private static bool CanBindToken(SyntaxToken token)
{
// Add more token kinds if necessary;
switch (token.Kind())
{
case SyntaxKind.CommaToken:
case SyntaxKind.DelegateKeyword:
return false;
}
return true;
}
public static ISet<INamespaceSymbol> GetUsingNamespacesInScope(this SemanticModel semanticModel, SyntaxNode location)
{
// Avoiding linq here for perf reasons. This is used heavily in the AddImport service
var result = new HashSet<INamespaceSymbol>();
foreach (var @using in location.GetEnclosingUsingDirectives())
{
if (@using.Alias == null)
{
var symbolInfo = semanticModel.GetSymbolInfo(@using.Name);
if (symbolInfo.Symbol != null && symbolInfo.Symbol.Kind == SymbolKind.Namespace)
{
result ??= new HashSet<INamespaceSymbol>();
result.Add((INamespaceSymbol)symbolInfo.Symbol);
}
}
}
return result;
}
public static Accessibility DetermineAccessibilityConstraint(
this SemanticModel semanticModel,
TypeSyntax type,
CancellationToken cancellationToken)
{
if (type == null)
{
return Accessibility.Private;
}
type = GetOutermostType(type);
// Interesting cases based on 3.5.4 Accessibility constraints in the language spec.
// If any of the below hold, then we will override the default accessibility if the
// constraint wants the type to be more accessible. i.e. if by default we generate
// 'internal', but a constraint makes us 'public', then be public.
// 1) The direct base class of a class type must be at least as accessible as the
// class type itself.
//
// 2) The explicit base interfaces of an interface type must be at least as accessible
// as the interface type itself.
if (type != null)
{
if (type.Parent is BaseTypeSyntax baseType &&
baseType.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax baseList) &&
baseType.Type == type)
{
var containingType = semanticModel.GetDeclaredSymbol(type.GetAncestor<BaseTypeDeclarationSyntax>(), cancellationToken) as INamedTypeSymbol;
if (containingType != null && containingType.TypeKind == TypeKind.Interface)
{
return containingType.DeclaredAccessibility;
}
else if (baseList.Types[0] == type.Parent)
{
return containingType.DeclaredAccessibility;
}
}
}
// 4) The type of a constant must be at least as accessible as the constant itself.
// 5) The type of a field must be at least as accessible as the field itself.
if (type.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax variableDeclaration) &&
variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration))
{
return semanticModel.GetDeclaredSymbol(
variableDeclaration.Variables[0], cancellationToken).DeclaredAccessibility;
}
// Also do the same check if we are in an object creation expression
if (type.IsParentKind(SyntaxKind.ObjectCreationExpression) &&
type.Parent.IsParentKind(SyntaxKind.EqualsValueClause) &&
type.Parent.Parent.IsParentKind(SyntaxKind.VariableDeclarator) &&
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.VariableDeclaration, out variableDeclaration) &&
variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration))
{
return semanticModel.GetDeclaredSymbol(
variableDeclaration.Variables[0], cancellationToken).DeclaredAccessibility;
}
// 3) The return type of a delegate type must be at least as accessible as the
// delegate type itself.
// 6) The return type of a method must be at least as accessible as the method
// itself.
// 7) The type of a property must be at least as accessible as the property itself.
// 8) The type of an event must be at least as accessible as the event itself.
// 9) The type of an indexer must be at least as accessible as the indexer itself.
// 10) The return type of an operator must be at least as accessible as the operator
// itself.
if (type.IsParentKind(SyntaxKind.DelegateDeclaration) ||
type.IsParentKind(SyntaxKind.MethodDeclaration) ||
type.IsParentKind(SyntaxKind.PropertyDeclaration) ||
type.IsParentKind(SyntaxKind.EventDeclaration) ||
type.IsParentKind(SyntaxKind.IndexerDeclaration) ||
type.IsParentKind(SyntaxKind.OperatorDeclaration))
{
return semanticModel.GetDeclaredSymbol(
type.Parent, cancellationToken).DeclaredAccessibility;
}
// 3) The parameter types of a delegate type must be at least as accessible as the
// delegate type itself.
// 6) The parameter types of a method must be at least as accessible as the method
// itself.
// 9) The parameter types of an indexer must be at least as accessible as the
// indexer itself.
// 10) The parameter types of an operator must be at least as accessible as the
// operator itself.
// 11) The parameter types of an instance constructor must be at least as accessible
// as the instance constructor itself.
if (type.IsParentKind(SyntaxKind.Parameter) && type.Parent.IsParentKind(SyntaxKind.ParameterList))
{
if (type.Parent.Parent.IsParentKind(SyntaxKind.DelegateDeclaration) ||
type.Parent.Parent.IsParentKind(SyntaxKind.MethodDeclaration) ||
type.Parent.Parent.IsParentKind(SyntaxKind.IndexerDeclaration) ||
type.Parent.Parent.IsParentKind(SyntaxKind.OperatorDeclaration))
{
return semanticModel.GetDeclaredSymbol(
type.Parent.Parent.Parent, cancellationToken).DeclaredAccessibility;
}
if (type.Parent.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration))
{
var symbol = semanticModel.GetDeclaredSymbol(type.Parent.Parent.Parent, cancellationToken);
if (!symbol.IsStatic)
{
return symbol.DeclaredAccessibility;
}
}
}
// 8) The type of an event must be at least as accessible as the event itself.
if (type.IsParentKind(SyntaxKind.VariableDeclaration, out variableDeclaration) &&
variableDeclaration.IsParentKind(SyntaxKind.EventFieldDeclaration))
{
var symbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Variables[0], cancellationToken);
if (symbol != null)
{
return symbol.DeclaredAccessibility;
}
}
// Type constraint must be at least as accessible as the declaring member (class, interface, delegate, method)
if (type.IsParentKind(SyntaxKind.TypeConstraint))
{
return AllContainingTypesArePublicOrProtected(semanticModel, type, cancellationToken)
? Accessibility.Public
: Accessibility.Internal;
}
return Accessibility.Private;
}
public static bool AllContainingTypesArePublicOrProtected(
this SemanticModel semanticModel,
TypeSyntax type,
CancellationToken cancellationToken)
{
if (type == null)
{
return false;
}
var typeDeclarations = type.GetAncestors<TypeDeclarationSyntax>();
foreach (var typeDeclaration in typeDeclarations)
{
var symbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
if (symbol.DeclaredAccessibility == Accessibility.Private ||
symbol.DeclaredAccessibility == Accessibility.ProtectedAndInternal ||
symbol.DeclaredAccessibility == Accessibility.Internal)
{
return false;
}
}
return true;
}
private static TypeSyntax GetOutermostType(TypeSyntax type)
=> type.GetAncestorsOrThis<TypeSyntax>().Last();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SemanticModelExtensions
{
public static IEnumerable<ITypeSymbol> LookupTypeRegardlessOfArity(
this SemanticModel semanticModel,
SyntaxToken name,
CancellationToken cancellationToken)
{
if (name.Parent is ExpressionSyntax expression)
{
var results = semanticModel.LookupName(expression, cancellationToken: cancellationToken);
if (results.Length > 0)
{
return results.OfType<ITypeSymbol>();
}
}
return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
}
public static ImmutableArray<ISymbol> LookupName(
this SemanticModel semanticModel,
SyntaxToken name,
CancellationToken cancellationToken)
{
if (name.Parent is ExpressionSyntax expression)
{
return semanticModel.LookupName(expression, cancellationToken);
}
return ImmutableArray.Create<ISymbol>();
}
/// <summary>
/// Decomposes a name or member access expression into its component parts.
/// </summary>
/// <param name="expression">The name or member access expression.</param>
/// <param name="qualifier">The qualifier (or left-hand-side) of the name expression. This may be null if there is no qualifier.</param>
/// <param name="name">The name of the expression.</param>
/// <param name="arity">The number of generic type parameters.</param>
private static void DecomposeName(ExpressionSyntax expression, out ExpressionSyntax qualifier, out string name, out int arity)
{
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
var max = (MemberAccessExpressionSyntax)expression;
qualifier = max.Expression;
name = max.Name.Identifier.ValueText;
arity = max.Name.Arity;
break;
case SyntaxKind.QualifiedName:
var qn = (QualifiedNameSyntax)expression;
qualifier = qn.Left;
name = qn.Right.Identifier.ValueText;
arity = qn.Arity;
break;
case SyntaxKind.AliasQualifiedName:
var aq = (AliasQualifiedNameSyntax)expression;
qualifier = aq.Alias;
name = aq.Name.Identifier.ValueText;
arity = aq.Name.Arity;
break;
case SyntaxKind.GenericName:
var gx = (GenericNameSyntax)expression;
qualifier = null;
name = gx.Identifier.ValueText;
arity = gx.Arity;
break;
case SyntaxKind.IdentifierName:
var nx = (IdentifierNameSyntax)expression;
qualifier = null;
name = nx.Identifier.ValueText;
arity = 0;
break;
default:
qualifier = null;
name = null;
arity = 0;
break;
}
}
public static ImmutableArray<ISymbol> LookupName(
this SemanticModel semanticModel,
ExpressionSyntax expression,
CancellationToken cancellationToken)
{
var expr = SyntaxFactory.GetStandaloneExpression(expression);
DecomposeName(expr, out var qualifier, out var name, out _);
INamespaceOrTypeSymbol symbol = null;
if (qualifier != null)
{
var typeInfo = semanticModel.GetTypeInfo(qualifier, cancellationToken);
var symbolInfo = semanticModel.GetSymbolInfo(qualifier, cancellationToken);
if (typeInfo.Type != null)
{
symbol = typeInfo.Type;
}
else if (symbolInfo.Symbol != null)
{
symbol = symbolInfo.Symbol as INamespaceOrTypeSymbol;
}
}
return semanticModel.LookupSymbols(expr.SpanStart, container: symbol, name: name, includeReducedExtensionMethods: true);
}
public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token)
{
if (!CanBindToken(token))
{
return default;
}
switch (token.Parent)
{
case ExpressionSyntax expression:
return semanticModel.GetSymbolInfo(expression);
case AttributeSyntax attribute:
return semanticModel.GetSymbolInfo(attribute);
case ConstructorInitializerSyntax constructorInitializer:
return semanticModel.GetSymbolInfo(constructorInitializer);
}
return default;
}
private static bool CanBindToken(SyntaxToken token)
{
// Add more token kinds if necessary;
switch (token.Kind())
{
case SyntaxKind.CommaToken:
case SyntaxKind.DelegateKeyword:
return false;
}
return true;
}
public static ISet<INamespaceSymbol> GetUsingNamespacesInScope(this SemanticModel semanticModel, SyntaxNode location)
{
// Avoiding linq here for perf reasons. This is used heavily in the AddImport service
var result = new HashSet<INamespaceSymbol>();
foreach (var @using in location.GetEnclosingUsingDirectives())
{
if (@using.Alias == null)
{
var symbolInfo = semanticModel.GetSymbolInfo(@using.Name);
if (symbolInfo.Symbol != null && symbolInfo.Symbol.Kind == SymbolKind.Namespace)
{
result ??= new HashSet<INamespaceSymbol>();
result.Add((INamespaceSymbol)symbolInfo.Symbol);
}
}
}
return result;
}
public static Accessibility DetermineAccessibilityConstraint(
this SemanticModel semanticModel,
TypeSyntax type,
CancellationToken cancellationToken)
{
if (type == null)
{
return Accessibility.Private;
}
type = GetOutermostType(type);
// Interesting cases based on 3.5.4 Accessibility constraints in the language spec.
// If any of the below hold, then we will override the default accessibility if the
// constraint wants the type to be more accessible. i.e. if by default we generate
// 'internal', but a constraint makes us 'public', then be public.
// 1) The direct base class of a class type must be at least as accessible as the
// class type itself.
//
// 2) The explicit base interfaces of an interface type must be at least as accessible
// as the interface type itself.
if (type != null)
{
if (type.Parent is BaseTypeSyntax baseType &&
baseType.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax baseList) &&
baseType.Type == type)
{
var containingType = semanticModel.GetDeclaredSymbol(type.GetAncestor<BaseTypeDeclarationSyntax>(), cancellationToken) as INamedTypeSymbol;
if (containingType != null && containingType.TypeKind == TypeKind.Interface)
{
return containingType.DeclaredAccessibility;
}
else if (baseList.Types[0] == type.Parent)
{
return containingType.DeclaredAccessibility;
}
}
}
// 4) The type of a constant must be at least as accessible as the constant itself.
// 5) The type of a field must be at least as accessible as the field itself.
if (type.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax variableDeclaration) &&
variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration))
{
return semanticModel.GetDeclaredSymbol(
variableDeclaration.Variables[0], cancellationToken).DeclaredAccessibility;
}
// Also do the same check if we are in an object creation expression
if (type.IsParentKind(SyntaxKind.ObjectCreationExpression) &&
type.Parent.IsParentKind(SyntaxKind.EqualsValueClause) &&
type.Parent.Parent.IsParentKind(SyntaxKind.VariableDeclarator) &&
type.Parent.Parent.Parent.IsParentKind(SyntaxKind.VariableDeclaration, out variableDeclaration) &&
variableDeclaration.IsParentKind(SyntaxKind.FieldDeclaration))
{
return semanticModel.GetDeclaredSymbol(
variableDeclaration.Variables[0], cancellationToken).DeclaredAccessibility;
}
// 3) The return type of a delegate type must be at least as accessible as the
// delegate type itself.
// 6) The return type of a method must be at least as accessible as the method
// itself.
// 7) The type of a property must be at least as accessible as the property itself.
// 8) The type of an event must be at least as accessible as the event itself.
// 9) The type of an indexer must be at least as accessible as the indexer itself.
// 10) The return type of an operator must be at least as accessible as the operator
// itself.
if (type.IsParentKind(SyntaxKind.DelegateDeclaration) ||
type.IsParentKind(SyntaxKind.MethodDeclaration) ||
type.IsParentKind(SyntaxKind.PropertyDeclaration) ||
type.IsParentKind(SyntaxKind.EventDeclaration) ||
type.IsParentKind(SyntaxKind.IndexerDeclaration) ||
type.IsParentKind(SyntaxKind.OperatorDeclaration))
{
return semanticModel.GetDeclaredSymbol(
type.Parent, cancellationToken).DeclaredAccessibility;
}
// 3) The parameter types of a delegate type must be at least as accessible as the
// delegate type itself.
// 6) The parameter types of a method must be at least as accessible as the method
// itself.
// 9) The parameter types of an indexer must be at least as accessible as the
// indexer itself.
// 10) The parameter types of an operator must be at least as accessible as the
// operator itself.
// 11) The parameter types of an instance constructor must be at least as accessible
// as the instance constructor itself.
if (type.IsParentKind(SyntaxKind.Parameter) && type.Parent.IsParentKind(SyntaxKind.ParameterList))
{
if (type.Parent.Parent.IsParentKind(SyntaxKind.DelegateDeclaration) ||
type.Parent.Parent.IsParentKind(SyntaxKind.MethodDeclaration) ||
type.Parent.Parent.IsParentKind(SyntaxKind.IndexerDeclaration) ||
type.Parent.Parent.IsParentKind(SyntaxKind.OperatorDeclaration))
{
return semanticModel.GetDeclaredSymbol(
type.Parent.Parent.Parent, cancellationToken).DeclaredAccessibility;
}
if (type.Parent.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration))
{
var symbol = semanticModel.GetDeclaredSymbol(type.Parent.Parent.Parent, cancellationToken);
if (!symbol.IsStatic)
{
return symbol.DeclaredAccessibility;
}
}
}
// 8) The type of an event must be at least as accessible as the event itself.
if (type.IsParentKind(SyntaxKind.VariableDeclaration, out variableDeclaration) &&
variableDeclaration.IsParentKind(SyntaxKind.EventFieldDeclaration))
{
var symbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Variables[0], cancellationToken);
if (symbol != null)
{
return symbol.DeclaredAccessibility;
}
}
// Type constraint must be at least as accessible as the declaring member (class, interface, delegate, method)
if (type.IsParentKind(SyntaxKind.TypeConstraint))
{
return AllContainingTypesArePublicOrProtected(semanticModel, type, cancellationToken)
? Accessibility.Public
: Accessibility.Internal;
}
return Accessibility.Private;
}
public static bool AllContainingTypesArePublicOrProtected(
this SemanticModel semanticModel,
TypeSyntax type,
CancellationToken cancellationToken)
{
if (type == null)
{
return false;
}
var typeDeclarations = type.GetAncestors<TypeDeclarationSyntax>();
foreach (var typeDeclaration in typeDeclarations)
{
var symbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
if (symbol.DeclaredAccessibility == Accessibility.Private ||
symbol.DeclaredAccessibility == Accessibility.ProtectedAndInternal ||
symbol.DeclaredAccessibility == Accessibility.Internal)
{
return false;
}
}
return true;
}
private static TypeSyntax GetOutermostType(TypeSyntax type)
=> type.GetAncestorsOrThis<TypeSyntax>().Last();
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CSharpFeaturesResources.resx">
<body>
<trans-unit id="Add_await">
<source>Add 'await'</source>
<target state="translated">'await' ekleyin</target>
<note>{Locked="await"} "await" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_await_and_ConfigureAwaitFalse">
<source>Add 'await' and 'ConfigureAwait(false)'</source>
<target state="translated">'await' ve 'ConfigureAwait(false)' ekleyin</target>
<note>{Locked="await"} "await" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_missing_usings">
<source>Add missing usings</source>
<target state="translated">Eksik usings Ekle</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_remove_braces_for_single_line_control_statements">
<source>Add/remove braces for single-line control statements</source>
<target state="translated">Tek satır denetim deyimleri için küme ayracı ekle/küme ayraçlarını kaldır</target>
<note />
</trans-unit>
<trans-unit id="Allow_unsafe_code_in_this_project">
<source>Allow unsafe code in this project</source>
<target state="translated">Bu projede güvenli olmayan koda izin ver</target>
<note />
</trans-unit>
<trans-unit id="Apply_expression_block_body_preferences">
<source>Apply expression/block body preferences</source>
<target state="translated">İfade/blok gövdesi tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_implicit_explicit_type_preferences">
<source>Apply implicit/explicit type preferences</source>
<target state="translated">Örtük/açık tür tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_inline_out_variable_preferences">
<source>Apply inline 'out' variables preferences</source>
<target state="translated">Satır içi 'out' değişkenlerine ilişkin tercihleri uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_language_framework_type_preferences">
<source>Apply language/framework type preferences</source>
<target state="translated">Dil/çerçeve türü tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_this_qualification_preferences">
<source>Apply 'this.' qualification preferences</source>
<target state="translated">'this.' nitelemesi tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_using_directive_placement_preferences">
<source>Apply preferred 'using' placement preferences</source>
<target state="translated">Tercih edilen 'using' yerleştirme tercihlerini uygulayın</target>
<note>'using' is a C# keyword and should not be localized</note>
</trans-unit>
<trans-unit id="Assign_out_parameters">
<source>Assign 'out' parameters</source>
<target state="translated">'out' parametreleri ata</target>
<note>{Locked="out"} "out" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Assign_out_parameters_at_start">
<source>Assign 'out' parameters (at start)</source>
<target state="translated">'out' parametreleri ata (başlangıçta)</target>
<note>{Locked="out"} "out" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Assign_to_0">
<source>Assign to '{0}'</source>
<target state="translated">'{0}' öğesine ata</target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration">
<source>Autoselect disabled due to potential pattern variable declaration.</source>
<target state="translated">Otomatik seçim, olası desen değişkeni bildirimi nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="Change_to_as_expression">
<source>Change to 'as' expression</source>
<target state="translated">'as' ifadesine değiştir</target>
<note />
</trans-unit>
<trans-unit id="Change_to_cast">
<source>Change to cast</source>
<target state="translated">Tür dönüştürme olarak değiştir</target>
<note />
</trans-unit>
<trans-unit id="Compare_to_0">
<source>Compare to '{0}'</source>
<target state="translated">'{0}' ile karşılaştır</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_method">
<source>Convert to method</source>
<target state="translated">Yönteme dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_regular_string">
<source>Convert to regular string</source>
<target state="translated">Normal dizeye dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_switch_expression">
<source>Convert to 'switch' expression</source>
<target state="translated">'switch' deyimine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_switch_statement">
<source>Convert to 'switch' statement</source>
<target state="translated">'switch' ifadesine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_verbatim_string">
<source>Convert to verbatim string</source>
<target state="translated">Düz metin dizesine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Declare_as_nullable">
<source>Declare as nullable</source>
<target state="translated">Olarak null olabilecek ilan</target>
<note />
</trans-unit>
<trans-unit id="Fix_return_type">
<source>Fix return type</source>
<target state="translated">Dönüş türünü düzelt</target>
<note />
</trans-unit>
<trans-unit id="Inline_temporary_variable">
<source>Inline temporary variable</source>
<target state="translated">Satır içi geçici değişken</target>
<note />
</trans-unit>
<trans-unit id="Conflict_s_detected">
<source>Conflict(s) detected.</source>
<target state="translated">Çakışmalar algılandı.</target>
<note />
</trans-unit>
<trans-unit id="Make_private_field_readonly_when_possible">
<source>Make private fields readonly when possible</source>
<target state="translated">Özel alanları mümkün olduğunda salt okunur yap</target>
<note />
</trans-unit>
<trans-unit id="Make_ref_struct">
<source>Make 'ref struct'</source>
<target state="translated">'ref struct' yap</target>
<note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note>
</trans-unit>
<trans-unit id="Remove_in_keyword">
<source>Remove 'in' keyword</source>
<target state="translated">'in' anahtar sözcüğünü kaldır</target>
<note>{Locked="in"} "in" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Remove_new_modifier">
<source>Remove 'new' modifier</source>
<target state="translated">'New' değiştiricisini kaldır</target>
<note />
</trans-unit>
<trans-unit id="Reverse_for_statement">
<source>Reverse 'for' statement</source>
<target state="translated">'for' ifadesini tersine çevir</target>
<note>{Locked="for"} "for" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Simplify_lambda_expression">
<source>Simplify lambda expression</source>
<target state="translated">Lambda ifadesini basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Simplify_all_occurrences">
<source>Simplify all occurrences</source>
<target state="translated">Tüm yinelemeleri basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Sort_accessibility_modifiers">
<source>Sort accessibility modifiers</source>
<target state="translated">Erişilebilirlik değiştiricilerini sırala</target>
<note />
</trans-unit>
<trans-unit id="Unseal_class_0">
<source>Unseal class '{0}'</source>
<target state="translated">'{0}' sınıfının mührünü aç</target>
<note />
</trans-unit>
<trans-unit id="Use_recursive_patterns">
<source>Use recursive patterns</source>
<target state="new">Use recursive patterns</target>
<note />
</trans-unit>
<trans-unit id="Warning_Inlining_temporary_into_conditional_method_call">
<source>Warning: Inlining temporary into conditional method call.</source>
<target state="translated">Uyarı: Koşullu yöntem çağrısında geçici öğe satır içinde kullanılıyor.</target>
<note />
</trans-unit>
<trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning">
<source>Warning: Inlining temporary variable may change code meaning.</source>
<target state="translated">Uyarı: Geçici değişkeni satır içinde belirtmek kod anlamını değişebilir.</target>
<note />
</trans-unit>
<trans-unit id="asynchronous_foreach_statement">
<source>asynchronous foreach statement</source>
<target state="translated">zaman uyumsuz foreach deyimi</target>
<note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="asynchronous_using_declaration">
<source>asynchronous using declaration</source>
<target state="translated">zaman uyumsuz using bildirimi</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="extern_alias">
<source>extern alias</source>
<target state="translated">dış diğer ad</target>
<note />
</trans-unit>
<trans-unit id="lambda_expression">
<source><lambda expression></source>
<target state="translated">< lambda ifadesi ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration">
<source>Autoselect disabled due to potential lambda declaration.</source>
<target state="translated">Otomatik seçim, olası lambda bildirimi nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="local_variable_declaration">
<source>local variable declaration</source>
<target state="translated">yerel değişken bildirimi</target>
<note />
</trans-unit>
<trans-unit id="member_name">
<source><member name> = </source>
<target state="translated">< üye adı > = </target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation">
<source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source>
<target state="translated">Otomatik seçim, olası açık adlı anonim tür üyesi oluşturma nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="element_name">
<source><element name> : </source>
<target state="translated">< öğe adı >: </target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation">
<source>Autoselect disabled due to possible tuple type element creation.</source>
<target state="translated">Olası demet türü öğe oluşturma işleminden dolayı Otomatik seçim devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="pattern_variable">
<source><pattern variable></source>
<target state="translated"><desen değişkeni></target>
<note />
</trans-unit>
<trans-unit id="range_variable">
<source><range variable></source>
<target state="translated">< Aralık değişkeni ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration">
<source>Autoselect disabled due to potential range variable declaration.</source>
<target state="translated">Otomatik seçim, olası aralık değişkeni bildirimi nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="Simplify_name_0">
<source>Simplify name '{0}'</source>
<target state="translated">'{0}' adını basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Simplify_member_access_0">
<source>Simplify member access '{0}'</source>
<target state="translated">'{0}' üye erişimini basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Remove_this_qualification">
<source>Remove 'this' qualification</source>
<target state="translated">this' nitelemesini kaldır</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified</source>
<target state="translated">Ad basitleştirilebilir</target>
<note />
</trans-unit>
<trans-unit id="Can_t_determine_valid_range_of_statements_to_extract">
<source>Can't determine valid range of statements to extract</source>
<target state="translated">Ayıklanacak deyimlerin geçerli aralığı belirlenemiyor</target>
<note />
</trans-unit>
<trans-unit id="Not_all_code_paths_return">
<source>Not all code paths return</source>
<target state="translated">Kod yollarından bazıları dönmüyor</target>
<note />
</trans-unit>
<trans-unit id="Selection_does_not_contain_a_valid_node">
<source>Selection does not contain a valid node</source>
<target state="translated">Seçim, geçerli bir düğüm içermiyor</target>
<note />
</trans-unit>
<trans-unit id="Invalid_selection">
<source>Invalid selection.</source>
<target state="translated">Geçersiz seçim.</target>
<note />
</trans-unit>
<trans-unit id="Contains_invalid_selection">
<source>Contains invalid selection.</source>
<target state="translated">Geçersiz seçimi içerir.</target>
<note />
</trans-unit>
<trans-unit id="The_selection_contains_syntactic_errors">
<source>The selection contains syntactic errors</source>
<target state="translated">Seçim söz dizimsel hatalar içeriyor</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_cross_over_preprocessor_directives">
<source>Selection can not cross over preprocessor directives.</source>
<target state="translated">Seçim önişlemci yönergeleriyle çapraz olamaz.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_contain_a_yield_statement">
<source>Selection can not contain a yield statement.</source>
<target state="translated">Seçim bir bırakma ifadesi içeremez.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_contain_throw_statement">
<source>Selection can not contain throw statement.</source>
<target state="translated">Seçim bir atma ifadesi içeremez.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression">
<source>Selection can not be part of constant initializer expression.</source>
<target state="translated">Seçim, sabit başlatıcı ifadesinin parçası olamaz.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_contain_a_pattern_expression">
<source>Selection can not contain a pattern expression.</source>
<target state="translated">Seçim, bir desen ifadesi içeremez.</target>
<note />
</trans-unit>
<trans-unit id="The_selected_code_is_inside_an_unsafe_context">
<source>The selected code is inside an unsafe context.</source>
<target state="translated">Seçili kod güvenli olmayan bir bağlam içinde.</target>
<note />
</trans-unit>
<trans-unit id="No_valid_statement_range_to_extract">
<source>No valid statement range to extract</source>
<target state="translated">Ayıklanacak geçerli deyim aralığı yok</target>
<note />
</trans-unit>
<trans-unit id="deprecated">
<source>deprecated</source>
<target state="translated">kullanım dışı</target>
<note />
</trans-unit>
<trans-unit id="extension">
<source>extension</source>
<target state="translated">uzantı</target>
<note />
</trans-unit>
<trans-unit id="awaitable">
<source>awaitable</source>
<target state="translated">awaitable</target>
<note />
</trans-unit>
<trans-unit id="awaitable_extension">
<source>awaitable, extension</source>
<target state="translated">awaitable, uzantı</target>
<note />
</trans-unit>
<trans-unit id="Organize_Usings">
<source>Organize Usings</source>
<target state="translated">Kullanımları Düzenle</target>
<note />
</trans-unit>
<trans-unit id="Insert_await">
<source>Insert 'await'.</source>
<target state="translated">await' ekle.</target>
<note />
</trans-unit>
<trans-unit id="Make_0_return_Task_instead_of_void">
<source>Make {0} return Task instead of void.</source>
<target state="translated">{0} öğesi boşluk yerine Görev döndürsün.</target>
<note />
</trans-unit>
<trans-unit id="Change_return_type_from_0_to_1">
<source>Change return type from {0} to {1}</source>
<target state="translated">Dönüş türünü {0} değerinden {1} olarak değiştir</target>
<note />
</trans-unit>
<trans-unit id="Replace_return_with_yield_return">
<source>Replace return with yield return</source>
<target state="translated">Dönüşü, bırakma dönüşüyle değiştir</target>
<note />
</trans-unit>
<trans-unit id="Generate_explicit_conversion_operator_in_0">
<source>Generate explicit conversion operator in '{0}'</source>
<target state="translated">'{0}' içinde açık dönüşüm işleci oluştur</target>
<note />
</trans-unit>
<trans-unit id="Generate_implicit_conversion_operator_in_0">
<source>Generate implicit conversion operator in '{0}'</source>
<target state="translated">'{0}' içinde örtük dönüşüm işleci oluştur</target>
<note />
</trans-unit>
<trans-unit id="record_">
<source>record</source>
<target state="translated">kayıt</target>
<note />
</trans-unit>
<trans-unit id="record_struct">
<source>record struct</source>
<target state="new">record struct</target>
<note />
</trans-unit>
<trans-unit id="switch_statement">
<source>switch statement</source>
<target state="translated">switch deyimi</target>
<note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="switch_statement_case_clause">
<source>switch statement case clause</source>
<target state="translated">switch deyimi case yan tümcesi</target>
<note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="try_block">
<source>try block</source>
<target state="translated">try bloğu</target>
<note>{Locked="try"} "try" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="catch_clause">
<source>catch clause</source>
<target state="translated">catch yan tümcesi</target>
<note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="filter_clause">
<source>filter clause</source>
<target state="translated">filter yan tümcesi</target>
<note />
</trans-unit>
<trans-unit id="finally_clause">
<source>finally clause</source>
<target state="translated">finally yan tümcesi</target>
<note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="fixed_statement">
<source>fixed statement</source>
<target state="translated">fixed deyimi</target>
<note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="using_declaration">
<source>using declaration</source>
<target state="translated">using bildirimi</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="using_statement">
<source>using statement</source>
<target state="translated">using deyimi</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="lock_statement">
<source>lock statement</source>
<target state="translated">lock deyimi</target>
<note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="foreach_statement">
<source>foreach statement</source>
<target state="translated">foreach deyimi</target>
<note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="checked_statement">
<source>checked statement</source>
<target state="translated">checked deyimi</target>
<note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="unchecked_statement">
<source>unchecked statement</source>
<target state="translated">unchecked deyimi</target>
<note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="await_expression">
<source>await expression</source>
<target state="translated">await ifadesi</target>
<note>{Locked="await"} "await" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="lambda">
<source>lambda</source>
<target state="translated">lambda</target>
<note />
</trans-unit>
<trans-unit id="anonymous_method">
<source>anonymous method</source>
<target state="translated">anonim yöntem</target>
<note />
</trans-unit>
<trans-unit id="from_clause">
<source>from clause</source>
<target state="translated">from yan tümcesi</target>
<note />
</trans-unit>
<trans-unit id="join_clause">
<source>join clause</source>
<target state="translated">join yan tümcesi</target>
<note>{Locked="join"} "join" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="let_clause">
<source>let clause</source>
<target state="translated">let yan tümcesi</target>
<note>{Locked="let"} "let" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="where_clause">
<source>where clause</source>
<target state="translated">where yan tümcesi</target>
<note>{Locked="where"} "where" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="orderby_clause">
<source>orderby clause</source>
<target state="translated">orderby yan tümcesi</target>
<note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="select_clause">
<source>select clause</source>
<target state="translated">select yan tümcesi</target>
<note>{Locked="select"} "select" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="groupby_clause">
<source>groupby clause</source>
<target state="translated">groupby yan tümcesi</target>
<note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="query_body">
<source>query body</source>
<target state="translated">sorgu gövdesi</target>
<note />
</trans-unit>
<trans-unit id="into_clause">
<source>into clause</source>
<target state="translated">into yan tümcesi</target>
<note>{Locked="into"} "into" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="is_pattern">
<source>is pattern</source>
<target state="translated">is deseni</target>
<note>{Locked="is"} "is" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="deconstruction">
<source>deconstruction</source>
<target state="translated">ayrıştırma</target>
<note />
</trans-unit>
<trans-unit id="tuple">
<source>tuple</source>
<target state="translated">demet</target>
<note />
</trans-unit>
<trans-unit id="local_function">
<source>local function</source>
<target state="translated">yerel işlev</target>
<note />
</trans-unit>
<trans-unit id="out_var">
<source>out variable</source>
<target state="translated">out değişkeni</target>
<note>{Locked="out"} "out" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="ref_local_or_expression">
<source>ref local or expression</source>
<target state="translated">yerel ref veya ifade</target>
<note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="global_statement">
<source>global statement</source>
<target state="translated">global deyimi</target>
<note>{Locked="global"} "global" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="using_directive">
<source>using directive</source>
<target state="translated">using yönergesi</target>
<note />
</trans-unit>
<trans-unit id="event_field">
<source>event field</source>
<target state="translated">olay alanı</target>
<note />
</trans-unit>
<trans-unit id="conversion_operator">
<source>conversion operator</source>
<target state="translated">dönüştürme işleci</target>
<note />
</trans-unit>
<trans-unit id="destructor">
<source>destructor</source>
<target state="translated">yok edici</target>
<note />
</trans-unit>
<trans-unit id="indexer">
<source>indexer</source>
<target state="translated">dizin oluşturucu</target>
<note />
</trans-unit>
<trans-unit id="property_getter">
<source>property getter</source>
<target state="translated">özellik alıcısı</target>
<note />
</trans-unit>
<trans-unit id="indexer_getter">
<source>indexer getter</source>
<target state="translated">dizin oluşturucu alıcısı</target>
<note />
</trans-unit>
<trans-unit id="property_setter">
<source>property setter</source>
<target state="translated">özellik ayarlayıcısı</target>
<note />
</trans-unit>
<trans-unit id="indexer_setter">
<source>indexer setter</source>
<target state="translated">dizin oluşturucu ayarlayıcısı</target>
<note />
</trans-unit>
<trans-unit id="attribute_target">
<source>attribute target</source>
<target state="translated">öznitelik hedefi</target>
<note />
</trans-unit>
<trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments">
<source>'{0}' does not contain a constructor that takes that many arguments.</source>
<target state="translated">'{0}' bu kadar çok sayıda bağımsız değişken alan bir oluşturucu içermiyor.</target>
<note />
</trans-unit>
<trans-unit id="The_name_0_does_not_exist_in_the_current_context">
<source>The name '{0}' does not exist in the current context.</source>
<target state="translated">'{0}' adı geçerli bağlamda yok.</target>
<note />
</trans-unit>
<trans-unit id="Hide_base_member">
<source>Hide base member</source>
<target state="translated">Temel üyeyi gizle</target>
<note />
</trans-unit>
<trans-unit id="Properties">
<source>Properties</source>
<target state="translated">Özellikler</target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_namespace_declaration">
<source>Autoselect disabled due to namespace declaration.</source>
<target state="translated">Ad alanı bildirimi nedeniyle otomatik seçme devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="namespace_name">
<source><namespace name></source>
<target state="translated">< ad alanı adı ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_type_declaration">
<source>Autoselect disabled due to type declaration.</source>
<target state="translated">Tür bildirimine göre devre dışı bırakılanı otomatik olarak seç.</target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration">
<source>Autoselect disabled due to possible deconstruction declaration.</source>
<target state="translated">Otomatik seçim, olası ayrıştırma bildiriminden dolayı devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="Upgrade_this_project_to_csharp_language_version_0">
<source>Upgrade this project to C# language version '{0}'</source>
<target state="translated">Bu projeyi C# '{0}' dil sürümüne yükselt</target>
<note />
</trans-unit>
<trans-unit id="Upgrade_all_csharp_projects_to_language_version_0">
<source>Upgrade all C# projects to language version '{0}'</source>
<target state="translated">Tüm C# projelerini '{0}' dil sürümüne yükselt</target>
<note />
</trans-unit>
<trans-unit id="class_name">
<source><class name></source>
<target state="translated">< sınıf adı ></target>
<note />
</trans-unit>
<trans-unit id="interface_name">
<source><interface name></source>
<target state="translated">< arabirim adı ></target>
<note />
</trans-unit>
<trans-unit id="designation_name">
<source><designation name></source>
<target state="translated">< atama adı ></target>
<note />
</trans-unit>
<trans-unit id="struct_name">
<source><struct name></source>
<target state="translated">< yapı adı ></target>
<note />
</trans-unit>
<trans-unit id="Make_method_async">
<source>Make method async</source>
<target state="translated">Metodu asenkron yap</target>
<note />
</trans-unit>
<trans-unit id="Make_method_async_remain_void">
<source>Make method async (stay void)</source>
<target state="translated">Metodu zaman uyumsuz yap (void olarak bırak)</target>
<note />
</trans-unit>
<trans-unit id="Name">
<source><Name></source>
<target state="translated">< ad ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_member_declaration">
<source>Autoselect disabled due to member declaration</source>
<target state="translated">Üye bildirimi nedeniyle otomatik seçim devre dışı</target>
<note />
</trans-unit>
<trans-unit id="Suggested_name">
<source>(Suggested name)</source>
<target state="translated">(Önerilen ad)</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_function">
<source>Remove unused function</source>
<target state="translated">Kullanılmayan işlevi kaldır</target>
<note />
</trans-unit>
<trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string">
<source>Add parentheses</source>
<target state="translated">Parantez ekle</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_foreach">
<source>Convert to 'foreach'</source>
<target state="translated">'foreach' deyimine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_for">
<source>Convert to 'for'</source>
<target state="translated">'for' deyimine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Invert_if">
<source>Invert if</source>
<target state="translated">if ifadesini tersine çevir</target>
<note />
</trans-unit>
<trans-unit id="Add_Obsolete">
<source>Add [Obsolete]</source>
<target state="translated">Ekle [Eski]</target>
<note />
</trans-unit>
<trans-unit id="Use_0">
<source>Use '{0}'</source>
<target state="translated">'{0}' kullan</target>
<note />
</trans-unit>
<trans-unit id="Introduce_using_statement">
<source>Introduce 'using' statement</source>
<target state="translated">'using' deyimi ekle</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="yield_break_statement">
<source>yield break statement</source>
<target state="translated">yield break deyimi</target>
<note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="yield_return_statement">
<source>yield return statement</source>
<target state="translated">yield return deyimi</target>
<note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CSharpFeaturesResources.resx">
<body>
<trans-unit id="Add_await">
<source>Add 'await'</source>
<target state="translated">'await' ekleyin</target>
<note>{Locked="await"} "await" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_await_and_ConfigureAwaitFalse">
<source>Add 'await' and 'ConfigureAwait(false)'</source>
<target state="translated">'await' ve 'ConfigureAwait(false)' ekleyin</target>
<note>{Locked="await"} "await" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_missing_usings">
<source>Add missing usings</source>
<target state="translated">Eksik usings Ekle</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_remove_braces_for_single_line_control_statements">
<source>Add/remove braces for single-line control statements</source>
<target state="translated">Tek satır denetim deyimleri için küme ayracı ekle/küme ayraçlarını kaldır</target>
<note />
</trans-unit>
<trans-unit id="Allow_unsafe_code_in_this_project">
<source>Allow unsafe code in this project</source>
<target state="translated">Bu projede güvenli olmayan koda izin ver</target>
<note />
</trans-unit>
<trans-unit id="Apply_expression_block_body_preferences">
<source>Apply expression/block body preferences</source>
<target state="translated">İfade/blok gövdesi tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_implicit_explicit_type_preferences">
<source>Apply implicit/explicit type preferences</source>
<target state="translated">Örtük/açık tür tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_inline_out_variable_preferences">
<source>Apply inline 'out' variables preferences</source>
<target state="translated">Satır içi 'out' değişkenlerine ilişkin tercihleri uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_language_framework_type_preferences">
<source>Apply language/framework type preferences</source>
<target state="translated">Dil/çerçeve türü tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_this_qualification_preferences">
<source>Apply 'this.' qualification preferences</source>
<target state="translated">'this.' nitelemesi tercihlerini uygula</target>
<note />
</trans-unit>
<trans-unit id="Apply_using_directive_placement_preferences">
<source>Apply preferred 'using' placement preferences</source>
<target state="translated">Tercih edilen 'using' yerleştirme tercihlerini uygulayın</target>
<note>'using' is a C# keyword and should not be localized</note>
</trans-unit>
<trans-unit id="Assign_out_parameters">
<source>Assign 'out' parameters</source>
<target state="translated">'out' parametreleri ata</target>
<note>{Locked="out"} "out" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Assign_out_parameters_at_start">
<source>Assign 'out' parameters (at start)</source>
<target state="translated">'out' parametreleri ata (başlangıçta)</target>
<note>{Locked="out"} "out" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Assign_to_0">
<source>Assign to '{0}'</source>
<target state="translated">'{0}' öğesine ata</target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration">
<source>Autoselect disabled due to potential pattern variable declaration.</source>
<target state="translated">Otomatik seçim, olası desen değişkeni bildirimi nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="Change_to_as_expression">
<source>Change to 'as' expression</source>
<target state="translated">'as' ifadesine değiştir</target>
<note />
</trans-unit>
<trans-unit id="Change_to_cast">
<source>Change to cast</source>
<target state="translated">Tür dönüştürme olarak değiştir</target>
<note />
</trans-unit>
<trans-unit id="Compare_to_0">
<source>Compare to '{0}'</source>
<target state="translated">'{0}' ile karşılaştır</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_method">
<source>Convert to method</source>
<target state="translated">Yönteme dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_regular_string">
<source>Convert to regular string</source>
<target state="translated">Normal dizeye dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_switch_expression">
<source>Convert to 'switch' expression</source>
<target state="translated">'switch' deyimine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_switch_statement">
<source>Convert to 'switch' statement</source>
<target state="translated">'switch' ifadesine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_verbatim_string">
<source>Convert to verbatim string</source>
<target state="translated">Düz metin dizesine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Declare_as_nullable">
<source>Declare as nullable</source>
<target state="translated">Olarak null olabilecek ilan</target>
<note />
</trans-unit>
<trans-unit id="Fix_return_type">
<source>Fix return type</source>
<target state="translated">Dönüş türünü düzelt</target>
<note />
</trans-unit>
<trans-unit id="Inline_temporary_variable">
<source>Inline temporary variable</source>
<target state="translated">Satır içi geçici değişken</target>
<note />
</trans-unit>
<trans-unit id="Conflict_s_detected">
<source>Conflict(s) detected.</source>
<target state="translated">Çakışmalar algılandı.</target>
<note />
</trans-unit>
<trans-unit id="Make_private_field_readonly_when_possible">
<source>Make private fields readonly when possible</source>
<target state="translated">Özel alanları mümkün olduğunda salt okunur yap</target>
<note />
</trans-unit>
<trans-unit id="Make_ref_struct">
<source>Make 'ref struct'</source>
<target state="translated">'ref struct' yap</target>
<note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note>
</trans-unit>
<trans-unit id="Remove_in_keyword">
<source>Remove 'in' keyword</source>
<target state="translated">'in' anahtar sözcüğünü kaldır</target>
<note>{Locked="in"} "in" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Remove_new_modifier">
<source>Remove 'new' modifier</source>
<target state="translated">'New' değiştiricisini kaldır</target>
<note />
</trans-unit>
<trans-unit id="Reverse_for_statement">
<source>Reverse 'for' statement</source>
<target state="translated">'for' ifadesini tersine çevir</target>
<note>{Locked="for"} "for" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Simplify_lambda_expression">
<source>Simplify lambda expression</source>
<target state="translated">Lambda ifadesini basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Simplify_all_occurrences">
<source>Simplify all occurrences</source>
<target state="translated">Tüm yinelemeleri basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Sort_accessibility_modifiers">
<source>Sort accessibility modifiers</source>
<target state="translated">Erişilebilirlik değiştiricilerini sırala</target>
<note />
</trans-unit>
<trans-unit id="Unseal_class_0">
<source>Unseal class '{0}'</source>
<target state="translated">'{0}' sınıfının mührünü aç</target>
<note />
</trans-unit>
<trans-unit id="Use_recursive_patterns">
<source>Use recursive patterns</source>
<target state="new">Use recursive patterns</target>
<note />
</trans-unit>
<trans-unit id="Warning_Inlining_temporary_into_conditional_method_call">
<source>Warning: Inlining temporary into conditional method call.</source>
<target state="translated">Uyarı: Koşullu yöntem çağrısında geçici öğe satır içinde kullanılıyor.</target>
<note />
</trans-unit>
<trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning">
<source>Warning: Inlining temporary variable may change code meaning.</source>
<target state="translated">Uyarı: Geçici değişkeni satır içinde belirtmek kod anlamını değişebilir.</target>
<note />
</trans-unit>
<trans-unit id="asynchronous_foreach_statement">
<source>asynchronous foreach statement</source>
<target state="translated">zaman uyumsuz foreach deyimi</target>
<note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="asynchronous_using_declaration">
<source>asynchronous using declaration</source>
<target state="translated">zaman uyumsuz using bildirimi</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="extern_alias">
<source>extern alias</source>
<target state="translated">dış diğer ad</target>
<note />
</trans-unit>
<trans-unit id="lambda_expression">
<source><lambda expression></source>
<target state="translated">< lambda ifadesi ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration">
<source>Autoselect disabled due to potential lambda declaration.</source>
<target state="translated">Otomatik seçim, olası lambda bildirimi nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="local_variable_declaration">
<source>local variable declaration</source>
<target state="translated">yerel değişken bildirimi</target>
<note />
</trans-unit>
<trans-unit id="member_name">
<source><member name> = </source>
<target state="translated">< üye adı > = </target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation">
<source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source>
<target state="translated">Otomatik seçim, olası açık adlı anonim tür üyesi oluşturma nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="element_name">
<source><element name> : </source>
<target state="translated">< öğe adı >: </target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation">
<source>Autoselect disabled due to possible tuple type element creation.</source>
<target state="translated">Olası demet türü öğe oluşturma işleminden dolayı Otomatik seçim devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="pattern_variable">
<source><pattern variable></source>
<target state="translated"><desen değişkeni></target>
<note />
</trans-unit>
<trans-unit id="range_variable">
<source><range variable></source>
<target state="translated">< Aralık değişkeni ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration">
<source>Autoselect disabled due to potential range variable declaration.</source>
<target state="translated">Otomatik seçim, olası aralık değişkeni bildirimi nedeniyle devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="Simplify_name_0">
<source>Simplify name '{0}'</source>
<target state="translated">'{0}' adını basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Simplify_member_access_0">
<source>Simplify member access '{0}'</source>
<target state="translated">'{0}' üye erişimini basitleştir</target>
<note />
</trans-unit>
<trans-unit id="Remove_this_qualification">
<source>Remove 'this' qualification</source>
<target state="translated">this' nitelemesini kaldır</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified</source>
<target state="translated">Ad basitleştirilebilir</target>
<note />
</trans-unit>
<trans-unit id="Can_t_determine_valid_range_of_statements_to_extract">
<source>Can't determine valid range of statements to extract</source>
<target state="translated">Ayıklanacak deyimlerin geçerli aralığı belirlenemiyor</target>
<note />
</trans-unit>
<trans-unit id="Not_all_code_paths_return">
<source>Not all code paths return</source>
<target state="translated">Kod yollarından bazıları dönmüyor</target>
<note />
</trans-unit>
<trans-unit id="Selection_does_not_contain_a_valid_node">
<source>Selection does not contain a valid node</source>
<target state="translated">Seçim, geçerli bir düğüm içermiyor</target>
<note />
</trans-unit>
<trans-unit id="Invalid_selection">
<source>Invalid selection.</source>
<target state="translated">Geçersiz seçim.</target>
<note />
</trans-unit>
<trans-unit id="Contains_invalid_selection">
<source>Contains invalid selection.</source>
<target state="translated">Geçersiz seçimi içerir.</target>
<note />
</trans-unit>
<trans-unit id="The_selection_contains_syntactic_errors">
<source>The selection contains syntactic errors</source>
<target state="translated">Seçim söz dizimsel hatalar içeriyor</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_cross_over_preprocessor_directives">
<source>Selection can not cross over preprocessor directives.</source>
<target state="translated">Seçim önişlemci yönergeleriyle çapraz olamaz.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_contain_a_yield_statement">
<source>Selection can not contain a yield statement.</source>
<target state="translated">Seçim bir bırakma ifadesi içeremez.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_contain_throw_statement">
<source>Selection can not contain throw statement.</source>
<target state="translated">Seçim bir atma ifadesi içeremez.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression">
<source>Selection can not be part of constant initializer expression.</source>
<target state="translated">Seçim, sabit başlatıcı ifadesinin parçası olamaz.</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_not_contain_a_pattern_expression">
<source>Selection can not contain a pattern expression.</source>
<target state="translated">Seçim, bir desen ifadesi içeremez.</target>
<note />
</trans-unit>
<trans-unit id="The_selected_code_is_inside_an_unsafe_context">
<source>The selected code is inside an unsafe context.</source>
<target state="translated">Seçili kod güvenli olmayan bir bağlam içinde.</target>
<note />
</trans-unit>
<trans-unit id="No_valid_statement_range_to_extract">
<source>No valid statement range to extract</source>
<target state="translated">Ayıklanacak geçerli deyim aralığı yok</target>
<note />
</trans-unit>
<trans-unit id="deprecated">
<source>deprecated</source>
<target state="translated">kullanım dışı</target>
<note />
</trans-unit>
<trans-unit id="extension">
<source>extension</source>
<target state="translated">uzantı</target>
<note />
</trans-unit>
<trans-unit id="awaitable">
<source>awaitable</source>
<target state="translated">awaitable</target>
<note />
</trans-unit>
<trans-unit id="awaitable_extension">
<source>awaitable, extension</source>
<target state="translated">awaitable, uzantı</target>
<note />
</trans-unit>
<trans-unit id="Organize_Usings">
<source>Organize Usings</source>
<target state="translated">Kullanımları Düzenle</target>
<note />
</trans-unit>
<trans-unit id="Insert_await">
<source>Insert 'await'.</source>
<target state="translated">await' ekle.</target>
<note />
</trans-unit>
<trans-unit id="Make_0_return_Task_instead_of_void">
<source>Make {0} return Task instead of void.</source>
<target state="translated">{0} öğesi boşluk yerine Görev döndürsün.</target>
<note />
</trans-unit>
<trans-unit id="Change_return_type_from_0_to_1">
<source>Change return type from {0} to {1}</source>
<target state="translated">Dönüş türünü {0} değerinden {1} olarak değiştir</target>
<note />
</trans-unit>
<trans-unit id="Replace_return_with_yield_return">
<source>Replace return with yield return</source>
<target state="translated">Dönüşü, bırakma dönüşüyle değiştir</target>
<note />
</trans-unit>
<trans-unit id="Generate_explicit_conversion_operator_in_0">
<source>Generate explicit conversion operator in '{0}'</source>
<target state="translated">'{0}' içinde açık dönüşüm işleci oluştur</target>
<note />
</trans-unit>
<trans-unit id="Generate_implicit_conversion_operator_in_0">
<source>Generate implicit conversion operator in '{0}'</source>
<target state="translated">'{0}' içinde örtük dönüşüm işleci oluştur</target>
<note />
</trans-unit>
<trans-unit id="record_">
<source>record</source>
<target state="translated">kayıt</target>
<note />
</trans-unit>
<trans-unit id="record_struct">
<source>record struct</source>
<target state="new">record struct</target>
<note />
</trans-unit>
<trans-unit id="switch_statement">
<source>switch statement</source>
<target state="translated">switch deyimi</target>
<note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="switch_statement_case_clause">
<source>switch statement case clause</source>
<target state="translated">switch deyimi case yan tümcesi</target>
<note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="try_block">
<source>try block</source>
<target state="translated">try bloğu</target>
<note>{Locked="try"} "try" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="catch_clause">
<source>catch clause</source>
<target state="translated">catch yan tümcesi</target>
<note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="filter_clause">
<source>filter clause</source>
<target state="translated">filter yan tümcesi</target>
<note />
</trans-unit>
<trans-unit id="finally_clause">
<source>finally clause</source>
<target state="translated">finally yan tümcesi</target>
<note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="fixed_statement">
<source>fixed statement</source>
<target state="translated">fixed deyimi</target>
<note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="using_declaration">
<source>using declaration</source>
<target state="translated">using bildirimi</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="using_statement">
<source>using statement</source>
<target state="translated">using deyimi</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="lock_statement">
<source>lock statement</source>
<target state="translated">lock deyimi</target>
<note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="foreach_statement">
<source>foreach statement</source>
<target state="translated">foreach deyimi</target>
<note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="checked_statement">
<source>checked statement</source>
<target state="translated">checked deyimi</target>
<note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="unchecked_statement">
<source>unchecked statement</source>
<target state="translated">unchecked deyimi</target>
<note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="await_expression">
<source>await expression</source>
<target state="translated">await ifadesi</target>
<note>{Locked="await"} "await" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="lambda">
<source>lambda</source>
<target state="translated">lambda</target>
<note />
</trans-unit>
<trans-unit id="anonymous_method">
<source>anonymous method</source>
<target state="translated">anonim yöntem</target>
<note />
</trans-unit>
<trans-unit id="from_clause">
<source>from clause</source>
<target state="translated">from yan tümcesi</target>
<note />
</trans-unit>
<trans-unit id="join_clause">
<source>join clause</source>
<target state="translated">join yan tümcesi</target>
<note>{Locked="join"} "join" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="let_clause">
<source>let clause</source>
<target state="translated">let yan tümcesi</target>
<note>{Locked="let"} "let" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="where_clause">
<source>where clause</source>
<target state="translated">where yan tümcesi</target>
<note>{Locked="where"} "where" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="orderby_clause">
<source>orderby clause</source>
<target state="translated">orderby yan tümcesi</target>
<note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="select_clause">
<source>select clause</source>
<target state="translated">select yan tümcesi</target>
<note>{Locked="select"} "select" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="groupby_clause">
<source>groupby clause</source>
<target state="translated">groupby yan tümcesi</target>
<note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="query_body">
<source>query body</source>
<target state="translated">sorgu gövdesi</target>
<note />
</trans-unit>
<trans-unit id="into_clause">
<source>into clause</source>
<target state="translated">into yan tümcesi</target>
<note>{Locked="into"} "into" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="is_pattern">
<source>is pattern</source>
<target state="translated">is deseni</target>
<note>{Locked="is"} "is" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="deconstruction">
<source>deconstruction</source>
<target state="translated">ayrıştırma</target>
<note />
</trans-unit>
<trans-unit id="tuple">
<source>tuple</source>
<target state="translated">demet</target>
<note />
</trans-unit>
<trans-unit id="local_function">
<source>local function</source>
<target state="translated">yerel işlev</target>
<note />
</trans-unit>
<trans-unit id="out_var">
<source>out variable</source>
<target state="translated">out değişkeni</target>
<note>{Locked="out"} "out" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="ref_local_or_expression">
<source>ref local or expression</source>
<target state="translated">yerel ref veya ifade</target>
<note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="global_statement">
<source>global statement</source>
<target state="translated">global deyimi</target>
<note>{Locked="global"} "global" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="using_directive">
<source>using directive</source>
<target state="translated">using yönergesi</target>
<note />
</trans-unit>
<trans-unit id="event_field">
<source>event field</source>
<target state="translated">olay alanı</target>
<note />
</trans-unit>
<trans-unit id="conversion_operator">
<source>conversion operator</source>
<target state="translated">dönüştürme işleci</target>
<note />
</trans-unit>
<trans-unit id="destructor">
<source>destructor</source>
<target state="translated">yok edici</target>
<note />
</trans-unit>
<trans-unit id="indexer">
<source>indexer</source>
<target state="translated">dizin oluşturucu</target>
<note />
</trans-unit>
<trans-unit id="property_getter">
<source>property getter</source>
<target state="translated">özellik alıcısı</target>
<note />
</trans-unit>
<trans-unit id="indexer_getter">
<source>indexer getter</source>
<target state="translated">dizin oluşturucu alıcısı</target>
<note />
</trans-unit>
<trans-unit id="property_setter">
<source>property setter</source>
<target state="translated">özellik ayarlayıcısı</target>
<note />
</trans-unit>
<trans-unit id="indexer_setter">
<source>indexer setter</source>
<target state="translated">dizin oluşturucu ayarlayıcısı</target>
<note />
</trans-unit>
<trans-unit id="attribute_target">
<source>attribute target</source>
<target state="translated">öznitelik hedefi</target>
<note />
</trans-unit>
<trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments">
<source>'{0}' does not contain a constructor that takes that many arguments.</source>
<target state="translated">'{0}' bu kadar çok sayıda bağımsız değişken alan bir oluşturucu içermiyor.</target>
<note />
</trans-unit>
<trans-unit id="The_name_0_does_not_exist_in_the_current_context">
<source>The name '{0}' does not exist in the current context.</source>
<target state="translated">'{0}' adı geçerli bağlamda yok.</target>
<note />
</trans-unit>
<trans-unit id="Hide_base_member">
<source>Hide base member</source>
<target state="translated">Temel üyeyi gizle</target>
<note />
</trans-unit>
<trans-unit id="Properties">
<source>Properties</source>
<target state="translated">Özellikler</target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_namespace_declaration">
<source>Autoselect disabled due to namespace declaration.</source>
<target state="translated">Ad alanı bildirimi nedeniyle otomatik seçme devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="namespace_name">
<source><namespace name></source>
<target state="translated">< ad alanı adı ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_type_declaration">
<source>Autoselect disabled due to type declaration.</source>
<target state="translated">Tür bildirimine göre devre dışı bırakılanı otomatik olarak seç.</target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration">
<source>Autoselect disabled due to possible deconstruction declaration.</source>
<target state="translated">Otomatik seçim, olası ayrıştırma bildiriminden dolayı devre dışı bırakıldı.</target>
<note />
</trans-unit>
<trans-unit id="Upgrade_this_project_to_csharp_language_version_0">
<source>Upgrade this project to C# language version '{0}'</source>
<target state="translated">Bu projeyi C# '{0}' dil sürümüne yükselt</target>
<note />
</trans-unit>
<trans-unit id="Upgrade_all_csharp_projects_to_language_version_0">
<source>Upgrade all C# projects to language version '{0}'</source>
<target state="translated">Tüm C# projelerini '{0}' dil sürümüne yükselt</target>
<note />
</trans-unit>
<trans-unit id="class_name">
<source><class name></source>
<target state="translated">< sınıf adı ></target>
<note />
</trans-unit>
<trans-unit id="interface_name">
<source><interface name></source>
<target state="translated">< arabirim adı ></target>
<note />
</trans-unit>
<trans-unit id="designation_name">
<source><designation name></source>
<target state="translated">< atama adı ></target>
<note />
</trans-unit>
<trans-unit id="struct_name">
<source><struct name></source>
<target state="translated">< yapı adı ></target>
<note />
</trans-unit>
<trans-unit id="Make_method_async">
<source>Make method async</source>
<target state="translated">Metodu asenkron yap</target>
<note />
</trans-unit>
<trans-unit id="Make_method_async_remain_void">
<source>Make method async (stay void)</source>
<target state="translated">Metodu zaman uyumsuz yap (void olarak bırak)</target>
<note />
</trans-unit>
<trans-unit id="Name">
<source><Name></source>
<target state="translated">< ad ></target>
<note />
</trans-unit>
<trans-unit id="Autoselect_disabled_due_to_member_declaration">
<source>Autoselect disabled due to member declaration</source>
<target state="translated">Üye bildirimi nedeniyle otomatik seçim devre dışı</target>
<note />
</trans-unit>
<trans-unit id="Suggested_name">
<source>(Suggested name)</source>
<target state="translated">(Önerilen ad)</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_function">
<source>Remove unused function</source>
<target state="translated">Kullanılmayan işlevi kaldır</target>
<note />
</trans-unit>
<trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string">
<source>Add parentheses</source>
<target state="translated">Parantez ekle</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_foreach">
<source>Convert to 'foreach'</source>
<target state="translated">'foreach' deyimine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_for">
<source>Convert to 'for'</source>
<target state="translated">'for' deyimine dönüştür</target>
<note />
</trans-unit>
<trans-unit id="Invert_if">
<source>Invert if</source>
<target state="translated">if ifadesini tersine çevir</target>
<note />
</trans-unit>
<trans-unit id="Add_Obsolete">
<source>Add [Obsolete]</source>
<target state="translated">Ekle [Eski]</target>
<note />
</trans-unit>
<trans-unit id="Use_0">
<source>Use '{0}'</source>
<target state="translated">'{0}' kullan</target>
<note />
</trans-unit>
<trans-unit id="Introduce_using_statement">
<source>Introduce 'using' statement</source>
<target state="translated">'using' deyimi ekle</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="yield_break_statement">
<source>yield break statement</source>
<target state="translated">yield break deyimi</target>
<note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="yield_return_statement">
<source>yield return statement</source>
<target state="translated">yield return deyimi</target>
<note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/EditorFeatures/Test/EditAndContinue/RemoteEditAndContinueServiceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue
{
[UseExportProvider]
public class RemoteEditAndContinueServiceTests
{
[ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared]
internal sealed class MockEncServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public MockEncServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new MockEditAndContinueWorkspaceService();
}
[Theory, CombinatorialData]
public async Task Proxy(TestHost testHost)
{
var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost);
if (testHost == TestHost.InProcess)
{
localComposition = localComposition.AddParts(typeof(MockEncServiceFactory));
}
using var localWorkspace = new TestWorkspace(composition: localComposition);
MockEditAndContinueWorkspaceService mockEncService;
var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>();
if (testHost == TestHost.InProcess)
{
Assert.Null(clientProvider);
mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
}
else
{
Assert.NotNull(clientProvider);
clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEncServiceFactory) };
var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false);
var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace();
mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
}
localWorkspace.ChangeSolution(localWorkspace.CurrentSolution.
AddProject("proj", "proj", LanguageNames.CSharp).
AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)).
AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution);
var solution = localWorkspace.CurrentSolution;
var project = solution.Projects.Single();
var document = project.Documents.Single();
var mockDiagnosticService = new MockDiagnosticAnalyzerService();
void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds)
{
AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze);
mockDiagnosticService.DocumentsToReanalyze.Clear();
}
var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource();
var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>();
var emitDiagnosticsClearedCount = 0;
diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args);
diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++;
var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5));
var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}");
var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2);
var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10);
var as1 = new ManagedActiveStatementDebugInfo(
instructionId1,
documentName: "test.cs",
span1.ToSourceSpan(),
flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted);
var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1);
var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate(
methodId2,
delta: 1,
newSpan: new SourceSpan(1, 2, 1, 5));
var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single();
var activeSpans1 = ImmutableArray.Create(
new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id));
var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) =>
{
Assert.Equal(document1.Id, documentId);
Assert.Equal("test.cs", path);
return new(activeSpans1);
});
var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace);
// StartDebuggingSession
IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null;
var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) =>
{
Assert.Equal("proj", solution.Projects.Single().Name);
AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments);
Assert.False(captureAllMatchingDocuments);
Assert.True(reportDiagnostics);
remoteDebuggeeModuleMetadataProvider = debuggerService;
return new DebuggingSessionId(1);
};
var sessionProxy = await proxy.StartDebuggingSessionAsync(
localWorkspace.CurrentSolution,
debuggerService: new MockManagedEditAndContinueDebuggerService()
{
IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"),
GetActiveStatementsImpl = () => ImmutableArray.Create(as1)
},
captureMatchingDocuments: ImmutableArray.Create(document1.Id),
captureAllMatchingDocuments: false,
reportDiagnostics: true,
CancellationToken.None).ConfigureAwait(false);
Contract.ThrowIfNull(sessionProxy);
// BreakStateChanged
mockEncService.BreakStateChangesImpl = (bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) =>
{
Assert.True(inBreakState);
documentsToReanalyze = ImmutableArray.Create(document.Id);
};
await sessionProxy.BreakStateChangedAsync(mockDiagnosticService, inBreakState: true, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id));
var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single();
Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction);
Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan);
Assert.Equal(as1.Flags, activeStatement.Flags);
var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false);
Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability);
// HasChanges
mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) =>
{
Assert.Equal("proj", solution.Projects.Single().Name);
Assert.Equal("test.cs", sourceFilePath);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result);
return true;
};
Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false));
// EmitSolutionUpdate
var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile);
mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) =>
{
var project = solution.Projects.Single();
Assert.Equal("proj", project.Name);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result);
var deltas = ImmutableArray.Create(new ManagedModuleUpdate(
module: moduleId1,
ilDelta: ImmutableArray.Create<byte>(1, 2),
metadataDelta: ImmutableArray.Create<byte>(3, 4),
pdbDelta: ImmutableArray.Create<byte>(5, 6),
updatedMethods: ImmutableArray.Create(0x06000001),
updatedTypes: ImmutableArray.Create(0x02000001),
sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))),
activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())),
exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1)));
var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!;
var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" });
var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" });
var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas);
var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic)));
var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty));
return new(updates, diagnostics, documentsWithRudeEdits);
};
var (updates, _, _) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id));
Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status);
Assert.Equal(1, emitDiagnosticsClearedCount);
emitDiagnosticsClearedCount = 0;
AssertEx.Equal(new[]
{
$"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}",
$"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}"
},
emitDiagnosticsUpdated.Select(update =>
{
var d = update.GetPushDiagnostics(localWorkspace, InternalDiagnosticsOptions.NormalDiagnosticMode).Single();
return $"[{d.ProjectId}] {d.Severity} {d.Id}:" +
(d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") +
$" {d.Message}";
}));
emitDiagnosticsUpdated.Clear();
var delta = updates.Updates.Single();
Assert.Equal(moduleId1, delta.Module);
AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta);
AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta);
AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta);
AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods);
AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes);
var lineEdit = delta.SequencePoints.Single();
Assert.Equal("file.cs", lineEdit.FileName);
AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates);
Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single());
var activeStatements = delta.ActiveStatements.Single();
Assert.Equal(instructionId1.Method.Method, activeStatements.Method);
Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset);
Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan());
// CommitSolutionUpdate
mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) =>
{
documentsToReanalyze = ImmutableArray.Create(document.Id);
};
await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id));
// DiscardSolutionUpdate
var called = false;
mockEncService.DiscardSolutionUpdateImpl = () => called = true;
await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false);
Assert.True(called);
// GetCurrentActiveStatementPosition
mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) =>
{
Assert.Equal("proj", solution.Projects.Single().Name);
Assert.Equal(instructionId1, instructionId);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result);
return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5));
};
Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync(
localWorkspace.CurrentSolution,
activeStatementSpanProvider,
instructionId1,
CancellationToken.None).ConfigureAwait(false));
// IsActiveStatementInExceptionRegion
mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) =>
{
Assert.Equal(instructionId1, instructionId);
return true;
};
Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false));
// GetBaseActiveStatementSpans
var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id);
mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) =>
{
AssertEx.Equal(new[] { document1.Id }, documentIds);
return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1));
};
var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false);
Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single());
// GetDocumentActiveStatementSpans
mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) =>
{
Assert.Equal("test.cs", document.Name);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result);
return ImmutableArray.Create(activeStatementSpan1);
};
var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false);
Assert.Equal(activeStatementSpan1, documentActiveSpans.Single());
// GetDocumentActiveStatementSpans (default array)
mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default;
documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false);
Assert.True(documentActiveSpans.IsDefault);
// OnSourceFileUpdatedAsync
called = false;
mockEncService.OnSourceFileUpdatedImpl = updatedDocument =>
{
Assert.Equal(document.Id, updatedDocument.Id);
called = true;
};
await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false);
Assert.True(called);
// EndDebuggingSession
mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) =>
{
documentsToReanalyze = ImmutableArray.Create(document.Id);
};
await sessionProxy.EndDebuggingSessionAsync(solution, diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id));
Assert.Equal(1, emitDiagnosticsClearedCount);
emitDiagnosticsClearedCount = 0;
Assert.Empty(emitDiagnosticsUpdated);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.EditAndContinue
{
[UseExportProvider]
public class RemoteEditAndContinueServiceTests
{
[ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Test), Shared]
internal sealed class MockEncServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public MockEncServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new MockEditAndContinueWorkspaceService();
}
[Theory, CombinatorialData]
public async Task Proxy(TestHost testHost)
{
var localComposition = EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost);
if (testHost == TestHost.InProcess)
{
localComposition = localComposition.AddParts(typeof(MockEncServiceFactory));
}
using var localWorkspace = new TestWorkspace(composition: localComposition);
MockEditAndContinueWorkspaceService mockEncService;
var clientProvider = (InProcRemoteHostClientProvider?)localWorkspace.Services.GetService<IRemoteHostClientProvider>();
if (testHost == TestHost.InProcess)
{
Assert.Null(clientProvider);
mockEncService = (MockEditAndContinueWorkspaceService)localWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
}
else
{
Assert.NotNull(clientProvider);
clientProvider!.AdditionalRemoteParts = new[] { typeof(MockEncServiceFactory) };
var client = await InProcRemoteHostClient.GetTestClientAsync(localWorkspace).ConfigureAwait(false);
var remoteWorkspace = client.TestData.WorkspaceManager.GetWorkspace();
mockEncService = (MockEditAndContinueWorkspaceService)remoteWorkspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
}
localWorkspace.ChangeSolution(localWorkspace.CurrentSolution.
AddProject("proj", "proj", LanguageNames.CSharp).
AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)).
AddDocument("test.cs", SourceText.From("class C { }", Encoding.UTF8), filePath: "test.cs").Project.Solution);
var solution = localWorkspace.CurrentSolution;
var project = solution.Projects.Single();
var document = project.Documents.Single();
var mockDiagnosticService = new MockDiagnosticAnalyzerService();
void VerifyReanalyzeInvocation(ImmutableArray<DocumentId> documentIds)
{
AssertEx.Equal(documentIds, mockDiagnosticService.DocumentsToReanalyze);
mockDiagnosticService.DocumentsToReanalyze.Clear();
}
var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource();
var emitDiagnosticsUpdated = new List<DiagnosticsUpdatedArgs>();
var emitDiagnosticsClearedCount = 0;
diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args);
diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => emitDiagnosticsClearedCount++;
var span1 = new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5));
var moduleId1 = new Guid("{44444444-1111-1111-1111-111111111111}");
var methodId1 = new ManagedMethodId(moduleId1, token: 0x06000003, version: 2);
var instructionId1 = new ManagedInstructionId(methodId1, ilOffset: 10);
var as1 = new ManagedActiveStatementDebugInfo(
instructionId1,
documentName: "test.cs",
span1.ToSourceSpan(),
flags: ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.PartiallyExecuted);
var methodId2 = new ManagedModuleMethodId(token: 0x06000002, version: 1);
var exceptionRegionUpdate1 = new ManagedExceptionRegionUpdate(
methodId2,
delta: 1,
newSpan: new SourceSpan(1, 2, 1, 5));
var document1 = localWorkspace.CurrentSolution.Projects.Single().Documents.Single();
var activeSpans1 = ImmutableArray.Create(
new ActiveStatementSpan(0, new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)), ActiveStatementFlags.IsNonLeafFrame, document.Id));
var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, path, cancellationToken) =>
{
Assert.Equal(document1.Id, documentId);
Assert.Equal("test.cs", path);
return new(activeSpans1);
});
var proxy = new RemoteEditAndContinueServiceProxy(localWorkspace);
// StartDebuggingSession
IManagedEditAndContinueDebuggerService? remoteDebuggeeModuleMetadataProvider = null;
var debuggingSession = mockEncService.StartDebuggingSessionImpl = (solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics) =>
{
Assert.Equal("proj", solution.Projects.Single().Name);
AssertEx.Equal(new[] { document1.Id }, captureMatchingDocuments);
Assert.False(captureAllMatchingDocuments);
Assert.True(reportDiagnostics);
remoteDebuggeeModuleMetadataProvider = debuggerService;
return new DebuggingSessionId(1);
};
var sessionProxy = await proxy.StartDebuggingSessionAsync(
localWorkspace.CurrentSolution,
debuggerService: new MockManagedEditAndContinueDebuggerService()
{
IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"),
GetActiveStatementsImpl = () => ImmutableArray.Create(as1)
},
captureMatchingDocuments: ImmutableArray.Create(document1.Id),
captureAllMatchingDocuments: false,
reportDiagnostics: true,
CancellationToken.None).ConfigureAwait(false);
Contract.ThrowIfNull(sessionProxy);
// BreakStateChanged
mockEncService.BreakStateChangesImpl = (bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) =>
{
Assert.True(inBreakState);
documentsToReanalyze = ImmutableArray.Create(document.Id);
};
await sessionProxy.BreakStateChangedAsync(mockDiagnosticService, inBreakState: true, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id));
var activeStatement = (await remoteDebuggeeModuleMetadataProvider!.GetActiveStatementsAsync(CancellationToken.None).ConfigureAwait(false)).Single();
Assert.Equal(as1.ActiveInstruction, activeStatement.ActiveInstruction);
Assert.Equal(as1.SourceSpan, activeStatement.SourceSpan);
Assert.Equal(as1.Flags, activeStatement.Flags);
var availability = await remoteDebuggeeModuleMetadataProvider!.GetAvailabilityAsync(moduleId1, CancellationToken.None).ConfigureAwait(false);
Assert.Equal(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForModule, "can't do enc"), availability);
// HasChanges
mockEncService.HasChangesImpl = (solution, activeStatementSpanProvider, sourceFilePath) =>
{
Assert.Equal("proj", solution.Projects.Single().Name);
Assert.Equal("test.cs", sourceFilePath);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result);
return true;
};
Assert.True(await sessionProxy.HasChangesAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, "test.cs", CancellationToken.None).ConfigureAwait(false));
// EmitSolutionUpdate
var diagnosticDescriptor1 = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile);
mockEncService.EmitSolutionUpdateImpl = (solution, activeStatementSpanProvider) =>
{
var project = solution.Projects.Single();
Assert.Equal("proj", project.Name);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result);
var deltas = ImmutableArray.Create(new ManagedModuleUpdate(
module: moduleId1,
ilDelta: ImmutableArray.Create<byte>(1, 2),
metadataDelta: ImmutableArray.Create<byte>(3, 4),
pdbDelta: ImmutableArray.Create<byte>(5, 6),
updatedMethods: ImmutableArray.Create(0x06000001),
updatedTypes: ImmutableArray.Create(0x02000001),
sequencePoints: ImmutableArray.Create(new SequencePointUpdates("file.cs", ImmutableArray.Create(new SourceLineUpdate(1, 2)))),
activeStatements: ImmutableArray.Create(new ManagedActiveStatementUpdate(instructionId1.Method.Method, instructionId1.ILOffset, span1.ToSourceSpan())),
exceptionRegions: ImmutableArray.Create(exceptionRegionUpdate1)));
var syntaxTree = project.Documents.Single().GetSyntaxTreeSynchronously(CancellationToken.None)!;
var documentDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.Create(syntaxTree, TextSpan.FromBounds(1, 2)), new[] { "doc", "some error" });
var projectDiagnostic = Diagnostic.Create(diagnosticDescriptor1, Location.None, new[] { "proj", "some error" });
var updates = new ManagedModuleUpdates(ManagedModuleUpdateStatus.Ready, deltas);
var diagnostics = ImmutableArray.Create((project.Id, ImmutableArray.Create(documentDiagnostic, projectDiagnostic)));
var documentsWithRudeEdits = ImmutableArray.Create((document1.Id, ImmutableArray<RudeEditDiagnostic>.Empty));
return new(updates, diagnostics, documentsWithRudeEdits);
};
var (updates, _, _) = await sessionProxy.EmitSolutionUpdateAsync(localWorkspace.CurrentSolution, activeStatementSpanProvider, mockDiagnosticService, diagnosticUpdateSource, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document1.Id));
Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status);
Assert.Equal(1, emitDiagnosticsClearedCount);
emitDiagnosticsClearedCount = 0;
AssertEx.Equal(new[]
{
$"[{project.Id}] Error ENC1001: test.cs(0, 1, 0, 2): {string.Format(FeaturesResources.ErrorReadingFile, "doc", "some error")}",
$"[{project.Id}] Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "proj", "some error")}"
},
emitDiagnosticsUpdated.Select(update =>
{
var d = update.GetPushDiagnostics(localWorkspace, InternalDiagnosticsOptions.NormalDiagnosticMode).Single();
return $"[{d.ProjectId}] {d.Severity} {d.Id}:" +
(d.DataLocation != null ? $" {d.DataLocation.OriginalFilePath}({d.DataLocation.OriginalStartLine}, {d.DataLocation.OriginalStartColumn}, {d.DataLocation.OriginalEndLine}, {d.DataLocation.OriginalEndColumn}):" : "") +
$" {d.Message}";
}));
emitDiagnosticsUpdated.Clear();
var delta = updates.Updates.Single();
Assert.Equal(moduleId1, delta.Module);
AssertEx.Equal(new byte[] { 1, 2 }, delta.ILDelta);
AssertEx.Equal(new byte[] { 3, 4 }, delta.MetadataDelta);
AssertEx.Equal(new byte[] { 5, 6 }, delta.PdbDelta);
AssertEx.Equal(new[] { 0x06000001 }, delta.UpdatedMethods);
AssertEx.Equal(new[] { 0x02000001 }, delta.UpdatedTypes);
var lineEdit = delta.SequencePoints.Single();
Assert.Equal("file.cs", lineEdit.FileName);
AssertEx.Equal(new[] { new SourceLineUpdate(1, 2) }, lineEdit.LineUpdates);
Assert.Equal(exceptionRegionUpdate1, delta.ExceptionRegions.Single());
var activeStatements = delta.ActiveStatements.Single();
Assert.Equal(instructionId1.Method.Method, activeStatements.Method);
Assert.Equal(instructionId1.ILOffset, activeStatements.ILOffset);
Assert.Equal(span1, activeStatements.NewSpan.ToLinePositionSpan());
// CommitSolutionUpdate
mockEncService.CommitSolutionUpdateImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) =>
{
documentsToReanalyze = ImmutableArray.Create(document.Id);
};
await sessionProxy.CommitSolutionUpdateAsync(mockDiagnosticService, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id));
// DiscardSolutionUpdate
var called = false;
mockEncService.DiscardSolutionUpdateImpl = () => called = true;
await sessionProxy.DiscardSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false);
Assert.True(called);
// GetCurrentActiveStatementPosition
mockEncService.GetCurrentActiveStatementPositionImpl = (solution, activeStatementSpanProvider, instructionId) =>
{
Assert.Equal("proj", solution.Projects.Single().Name);
Assert.Equal(instructionId1, instructionId);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document1.Id, "test.cs", CancellationToken.None).AsTask().Result);
return new LinePositionSpan(new LinePosition(1, 2), new LinePosition(1, 5));
};
Assert.Equal(span1, await sessionProxy.GetCurrentActiveStatementPositionAsync(
localWorkspace.CurrentSolution,
activeStatementSpanProvider,
instructionId1,
CancellationToken.None).ConfigureAwait(false));
// IsActiveStatementInExceptionRegion
mockEncService.IsActiveStatementInExceptionRegionImpl = (solution, instructionId) =>
{
Assert.Equal(instructionId1, instructionId);
return true;
};
Assert.True(await sessionProxy.IsActiveStatementInExceptionRegionAsync(localWorkspace.CurrentSolution, instructionId1, CancellationToken.None).ConfigureAwait(false));
// GetBaseActiveStatementSpans
var activeStatementSpan1 = new ActiveStatementSpan(0, span1, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.PartiallyExecuted, unmappedDocumentId: document1.Id);
mockEncService.GetBaseActiveStatementSpansImpl = (solution, documentIds) =>
{
AssertEx.Equal(new[] { document1.Id }, documentIds);
return ImmutableArray.Create(ImmutableArray.Create(activeStatementSpan1));
};
var baseActiveSpans = await sessionProxy.GetBaseActiveStatementSpansAsync(localWorkspace.CurrentSolution, ImmutableArray.Create(document1.Id), CancellationToken.None).ConfigureAwait(false);
Assert.Equal(activeStatementSpan1, baseActiveSpans.Single().Single());
// GetDocumentActiveStatementSpans
mockEncService.GetAdjustedActiveStatementSpansImpl = (document, activeStatementSpanProvider) =>
{
Assert.Equal("test.cs", document.Name);
AssertEx.Equal(activeSpans1, activeStatementSpanProvider(document.Id, "test.cs", CancellationToken.None).AsTask().Result);
return ImmutableArray.Create(activeStatementSpan1);
};
var documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false);
Assert.Equal(activeStatementSpan1, documentActiveSpans.Single());
// GetDocumentActiveStatementSpans (default array)
mockEncService.GetAdjustedActiveStatementSpansImpl = (document, _) => default;
documentActiveSpans = await sessionProxy.GetAdjustedActiveStatementSpansAsync(document1, activeStatementSpanProvider, CancellationToken.None).ConfigureAwait(false);
Assert.True(documentActiveSpans.IsDefault);
// OnSourceFileUpdatedAsync
called = false;
mockEncService.OnSourceFileUpdatedImpl = updatedDocument =>
{
Assert.Equal(document.Id, updatedDocument.Id);
called = true;
};
await proxy.OnSourceFileUpdatedAsync(document, CancellationToken.None).ConfigureAwait(false);
Assert.True(called);
// EndDebuggingSession
mockEncService.EndDebuggingSessionImpl = (out ImmutableArray<DocumentId> documentsToReanalyze) =>
{
documentsToReanalyze = ImmutableArray.Create(document.Id);
};
await sessionProxy.EndDebuggingSessionAsync(solution, diagnosticUpdateSource, mockDiagnosticService, CancellationToken.None).ConfigureAwait(false);
VerifyReanalyzeInvocation(ImmutableArray.Create(document.Id));
Assert.Equal(1, emitDiagnosticsClearedCount);
emitDiagnosticsClearedCount = 0;
Assert.Empty(emitDiagnosticsUpdated);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/SymbolExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Collections.ObjectModel;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal static class SymbolExtensions
{
internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this MethodSymbol method)
{
var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance();
method.ContainingType.GetAllTypeParameters(builder);
builder.AddRange(method.TypeParameters);
return builder.ToImmutableAndFree();
}
internal static ReadOnlyCollection<byte>? GetCustomTypeInfoPayload(this MethodSymbol method)
{
return method.DeclaringCompilation.GetCustomTypeInfoPayload(method.ReturnType, method.ReturnTypeWithAnnotations.CustomModifiers.Length + method.RefCustomModifiers.Length, RefKind.None);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Collections.ObjectModel;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal static class SymbolExtensions
{
internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this MethodSymbol method)
{
var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance();
method.ContainingType.GetAllTypeParameters(builder);
builder.AddRange(method.TypeParameters);
return builder.ToImmutableAndFree();
}
internal static ReadOnlyCollection<byte>? GetCustomTypeInfoPayload(this MethodSymbol method)
{
return method.DeclaringCompilation.GetCustomTypeInfoPayload(method.ReturnType, method.ReturnTypeWithAnnotations.CustomModifiers.Length + method.RefCustomModifiers.Length, RefKind.None);
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Workspaces/MSBuildTest/Resources/key.snk | $ RSA2 ;y[KBLo@ij)3y)H[+5o_~)<MTJۇשEM0A8K;灵6wg^ yR%K@s[ 9]27 Zf w.~nw
/*UvD
tWdQ~t'w=2W %y#`:(*ILXd,voFhJ9 Uaqlmp
bvwL.2eVTPLϤ&
CNR5T`7}%~bq\bpA^GQkg N$ynq P[\
kB6,jD}V %=4m?\PVq@? \aQӧGaXX^b}aZg f8oOb
)bjWHKpYQn$jeеe1uY!/pSe26 | $ RSA2 ;y[KBLo@ij)3y)H[+5o_~)<MTJۇשEM0A8K;灵6wg^ yR%K@s[ 9]27 Zf w.~nw
/*UvD
tWdQ~t'w=2W %y#`:(*ILXd,voFhJ9 Uaqlmp
bvwL.2eVTPLϤ&
CNR5T`7}%~bq\bpA^GQkg N$ynq P[\
kB6,jD}V %=4m?\PVq@? \aQӧGaXX^b}aZg f8oOb
)bjWHKpYQn$jeеe1uY!/pSe26 | -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/NonSourceAssemblySymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Symbols.PublicModel
{
internal sealed class NonSourceAssemblySymbol : AssemblySymbol
{
private readonly Symbols.AssemblySymbol _underlying;
public NonSourceAssemblySymbol(Symbols.AssemblySymbol underlying)
{
Debug.Assert(underlying is object);
Debug.Assert(!(underlying is Symbols.SourceAssemblySymbol));
_underlying = underlying;
}
internal override Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying;
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Symbols.PublicModel
{
internal sealed class NonSourceAssemblySymbol : AssemblySymbol
{
private readonly Symbols.AssemblySymbol _underlying;
public NonSourceAssemblySymbol(Symbols.AssemblySymbol underlying)
{
Debug.Assert(underlying is object);
Debug.Assert(!(underlying is Symbols.SourceAssemblySymbol));
_underlying = underlying;
}
internal override Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying;
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Tools/AnalyzerRunner/Properties/launchSettings.json | {
"profiles": {
"IDE Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /concurrent /stats /compilerStats"
},
"CSharpEditorFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"CSharpFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.CSharp.Features.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"BasicEditorFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"BasicFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.VisualBasic.Features.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"Microsoft.CodeQuality.CSharp.Analyzers Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(SolutionDir)..\\roslyn-analyzers\\artifacts\\Release\\bin\\Microsoft.CodeAnalysis.FxCopAnalyzers.Package\\netstandard1.3 $(SolutionDir)..\\Orchard\\src\\Orchard.sln /concurrent /iter:4 /stats"
},
"Profile CSharpSimplifyTypeNamesDiagnosticAnalyzer": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.CSharp.Features.dll $(SolutionDir)..\\Orchard\\src\\Orchard.sln /stats /a CSharpSimplifyTypeNamesDiagnosticAnalyzer /editperf:ContentQueryExtensions /edititer:300"
},
"Profile RemoveUnnecessaryCastDiagnosticAnalyzerBase": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /concurrent /stats /a CSharpRemoveUnnecessaryCastDiagnosticAnalyzer /a VisualBasicRemoveUnnecessaryCastDiagnosticAnalyzer"
},
"Profile FormattingDiagnosticAnalyzer": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /a FormattingDiagnosticAnalyzer"
},
"IIncrementalAnalyzer SyntaxTreeInfoIncrementalAnalyzerProvider": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /ia SyntaxTreeInfoIncrementalAnalyzerProvider /persist /profileroot $(SolutionDir)artifacts\\profileRoot"
},
"IIncrementalAnalyzer SymbolTreeInfoIncrementalAnalyzerProvider": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /ia SymbolTreeInfoIncrementalAnalyzerProvider /persist /profileroot $(SolutionDir)artifacts\\profileRoot"
},
"IIncrementalAnalyzer DiagnosticAnalyzerService": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /ia Diagnostic /persist /profileroot $(SolutionDir)artifacts\\profileRoot"
}
}
}
| {
"profiles": {
"IDE Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /concurrent /stats /compilerStats"
},
"CSharpEditorFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"CSharpFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.CSharp.Features.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"BasicEditorFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"BasicFeatures Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.VisualBasic.Features.dll $(SolutionDir)Roslyn.sln /concurrent /stats"
},
"Microsoft.CodeQuality.CSharp.Analyzers Analyzers": {
"commandName": "Project",
"commandLineArgs": "$(SolutionDir)..\\roslyn-analyzers\\artifacts\\Release\\bin\\Microsoft.CodeAnalysis.FxCopAnalyzers.Package\\netstandard1.3 $(SolutionDir)..\\Orchard\\src\\Orchard.sln /concurrent /iter:4 /stats"
},
"Profile CSharpSimplifyTypeNamesDiagnosticAnalyzer": {
"commandName": "Project",
"commandLineArgs": "$(OutDir)Microsoft.CodeAnalysis.CSharp.Features.dll $(SolutionDir)..\\Orchard\\src\\Orchard.sln /stats /a CSharpSimplifyTypeNamesDiagnosticAnalyzer /editperf:ContentQueryExtensions /edititer:300"
},
"Profile RemoveUnnecessaryCastDiagnosticAnalyzerBase": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /concurrent /stats /a CSharpRemoveUnnecessaryCastDiagnosticAnalyzer /a VisualBasicRemoveUnnecessaryCastDiagnosticAnalyzer"
},
"Profile FormattingDiagnosticAnalyzer": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /a FormattingDiagnosticAnalyzer"
},
"IIncrementalAnalyzer SyntaxTreeInfoIncrementalAnalyzerProvider": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /ia SyntaxTreeInfoIncrementalAnalyzerProvider /persist /profileroot $(SolutionDir)artifacts\\profileRoot"
},
"IIncrementalAnalyzer SymbolTreeInfoIncrementalAnalyzerProvider": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /ia SymbolTreeInfoIncrementalAnalyzerProvider /persist /profileroot $(SolutionDir)artifacts\\profileRoot"
},
"IIncrementalAnalyzer DiagnosticAnalyzerService": {
"commandName": "Project",
"commandLineArgs": "$(OutDir) $(SolutionDir)Roslyn.sln /stats /ia Diagnostic /persist /profileroot $(SolutionDir)artifacts\\profileRoot"
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/StatementBlockContext.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the BlockContext
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend NotInheritable Class StatementBlockContext
Inherits ExecutableStatementContext
Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext)
MyBase.New(kind, statement, prevContext)
End Sub
Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode
Dim endStmt As EndBlockStatementSyntax = DirectCast(statement, EndBlockStatementSyntax)
Dim result As VisualBasicSyntaxNode
Select Case BlockKind
Case SyntaxKind.WhileBlock
Dim beginStmt As WhileStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.WhileBlock(beginStmt, Body(), endStmt)
Case SyntaxKind.WithBlock
Dim beginStmt As WithStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.WithBlock(beginStmt, Body(), endStmt)
Case SyntaxKind.SyncLockBlock
Dim beginStmt As SyncLockStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.SyncLockBlock(beginStmt, Body(), endStmt)
Case SyntaxKind.UsingBlock
Dim beginStmt As UsingStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.UsingBlock(beginStmt, Body(), endStmt)
Case Else
Throw ExceptionUtilities.UnexpectedValue(BlockKind)
End Select
FreeStatements()
Return result
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the BlockContext
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend NotInheritable Class StatementBlockContext
Inherits ExecutableStatementContext
Friend Sub New(kind As SyntaxKind, statement As StatementSyntax, prevContext As BlockContext)
MyBase.New(kind, statement, prevContext)
End Sub
Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode
Dim endStmt As EndBlockStatementSyntax = DirectCast(statement, EndBlockStatementSyntax)
Dim result As VisualBasicSyntaxNode
Select Case BlockKind
Case SyntaxKind.WhileBlock
Dim beginStmt As WhileStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.WhileBlock(beginStmt, Body(), endStmt)
Case SyntaxKind.WithBlock
Dim beginStmt As WithStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.WithBlock(beginStmt, Body(), endStmt)
Case SyntaxKind.SyncLockBlock
Dim beginStmt As SyncLockStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.SyncLockBlock(beginStmt, Body(), endStmt)
Case SyntaxKind.UsingBlock
Dim beginStmt As UsingStatementSyntax = Nothing
GetBeginEndStatements(beginStmt, endStmt)
result = SyntaxFactory.UsingBlock(beginStmt, Body(), endStmt)
Case Else
Throw ExceptionUtilities.UnexpectedValue(BlockKind)
End Select
FreeStatements()
Return result
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/CSharp/Test/Symbol/Symbols/GenericConstraintConversionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class GenericConstraintConversionTests : CSharpTestBase
{
/// <summary>
/// 6.1.10, bullet 1
/// </summary>
[Fact]
public void ImplicitInterfaceAndBaseTypeConversions01()
{
var source =
@"interface I { }
interface IA : I { }
interface IB : I { }
class A : IA { }
class B : A, IB { }
class C<T>
where T : B
{
static I i;
static IA ia;
static IB ib;
static A a;
static B b;
static void M<U, V>(T t, U u, V v)
where U : struct, IA
where V : class, IA
{
i = t;
i = u;
i = v;
ia = t;
ia = u;
ia = v;
ib = t;
ib = u;
ib = v;
a = t;
a = u;
b = t;
b = u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (25,14): error CS0266: Cannot implicitly convert type 'U' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "IB").WithLocation(25, 14),
// (26,14): error CS0266: Cannot implicitly convert type 'V' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "IB").WithLocation(26, 14),
// (28,13): error CS0029: Cannot implicitly convert type 'U' to 'A'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "A").WithLocation(28, 13),
// (30,13): error CS0029: Cannot implicitly convert type 'U' to 'B'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "B").WithLocation(30, 13));
}
[Fact]
public void ImplicitInterfaceAndBaseTypeConversions02()
{
var source =
@"interface IA { }
interface IB { }
class A : IA { }
class B : A, IB { }
class C<T, U>
where T : A
where U : B, T
{
static IA ia;
static IB ib;
static void M<V>(T t, U u, V v)
where V : B, T
{
ia = t;
ia = u;
ia = v;
ib = t;
ib = u;
ib = v;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (17,14): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(17, 14));
}
/// <summary>
/// 6.1.10, bullet 2
/// </summary>
[Fact]
public void ImplicitConversionEffectiveInterfaceSet()
{
var source =
@"interface IA { }
interface IB { }
class A : IA { }
class B : IB { }
class C<T, U, V>
where T : A
where U : IB
where V : B, IA
{
static IA a;
static IB b;
static void M(T t, U u, V v)
{
a = t;
a = u;
b = t;
b = u;
}
static void M1<X>(X x) where X : T
{
a = x;
b = x;
}
static void M2<X>(X x) where X : U
{
a = x;
b = x;
}
static void M3<X>(X x) where X : T, U
{
a = x;
b = x;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,13): error CS0266: Cannot implicitly convert type 'U' to 'IA'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "IA").WithLocation(15, 13),
// (16,13): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(16, 13),
// (22,13): error CS0266: Cannot implicitly convert type 'X' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IB").WithLocation(22, 13),
// (26,13): error CS0266: Cannot implicitly convert type 'X' to 'IA'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IA").WithLocation(26, 13));
}
/// <summary>
/// 6.1.10, bullet 3
/// </summary>
[Fact]
public void ImplicitConversionToTypeParameter()
{
var source =
@"class C<T, U, V, W>
where T : U, V
where U : W
{
static T t;
static U u;
static V v;
static W w;
static void M()
{
t = u;
t = v;
t = w;
u = t;
u = v;
u = w;
v = t;
v = u;
v = w;
w = t;
w = u;
w = v;
}
static void M1<X>(X x) where X : T
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
static void M2<X>(X x) where X : U
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
static void M3<X>(X x) where X : U, V, W
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): error CS0266: Cannot implicitly convert type 'U' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "T").WithLocation(11, 13),
// (12,13): error CS0266: Cannot implicitly convert type 'V' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "T").WithLocation(12, 13),
// (13,13): error CS0266: Cannot implicitly convert type 'W' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "T").WithLocation(13, 13),
// (15,13): error CS0029: Cannot implicitly convert type 'V' to 'U'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "U").WithLocation(15, 13),
// (16,13): error CS0266: Cannot implicitly convert type 'W' to 'U'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "U").WithLocation(16, 13),
// (18,13): error CS0029: Cannot implicitly convert type 'U' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "V").WithLocation(18, 13),
// (19,13): error CS0029: Cannot implicitly convert type 'W' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "w").WithArguments("W", "V").WithLocation(19, 13),
// (22,13): error CS0029: Cannot implicitly convert type 'V' to 'W'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "W").WithLocation(22, 13),
// (30,13): error CS0266: Cannot implicitly convert type 'T' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "X").WithLocation(30, 13),
// (31,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(31, 13),
// (32,13): error CS0266: Cannot implicitly convert type 'V' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "X").WithLocation(32, 13),
// (33,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(33, 13),
// (37,13): error CS0029: Cannot implicitly convert type 'X' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "T").WithLocation(37, 13),
// (39,13): error CS0029: Cannot implicitly convert type 'X' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "V").WithLocation(39, 13),
// (41,13): error CS0029: Cannot implicitly convert type 'T' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "X").WithLocation(41, 13),
// (42,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(42, 13),
// (43,13): error CS0029: Cannot implicitly convert type 'V' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "X").WithLocation(43, 13),
// (44,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(44, 13),
// (48,13): error CS0029: Cannot implicitly convert type 'X' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "T").WithLocation(48, 13),
// (52,13): error CS0029: Cannot implicitly convert type 'T' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "X").WithLocation(52, 13),
// (53,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(53, 13),
// (54,13): error CS0266: Cannot implicitly convert type 'V' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "X").WithLocation(54, 13),
// (55,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(55, 13));
}
/// <summary>
/// 6.1.10, bullet 4
/// </summary>
[Fact]
public void ImplicitConversionFromNull()
{
var source =
@"interface I { }
class A { }
class B<T1, T2, T3, T4, T5, T6>
where T2 : class
where T3 : struct
where T4 : new()
where T5: I
where T6: A
{
static T1 F1 = null;
static T2 F2 = null;
static T3 F3 = null;
static T4 F4 = null;
static T5 F5 = null;
static T6 F6 = null;
}";
CreateCompilation(source).VerifyDiagnostics(
// (10,20): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead.
// static T1 F1 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"),
// (12,20): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead.
// static T3 F3 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"),
// (13,20): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead.
// static T4 F4 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"),
// (14,20): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead.
// static T5 F5 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"),
// (11,15): warning CS0414: The field 'B<T1, T2, T3, T4, T5, T6>.F2' is assigned but its value is never used
// static T2 F2 = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F2").WithArguments("B<T1, T2, T3, T4, T5, T6>.F2"),
// (15,15): warning CS0414: The field 'B<T1, T2, T3, T4, T5, T6>.F6' is assigned but its value is never used
// static T6 F6 = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F6").WithArguments("B<T1, T2, T3, T4, T5, T6>.F6")
);
}
/// <summary>
/// 6.1.10, bullet 5
/// </summary>
[Fact]
public void ImplicitReferenceConversionToInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
class A : IA { }
class B : A, IB { }
class C<T, U>
where T : A
where U : B
{
static void M(T t, U u)
{
IA a;
IB b;
a = t;
a = u;
b = t;
b = u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,13): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(15, 13));
}
/// <summary>
/// 6.1.10, bullet 6
/// </summary>
[Fact]
public void ImplicitInterfaceVarianceConversions01()
{
var source =
@"interface IIn<in T> { }
interface IOut<out T> { }
interface IInDerived<T> : IIn<T> { }
interface IOutDerived<T> : IOut<T> { }
class CIn<T> : IIn<T> { }
class COut<T> : IOut<T> { }
class C<T, U>
where T : class
where U : class, T
{
static IIn<T> it;
static IOut<T> ot;
static IIn<U> iu;
static IOut<U> ou;
static void M1<X, Y>(X x, Y y)
where X : IIn<T>
where Y : IIn<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M2<X, Y>(X x, Y y)
where X : IOut<T>
where Y : IOut<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
static void M3<X, Y>(X x, Y y)
where X : IInDerived<T>
where Y : IInDerived<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M4<X, Y>(X x, Y y)
where X : IOutDerived<T>
where Y : IOutDerived<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
static void M5<X, Y>(X x, Y y)
where X : CIn<T>
where Y : CIn<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M6<X, Y>(X x, Y y)
where X : COut<T>
where Y : COut<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (20,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(20, 14),
// (30,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(30, 14),
// (38,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(38, 14),
// (48,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(48, 14),
// (56,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(56, 14),
// (66,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(66, 14));
}
[Fact]
public void ImplicitInterfaceVarianceConversions02()
{
var source =
@"interface I<T> { }
interface IIn<in T> { }
interface IOut<out T> { }
class A<T, U>
where U : T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class B<T, U>
where T : class
where U : T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class C<T, U>
where T : class
where U : class, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it; // valid
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu; // valid
iu = it;
}
}
class D<T, U>
where U : struct, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class E<T, U>
where T : class
where U : struct, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(9, 14),
// (10,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(10, 14),
// (14,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(14, 14),
// (15,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(15, 14),
// (19,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(19, 14),
// (20,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(20, 14),
// (29,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(29, 14),
// (30,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(30, 14),
// (34,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(34, 14),
// (35,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(35, 14),
// (39,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(39, 14),
// (40,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(40, 14),
// (49,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(49, 14),
// (50,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(50, 14),
// (54,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(54, 14),
// (60,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(60, 14),
// (68,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(68, 14),
// (69,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(69, 14),
// (73,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(73, 14),
// (74,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(74, 14),
// (78,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(78, 14),
// (79,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(79, 14),
// (88,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(88, 14),
// (89,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(89, 14),
// (93,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(93, 14),
// (94,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(94, 14),
// (98,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(98, 14),
// (99,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(99, 14));
}
[Fact]
public void ImplicitReferenceConversions()
{
var source =
@"class C<T, U>
where T : U
where U : class
{
static void M<X>(X x, U u) where X : class, T
{
u = x;
x = u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (8,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(8, 13));
}
[Fact]
public void ImplicitBoxingConversions()
{
var source =
@"class C<T, U>
where T : class
where U : T
{
static void M<X, Y>(Y y, T t)
where X : U
where Y : struct, X
{
t = y;
y = t;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (10,13): error CS0266: Cannot implicitly convert type 'T' to 'Y'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "Y").WithLocation(10, 13));
}
[Fact]
public void ImplicitInterfaceConversionsCircularConstraint()
{
var source =
@"interface I { }
class C<T, U>
where T : T
where U : U, I
{
static void M<V>(T t, U u, V v)
where V : U
{
I i;
i = t;
i = u;
i = v;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (2,9): error CS0454: Circular constraint dependency involving 'T' and 'T'
Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(2, 9),
// (2,12): error CS0454: Circular constraint dependency involving 'U' and 'U'
Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(2, 12),
// (10,13): error CS0266: Cannot implicitly convert type 'T' to 'I'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "I").WithLocation(10, 13));
}
/// <summary>
/// 6.2.7, bullet 1
/// </summary>
[Fact]
public void ExplicitBaseClassConversions()
{
var source =
@"class A { }
class B1<T> : A { }
class C<T> : B1<T> { }
class B2 : A { }
class D<T>
where T : C<object>
{
static void M<U>(object o, A a, B1<T> b1t, B1<object> b1o, B2 b2)
where U : C<T>
{
T t;
t = (T)o;
t = (T)a;
t = (T)b1t;
t = (T)b1o;
t = (T)b2;
U u;
u = (U)o;
u = (U)a;
u = (U)b1t;
u = (U)b1o;
u = (U)b2;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (14,13): error CS0030: Cannot convert type 'B1<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)b1t").WithArguments("B1<T>", "T").WithLocation(14, 13),
// (16,13): error CS0030: Cannot convert type 'B2' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)b2").WithArguments("B2", "T").WithLocation(16, 13),
// (21,13): error CS0030: Cannot convert type 'B1<object>' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)b1o").WithArguments("B1<object>", "U").WithLocation(21, 13),
// (22,13): error CS0030: Cannot convert type 'B2' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)b2").WithArguments("B2", "U").WithLocation(22, 13));
}
/// <summary>
/// 6.2.7, bullet 2
/// </summary>
[Fact]
public void ExplicitConversionFromInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
interface IC<T> { }
class A<T>
where T : IA
{
static void M<U>(IA a, IB b, IC<object> co, IC<T> ct)
where U : IC<T>
{
T t;
t = (T)a;
t = (T)b;
t = (T)co;
t = (T)ct;
U u;
u = (U)a;
u = (U)b;
u = (U)co;
u = (U)ct;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// 6.2.7, bullet 3
/// </summary>
[Fact]
public void ExplicitConversionToInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
interface IC<T> { }
class A<T>
where T : IA
{
static void M<U>(T t, U u)
where U : IC<T>
{
IA a;
IB b;
IC<object> co;
IC<T> ct;
b = (IB)t;
co = (IC<object>)t;
ct = (IC<T>)t;
a = (IA)u;
b = (IB)u;
co = (IC<object>)u;
ct = (IC<T>)u;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// 6.2.7, bullet 4
/// </summary>
[Fact]
public void ExplicitConversionToTypeParameter()
{
var source =
@"class C<T, U, V, W>
where T : U, V, W
where U : V, W
{
static T t;
static U u;
static V v;
static W w;
static void M()
{
t = (T)u;
t = (T)v;
t = (T)w;
u = (U)v;
u = (U)w;
v = (V)w;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (16,13): error CS0030: Cannot convert type 'W' to 'V'
// v = (V)w;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(V)w").WithArguments("W", "V"),
// (8,14): warning CS0649: Field 'C<T, U, V, W>.w' is never assigned to, and will always have its default value
// static W w;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "w").WithArguments("C<T, U, V, W>.w", "")
);
}
[Fact]
public void NoConversionsToValueType()
{
var source =
@"abstract class A<T>
{
internal abstract void M<U>(T t, U u) where U : T;
}
class B : A<int>
{
internal override void M<U>(int t, U u)
{
u = t;
u = (U)t;
t = u;
t = (int)u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,13): error CS0029: Cannot implicitly convert type 'int' to 'U'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("int", "U").WithLocation(9, 13),
// (10,13): error CS0030: Cannot convert type 'int' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)t").WithArguments("int", "U").WithLocation(10, 13),
// (11,13): error CS0029: Cannot implicitly convert type 'U' to 'int'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "int").WithLocation(11, 13),
// (12,13): error CS0030: Cannot convert type 'U' to 'int'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)u").WithArguments("U", "int").WithLocation(12, 13));
}
/// <summary>
/// 6.1.10
/// </summary>
[ClrOnlyFact]
public void EmitImplicitConversions()
{
var source =
@"interface I { }
interface I<in T> { }
class A { }
class B : A { }
class C<T1, T2, T3, T4, T5, T6>
where T2 : I
where T3 : T4
where T5 : B
where T6 : I<A>
{
static void F1(object o) { }
static void F2(I i) { }
static void F3(T4 t) { }
static void F5(A a) { }
static void F6(I<B> b) { }
static void M(T1 a, T2 b, T3 c, T5 d, T6 e)
{
// 6.1.10 bullet 1: conversion to base type.
F1(a);
// 6.1.10 bullet 2: conversion to interface.
F2(b);
// 6.1.10 bullet 3: conversion to type parameter.
F3(c);
// 6.1.10 bullet 4: conversion from null to reference type.
// ... no test
// 6.1.10 bullet 5: conversion to reference type.
F5(d);
// 6.1.10 bullet 6: conversion to variance-convertible interface.
F6(e);
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C<T1, T2, T3, T4, T5, T6>.M(T1, T2, T3, T5, T6)",
@"{
// Code size 62 (0x3e)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T1""
IL_0006: call ""void C<T1, T2, T3, T4, T5, T6>.F1(object)""
IL_000b: ldarg.1
IL_000c: box ""T2""
IL_0011: call ""void C<T1, T2, T3, T4, T5, T6>.F2(I)""
IL_0016: ldarg.2
IL_0017: box ""T3""
IL_001c: unbox.any ""T4""
IL_0021: call ""void C<T1, T2, T3, T4, T5, T6>.F3(T4)""
IL_0026: ldarg.3
IL_0027: box ""T5""
IL_002c: call ""void C<T1, T2, T3, T4, T5, T6>.F5(A)""
IL_0031: ldarg.s V_4
IL_0033: box ""T6""
IL_0038: call ""void C<T1, T2, T3, T4, T5, T6>.F6(I<B>)""
IL_003d: ret
}");
}
/// <summary>
/// 6.2.7
/// </summary>
[ClrOnlyFact]
public void EmitExplicitConversions()
{
var source =
@"interface I { }
class C<T1, T2, T3, T4, T5>
where T2 : I
where T5 : T4
{
static void F1(T1 t) { }
static void F2(T2 t) { }
static void F3(I i) { }
static void F5(T5 t) { }
static void M(object a, I b, T3 c, T4 d)
{
// 6.2.7 bullet 1: conversion from base class to type parameter.
F1((T1)a);
// 6.2.7 bullet 2: conversion from interface to type parameter.
F2((T2)b);
// 6.2.7 bullet 3: conversion from type parameter to interface
// not in interface set.
F3((I)c);
// 6.2.7 bullet 4: conversion from type parameter to type parameter.
F5((T5)d);
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C<T1, T2, T3, T4, T5>.M(object, I, T3, T4)",
@"{
// Code size 55 (0x37)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""T1""
IL_0006: call ""void C<T1, T2, T3, T4, T5>.F1(T1)""
IL_000b: ldarg.1
IL_000c: unbox.any ""T2""
IL_0011: call ""void C<T1, T2, T3, T4, T5>.F2(T2)""
IL_0016: ldarg.2
IL_0017: box ""T3""
IL_001c: castclass ""I""
IL_0021: call ""void C<T1, T2, T3, T4, T5>.F3(I)""
IL_0026: ldarg.3
IL_0027: box ""T4""
IL_002c: unbox.any ""T5""
IL_0031: call ""void C<T1, T2, T3, T4, T5>.F5(T5)""
IL_0036: ret
}");
}
[Fact]
public void ImplicitUserDefinedConversion()
{
var source =
@"class C0 { }
class C1
{
public static implicit operator C0(C1 o) { return null; }
}
class C2 { }
class C3<T>
{
public static implicit operator T(C3<T> t) { return default(T); }
}
class C4<T> { }
class C
{
// Implicit conversion from type parameter (success).
static C0 F1<T>(T t) where T : C1 { return t; }
// Implicit conversion from type parameter (error).
static C0 F2<T>(T t) where T : C2 { return t; }
// Implicit conversion to type parameter (success).
static T F3<T>(C3<T> c) { return c; }
// Implicit conversion to type parameter (error).
static T F4<T>(C4<T> c) { return c; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (17,48): error CS0029: Cannot implicitly convert type 'T' to 'C0'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "C0").WithLocation(17, 48),
// (21,38): error CS0029: Cannot implicitly convert type 'C4<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c").WithArguments("C4<T>", "T").WithLocation(21, 38));
}
[Fact]
public void ExplicitUserDefinedConversion()
{
var source =
@"class C0 { }
class C1
{
public static explicit operator C0(C1 o) { return null; }
}
class C2 { }
class C3<T>
{
public static explicit operator T(C3<T> t) { return default(T); }
}
class C4<T> { }
class C
{
// Explicit conversion from type parameter (success).
static C0 F1<T>(T t) where T : C1 { return (C0)t; }
// Explicit conversion from type parameter (error).
static C0 F2<T>(T t) where T : C2 { return (C0)t; }
// Explicit conversion to type parameter (success).
static T F3<T>(C3<T> c) { return (T)c; }
// Explicit conversion to type parameter (error).
static T F4<T>(C4<T> c) { return (T)c; }
}";
// Note: Dev10 also reports "CS0030: Cannot convert type 'T' to 'C0'" in F1<T>(T),
// although there is an explicit conversion from C1 to C0.
CreateCompilation(source).VerifyDiagnostics(
// (17,48): error CS0030: Cannot convert type 'T' to 'C0'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C0)t").WithArguments("T", "C0").WithLocation(17, 48),
// (21,38): error CS0030: Cannot convert type 'C4<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)c").WithArguments("C4<T>", "T").WithLocation(21, 38));
}
/// <summary>
/// Dev10 does not report errors for implicit or explicit conversions between
/// base and derived types if one of those types is a type parameter.
/// </summary>
[Fact]
public void UserDefinedConversionsBaseToFromDerived()
{
var source =
@"class A { }
class B1 : A
{
public static implicit operator A(B1 b) { return null; }
}
class B2 : A
{
public static explicit operator A(B2 b) { return null; }
}
class B3 : A
{
public static implicit operator B3(A a) { return null; }
}
class B4 : A
{
public static explicit operator B4(A a) { return null; }
}
class C1<T> where T : C1<T>
{
public static implicit operator C1<T>(T t) { return null; }
}
class C2<T> where T : C2<T>
{
public static explicit operator C2<T>(T t) { return null; }
}
class C3<T> where T : C3<T>
{
public static implicit operator T(C3<T> c) { return null; }
}
class C4<T> where T : C4<T>
{
public static explicit operator T(C4<T> c) { return null; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,37): error CS0553: 'B1.implicit operator A(B1)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "A").WithArguments("B1.implicit operator A(B1)").WithLocation(4, 37),
// (8,37): error CS0553: 'B2.explicit operator A(B2)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "A").WithArguments("B2.explicit operator A(B2)").WithLocation(8, 37),
// (12,37): error CS0553: 'B3.implicit operator B3(A)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "B3").WithArguments("B3.implicit operator B3(A)").WithLocation(12, 37),
// (16,37): error CS0553: 'B4.explicit operator B4(A)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "B4").WithArguments("B4.explicit operator B4(A)").WithLocation(16, 37));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class GenericConstraintConversionTests : CSharpTestBase
{
/// <summary>
/// 6.1.10, bullet 1
/// </summary>
[Fact]
public void ImplicitInterfaceAndBaseTypeConversions01()
{
var source =
@"interface I { }
interface IA : I { }
interface IB : I { }
class A : IA { }
class B : A, IB { }
class C<T>
where T : B
{
static I i;
static IA ia;
static IB ib;
static A a;
static B b;
static void M<U, V>(T t, U u, V v)
where U : struct, IA
where V : class, IA
{
i = t;
i = u;
i = v;
ia = t;
ia = u;
ia = v;
ib = t;
ib = u;
ib = v;
a = t;
a = u;
b = t;
b = u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (25,14): error CS0266: Cannot implicitly convert type 'U' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "IB").WithLocation(25, 14),
// (26,14): error CS0266: Cannot implicitly convert type 'V' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "IB").WithLocation(26, 14),
// (28,13): error CS0029: Cannot implicitly convert type 'U' to 'A'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "A").WithLocation(28, 13),
// (30,13): error CS0029: Cannot implicitly convert type 'U' to 'B'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "B").WithLocation(30, 13));
}
[Fact]
public void ImplicitInterfaceAndBaseTypeConversions02()
{
var source =
@"interface IA { }
interface IB { }
class A : IA { }
class B : A, IB { }
class C<T, U>
where T : A
where U : B, T
{
static IA ia;
static IB ib;
static void M<V>(T t, U u, V v)
where V : B, T
{
ia = t;
ia = u;
ia = v;
ib = t;
ib = u;
ib = v;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (17,14): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(17, 14));
}
/// <summary>
/// 6.1.10, bullet 2
/// </summary>
[Fact]
public void ImplicitConversionEffectiveInterfaceSet()
{
var source =
@"interface IA { }
interface IB { }
class A : IA { }
class B : IB { }
class C<T, U, V>
where T : A
where U : IB
where V : B, IA
{
static IA a;
static IB b;
static void M(T t, U u, V v)
{
a = t;
a = u;
b = t;
b = u;
}
static void M1<X>(X x) where X : T
{
a = x;
b = x;
}
static void M2<X>(X x) where X : U
{
a = x;
b = x;
}
static void M3<X>(X x) where X : T, U
{
a = x;
b = x;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,13): error CS0266: Cannot implicitly convert type 'U' to 'IA'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "IA").WithLocation(15, 13),
// (16,13): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(16, 13),
// (22,13): error CS0266: Cannot implicitly convert type 'X' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IB").WithLocation(22, 13),
// (26,13): error CS0266: Cannot implicitly convert type 'X' to 'IA'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IA").WithLocation(26, 13));
}
/// <summary>
/// 6.1.10, bullet 3
/// </summary>
[Fact]
public void ImplicitConversionToTypeParameter()
{
var source =
@"class C<T, U, V, W>
where T : U, V
where U : W
{
static T t;
static U u;
static V v;
static W w;
static void M()
{
t = u;
t = v;
t = w;
u = t;
u = v;
u = w;
v = t;
v = u;
v = w;
w = t;
w = u;
w = v;
}
static void M1<X>(X x) where X : T
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
static void M2<X>(X x) where X : U
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
static void M3<X>(X x) where X : U, V, W
{
t = x;
u = x;
v = x;
w = x;
x = t;
x = u;
x = v;
x = w;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,13): error CS0266: Cannot implicitly convert type 'U' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "T").WithLocation(11, 13),
// (12,13): error CS0266: Cannot implicitly convert type 'V' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "T").WithLocation(12, 13),
// (13,13): error CS0266: Cannot implicitly convert type 'W' to 'T'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "T").WithLocation(13, 13),
// (15,13): error CS0029: Cannot implicitly convert type 'V' to 'U'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "U").WithLocation(15, 13),
// (16,13): error CS0266: Cannot implicitly convert type 'W' to 'U'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "U").WithLocation(16, 13),
// (18,13): error CS0029: Cannot implicitly convert type 'U' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "V").WithLocation(18, 13),
// (19,13): error CS0029: Cannot implicitly convert type 'W' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "w").WithArguments("W", "V").WithLocation(19, 13),
// (22,13): error CS0029: Cannot implicitly convert type 'V' to 'W'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "W").WithLocation(22, 13),
// (30,13): error CS0266: Cannot implicitly convert type 'T' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "X").WithLocation(30, 13),
// (31,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(31, 13),
// (32,13): error CS0266: Cannot implicitly convert type 'V' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "X").WithLocation(32, 13),
// (33,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(33, 13),
// (37,13): error CS0029: Cannot implicitly convert type 'X' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "T").WithLocation(37, 13),
// (39,13): error CS0029: Cannot implicitly convert type 'X' to 'V'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "V").WithLocation(39, 13),
// (41,13): error CS0029: Cannot implicitly convert type 'T' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "X").WithLocation(41, 13),
// (42,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(42, 13),
// (43,13): error CS0029: Cannot implicitly convert type 'V' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "v").WithArguments("V", "X").WithLocation(43, 13),
// (44,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(44, 13),
// (48,13): error CS0029: Cannot implicitly convert type 'X' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("X", "T").WithLocation(48, 13),
// (52,13): error CS0029: Cannot implicitly convert type 'T' to 'X'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "X").WithLocation(52, 13),
// (53,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(53, 13),
// (54,13): error CS0266: Cannot implicitly convert type 'V' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "v").WithArguments("V", "X").WithLocation(54, 13),
// (55,13): error CS0266: Cannot implicitly convert type 'W' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "w").WithArguments("W", "X").WithLocation(55, 13));
}
/// <summary>
/// 6.1.10, bullet 4
/// </summary>
[Fact]
public void ImplicitConversionFromNull()
{
var source =
@"interface I { }
class A { }
class B<T1, T2, T3, T4, T5, T6>
where T2 : class
where T3 : struct
where T4 : new()
where T5: I
where T6: A
{
static T1 F1 = null;
static T2 F2 = null;
static T3 F3 = null;
static T4 F4 = null;
static T5 F5 = null;
static T6 F6 = null;
}";
CreateCompilation(source).VerifyDiagnostics(
// (10,20): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead.
// static T1 F1 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"),
// (12,20): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead.
// static T3 F3 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"),
// (13,20): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead.
// static T4 F4 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"),
// (14,20): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead.
// static T5 F5 = null;
Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"),
// (11,15): warning CS0414: The field 'B<T1, T2, T3, T4, T5, T6>.F2' is assigned but its value is never used
// static T2 F2 = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F2").WithArguments("B<T1, T2, T3, T4, T5, T6>.F2"),
// (15,15): warning CS0414: The field 'B<T1, T2, T3, T4, T5, T6>.F6' is assigned but its value is never used
// static T6 F6 = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F6").WithArguments("B<T1, T2, T3, T4, T5, T6>.F6")
);
}
/// <summary>
/// 6.1.10, bullet 5
/// </summary>
[Fact]
public void ImplicitReferenceConversionToInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
class A : IA { }
class B : A, IB { }
class C<T, U>
where T : A
where U : B
{
static void M(T t, U u)
{
IA a;
IB b;
a = t;
a = u;
b = t;
b = u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,13): error CS0266: Cannot implicitly convert type 'T' to 'IB'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "IB").WithLocation(15, 13));
}
/// <summary>
/// 6.1.10, bullet 6
/// </summary>
[Fact]
public void ImplicitInterfaceVarianceConversions01()
{
var source =
@"interface IIn<in T> { }
interface IOut<out T> { }
interface IInDerived<T> : IIn<T> { }
interface IOutDerived<T> : IOut<T> { }
class CIn<T> : IIn<T> { }
class COut<T> : IOut<T> { }
class C<T, U>
where T : class
where U : class, T
{
static IIn<T> it;
static IOut<T> ot;
static IIn<U> iu;
static IOut<U> ou;
static void M1<X, Y>(X x, Y y)
where X : IIn<T>
where Y : IIn<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M2<X, Y>(X x, Y y)
where X : IOut<T>
where Y : IOut<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
static void M3<X, Y>(X x, Y y)
where X : IInDerived<T>
where Y : IInDerived<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M4<X, Y>(X x, Y y)
where X : IOutDerived<T>
where Y : IOutDerived<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
static void M5<X, Y>(X x, Y y)
where X : CIn<T>
where Y : CIn<U>
{
it = x;
it = y;
iu = x;
iu = y;
}
static void M6<X, Y>(X x, Y y)
where X : COut<T>
where Y : COut<U>
{
ot = x;
ot = y;
ou = x;
ou = y;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (20,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(20, 14),
// (30,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(30, 14),
// (38,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(38, 14),
// (48,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(48, 14),
// (56,14): error CS0266: Cannot implicitly convert type 'Y' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Y", "IIn<T>").WithLocation(56, 14),
// (66,14): error CS0266: Cannot implicitly convert type 'X' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("X", "IOut<U>").WithLocation(66, 14));
}
[Fact]
public void ImplicitInterfaceVarianceConversions02()
{
var source =
@"interface I<T> { }
interface IIn<in T> { }
interface IOut<out T> { }
class A<T, U>
where U : T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class B<T, U>
where T : class
where U : T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class C<T, U>
where T : class
where U : class, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it; // valid
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu; // valid
iu = it;
}
}
class D<T, U>
where U : struct, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}
class E<T, U>
where T : class
where U : struct, T
{
static void M(I<T> it, I<U> iu)
{
it = iu;
iu = it;
}
static void M(IIn<T> it, IIn<U> iu)
{
it = iu;
iu = it;
}
static void M(IOut<T> it, IOut<U> iu)
{
it = iu;
iu = it;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(9, 14),
// (10,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(10, 14),
// (14,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(14, 14),
// (15,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(15, 14),
// (19,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(19, 14),
// (20,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(20, 14),
// (29,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(29, 14),
// (30,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(30, 14),
// (34,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(34, 14),
// (35,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(35, 14),
// (39,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(39, 14),
// (40,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(40, 14),
// (49,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(49, 14),
// (50,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(50, 14),
// (54,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(54, 14),
// (60,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(60, 14),
// (68,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(68, 14),
// (69,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(69, 14),
// (73,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(73, 14),
// (74,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(74, 14),
// (78,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(78, 14),
// (79,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(79, 14),
// (88,14): error CS0266: Cannot implicitly convert type 'I<U>' to 'I<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("I<U>", "I<T>").WithLocation(88, 14),
// (89,14): error CS0266: Cannot implicitly convert type 'I<T>' to 'I<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("I<T>", "I<U>").WithLocation(89, 14),
// (93,14): error CS0266: Cannot implicitly convert type 'IIn<U>' to 'IIn<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IIn<U>", "IIn<T>").WithLocation(93, 14),
// (94,14): error CS0266: Cannot implicitly convert type 'IIn<T>' to 'IIn<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IIn<T>", "IIn<U>").WithLocation(94, 14),
// (98,14): error CS0266: Cannot implicitly convert type 'IOut<U>' to 'IOut<T>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "iu").WithArguments("IOut<U>", "IOut<T>").WithLocation(98, 14),
// (99,14): error CS0266: Cannot implicitly convert type 'IOut<T>' to 'IOut<U>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "it").WithArguments("IOut<T>", "IOut<U>").WithLocation(99, 14));
}
[Fact]
public void ImplicitReferenceConversions()
{
var source =
@"class C<T, U>
where T : U
where U : class
{
static void M<X>(X x, U u) where X : class, T
{
u = x;
x = u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (8,13): error CS0266: Cannot implicitly convert type 'U' to 'X'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "u").WithArguments("U", "X").WithLocation(8, 13));
}
[Fact]
public void ImplicitBoxingConversions()
{
var source =
@"class C<T, U>
where T : class
where U : T
{
static void M<X, Y>(Y y, T t)
where X : U
where Y : struct, X
{
t = y;
y = t;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (10,13): error CS0266: Cannot implicitly convert type 'T' to 'Y'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "Y").WithLocation(10, 13));
}
[Fact]
public void ImplicitInterfaceConversionsCircularConstraint()
{
var source =
@"interface I { }
class C<T, U>
where T : T
where U : U, I
{
static void M<V>(T t, U u, V v)
where V : U
{
I i;
i = t;
i = u;
i = v;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (2,9): error CS0454: Circular constraint dependency involving 'T' and 'T'
Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(2, 9),
// (2,12): error CS0454: Circular constraint dependency involving 'U' and 'U'
Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(2, 12),
// (10,13): error CS0266: Cannot implicitly convert type 'T' to 'I'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("T", "I").WithLocation(10, 13));
}
/// <summary>
/// 6.2.7, bullet 1
/// </summary>
[Fact]
public void ExplicitBaseClassConversions()
{
var source =
@"class A { }
class B1<T> : A { }
class C<T> : B1<T> { }
class B2 : A { }
class D<T>
where T : C<object>
{
static void M<U>(object o, A a, B1<T> b1t, B1<object> b1o, B2 b2)
where U : C<T>
{
T t;
t = (T)o;
t = (T)a;
t = (T)b1t;
t = (T)b1o;
t = (T)b2;
U u;
u = (U)o;
u = (U)a;
u = (U)b1t;
u = (U)b1o;
u = (U)b2;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (14,13): error CS0030: Cannot convert type 'B1<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)b1t").WithArguments("B1<T>", "T").WithLocation(14, 13),
// (16,13): error CS0030: Cannot convert type 'B2' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)b2").WithArguments("B2", "T").WithLocation(16, 13),
// (21,13): error CS0030: Cannot convert type 'B1<object>' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)b1o").WithArguments("B1<object>", "U").WithLocation(21, 13),
// (22,13): error CS0030: Cannot convert type 'B2' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)b2").WithArguments("B2", "U").WithLocation(22, 13));
}
/// <summary>
/// 6.2.7, bullet 2
/// </summary>
[Fact]
public void ExplicitConversionFromInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
interface IC<T> { }
class A<T>
where T : IA
{
static void M<U>(IA a, IB b, IC<object> co, IC<T> ct)
where U : IC<T>
{
T t;
t = (T)a;
t = (T)b;
t = (T)co;
t = (T)ct;
U u;
u = (U)a;
u = (U)b;
u = (U)co;
u = (U)ct;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// 6.2.7, bullet 3
/// </summary>
[Fact]
public void ExplicitConversionToInterface()
{
var source =
@"interface IA { }
interface IB : IA { }
interface IC<T> { }
class A<T>
where T : IA
{
static void M<U>(T t, U u)
where U : IC<T>
{
IA a;
IB b;
IC<object> co;
IC<T> ct;
b = (IB)t;
co = (IC<object>)t;
ct = (IC<T>)t;
a = (IA)u;
b = (IB)u;
co = (IC<object>)u;
ct = (IC<T>)u;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
/// <summary>
/// 6.2.7, bullet 4
/// </summary>
[Fact]
public void ExplicitConversionToTypeParameter()
{
var source =
@"class C<T, U, V, W>
where T : U, V, W
where U : V, W
{
static T t;
static U u;
static V v;
static W w;
static void M()
{
t = (T)u;
t = (T)v;
t = (T)w;
u = (U)v;
u = (U)w;
v = (V)w;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (16,13): error CS0030: Cannot convert type 'W' to 'V'
// v = (V)w;
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(V)w").WithArguments("W", "V"),
// (8,14): warning CS0649: Field 'C<T, U, V, W>.w' is never assigned to, and will always have its default value
// static W w;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "w").WithArguments("C<T, U, V, W>.w", "")
);
}
[Fact]
public void NoConversionsToValueType()
{
var source =
@"abstract class A<T>
{
internal abstract void M<U>(T t, U u) where U : T;
}
class B : A<int>
{
internal override void M<U>(int t, U u)
{
u = t;
u = (U)t;
t = u;
t = (int)u;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,13): error CS0029: Cannot implicitly convert type 'int' to 'U'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("int", "U").WithLocation(9, 13),
// (10,13): error CS0030: Cannot convert type 'int' to 'U'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(U)t").WithArguments("int", "U").WithLocation(10, 13),
// (11,13): error CS0029: Cannot implicitly convert type 'U' to 'int'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "u").WithArguments("U", "int").WithLocation(11, 13),
// (12,13): error CS0030: Cannot convert type 'U' to 'int'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)u").WithArguments("U", "int").WithLocation(12, 13));
}
/// <summary>
/// 6.1.10
/// </summary>
[ClrOnlyFact]
public void EmitImplicitConversions()
{
var source =
@"interface I { }
interface I<in T> { }
class A { }
class B : A { }
class C<T1, T2, T3, T4, T5, T6>
where T2 : I
where T3 : T4
where T5 : B
where T6 : I<A>
{
static void F1(object o) { }
static void F2(I i) { }
static void F3(T4 t) { }
static void F5(A a) { }
static void F6(I<B> b) { }
static void M(T1 a, T2 b, T3 c, T5 d, T6 e)
{
// 6.1.10 bullet 1: conversion to base type.
F1(a);
// 6.1.10 bullet 2: conversion to interface.
F2(b);
// 6.1.10 bullet 3: conversion to type parameter.
F3(c);
// 6.1.10 bullet 4: conversion from null to reference type.
// ... no test
// 6.1.10 bullet 5: conversion to reference type.
F5(d);
// 6.1.10 bullet 6: conversion to variance-convertible interface.
F6(e);
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C<T1, T2, T3, T4, T5, T6>.M(T1, T2, T3, T5, T6)",
@"{
// Code size 62 (0x3e)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T1""
IL_0006: call ""void C<T1, T2, T3, T4, T5, T6>.F1(object)""
IL_000b: ldarg.1
IL_000c: box ""T2""
IL_0011: call ""void C<T1, T2, T3, T4, T5, T6>.F2(I)""
IL_0016: ldarg.2
IL_0017: box ""T3""
IL_001c: unbox.any ""T4""
IL_0021: call ""void C<T1, T2, T3, T4, T5, T6>.F3(T4)""
IL_0026: ldarg.3
IL_0027: box ""T5""
IL_002c: call ""void C<T1, T2, T3, T4, T5, T6>.F5(A)""
IL_0031: ldarg.s V_4
IL_0033: box ""T6""
IL_0038: call ""void C<T1, T2, T3, T4, T5, T6>.F6(I<B>)""
IL_003d: ret
}");
}
/// <summary>
/// 6.2.7
/// </summary>
[ClrOnlyFact]
public void EmitExplicitConversions()
{
var source =
@"interface I { }
class C<T1, T2, T3, T4, T5>
where T2 : I
where T5 : T4
{
static void F1(T1 t) { }
static void F2(T2 t) { }
static void F3(I i) { }
static void F5(T5 t) { }
static void M(object a, I b, T3 c, T4 d)
{
// 6.2.7 bullet 1: conversion from base class to type parameter.
F1((T1)a);
// 6.2.7 bullet 2: conversion from interface to type parameter.
F2((T2)b);
// 6.2.7 bullet 3: conversion from type parameter to interface
// not in interface set.
F3((I)c);
// 6.2.7 bullet 4: conversion from type parameter to type parameter.
F5((T5)d);
}
}";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C<T1, T2, T3, T4, T5>.M(object, I, T3, T4)",
@"{
// Code size 55 (0x37)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any ""T1""
IL_0006: call ""void C<T1, T2, T3, T4, T5>.F1(T1)""
IL_000b: ldarg.1
IL_000c: unbox.any ""T2""
IL_0011: call ""void C<T1, T2, T3, T4, T5>.F2(T2)""
IL_0016: ldarg.2
IL_0017: box ""T3""
IL_001c: castclass ""I""
IL_0021: call ""void C<T1, T2, T3, T4, T5>.F3(I)""
IL_0026: ldarg.3
IL_0027: box ""T4""
IL_002c: unbox.any ""T5""
IL_0031: call ""void C<T1, T2, T3, T4, T5>.F5(T5)""
IL_0036: ret
}");
}
[Fact]
public void ImplicitUserDefinedConversion()
{
var source =
@"class C0 { }
class C1
{
public static implicit operator C0(C1 o) { return null; }
}
class C2 { }
class C3<T>
{
public static implicit operator T(C3<T> t) { return default(T); }
}
class C4<T> { }
class C
{
// Implicit conversion from type parameter (success).
static C0 F1<T>(T t) where T : C1 { return t; }
// Implicit conversion from type parameter (error).
static C0 F2<T>(T t) where T : C2 { return t; }
// Implicit conversion to type parameter (success).
static T F3<T>(C3<T> c) { return c; }
// Implicit conversion to type parameter (error).
static T F4<T>(C4<T> c) { return c; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (17,48): error CS0029: Cannot implicitly convert type 'T' to 'C0'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("T", "C0").WithLocation(17, 48),
// (21,38): error CS0029: Cannot implicitly convert type 'C4<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoImplicitConv, "c").WithArguments("C4<T>", "T").WithLocation(21, 38));
}
[Fact]
public void ExplicitUserDefinedConversion()
{
var source =
@"class C0 { }
class C1
{
public static explicit operator C0(C1 o) { return null; }
}
class C2 { }
class C3<T>
{
public static explicit operator T(C3<T> t) { return default(T); }
}
class C4<T> { }
class C
{
// Explicit conversion from type parameter (success).
static C0 F1<T>(T t) where T : C1 { return (C0)t; }
// Explicit conversion from type parameter (error).
static C0 F2<T>(T t) where T : C2 { return (C0)t; }
// Explicit conversion to type parameter (success).
static T F3<T>(C3<T> c) { return (T)c; }
// Explicit conversion to type parameter (error).
static T F4<T>(C4<T> c) { return (T)c; }
}";
// Note: Dev10 also reports "CS0030: Cannot convert type 'T' to 'C0'" in F1<T>(T),
// although there is an explicit conversion from C1 to C0.
CreateCompilation(source).VerifyDiagnostics(
// (17,48): error CS0030: Cannot convert type 'T' to 'C0'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(C0)t").WithArguments("T", "C0").WithLocation(17, 48),
// (21,38): error CS0030: Cannot convert type 'C4<T>' to 'T'
Diagnostic(ErrorCode.ERR_NoExplicitConv, "(T)c").WithArguments("C4<T>", "T").WithLocation(21, 38));
}
/// <summary>
/// Dev10 does not report errors for implicit or explicit conversions between
/// base and derived types if one of those types is a type parameter.
/// </summary>
[Fact]
public void UserDefinedConversionsBaseToFromDerived()
{
var source =
@"class A { }
class B1 : A
{
public static implicit operator A(B1 b) { return null; }
}
class B2 : A
{
public static explicit operator A(B2 b) { return null; }
}
class B3 : A
{
public static implicit operator B3(A a) { return null; }
}
class B4 : A
{
public static explicit operator B4(A a) { return null; }
}
class C1<T> where T : C1<T>
{
public static implicit operator C1<T>(T t) { return null; }
}
class C2<T> where T : C2<T>
{
public static explicit operator C2<T>(T t) { return null; }
}
class C3<T> where T : C3<T>
{
public static implicit operator T(C3<T> c) { return null; }
}
class C4<T> where T : C4<T>
{
public static explicit operator T(C4<T> c) { return null; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,37): error CS0553: 'B1.implicit operator A(B1)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "A").WithArguments("B1.implicit operator A(B1)").WithLocation(4, 37),
// (8,37): error CS0553: 'B2.explicit operator A(B2)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "A").WithArguments("B2.explicit operator A(B2)").WithLocation(8, 37),
// (12,37): error CS0553: 'B3.implicit operator B3(A)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "B3").WithArguments("B3.implicit operator B3(A)").WithLocation(12, 37),
// (16,37): error CS0553: 'B4.explicit operator B4(A)': user-defined conversions to or from a base type are not allowed
Diagnostic(ErrorCode.ERR_ConversionWithBase, "B4").WithArguments("B4.explicit operator B4(A)").WithLocation(16, 37));
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/Compilers/Core/Portable/CommandLine/ErrorLogOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
/// <summary>
/// Options controlling the generation of a SARIF log file containing compilation or analyzer diagnostics.
/// </summary>
public sealed class ErrorLogOptions
{
/// <summary>
/// Absolute path of the error log file.
/// </summary>
public string Path { get; }
/// <summary>
/// Version of the SARIF format used in the error log.
/// </summary>
public SarifVersion SarifVersion { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ErrorLogOptions"/> class.
/// </summary>
/// <param name="path">Absolute path of the error log file.</param>
/// <param name="sarifVersion">Version of the SARIF format used in the error log.</param>
public ErrorLogOptions(string path, SarifVersion sarifVersion)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
Path = path;
SarifVersion = sarifVersion;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
/// <summary>
/// Options controlling the generation of a SARIF log file containing compilation or analyzer diagnostics.
/// </summary>
public sealed class ErrorLogOptions
{
/// <summary>
/// Absolute path of the error log file.
/// </summary>
public string Path { get; }
/// <summary>
/// Version of the SARIF format used in the error log.
/// </summary>
public SarifVersion SarifVersion { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ErrorLogOptions"/> class.
/// </summary>
/// <param name="path">Absolute path of the error log file.</param>
/// <param name="sarifVersion">Version of the SARIF format used in the error log.</param>
public ErrorLogOptions(string path, SarifVersion sarifVersion)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
Path = path;
SarifVersion = sarifVersion;
}
}
}
| -1 |
dotnet/roslyn | 56,011 | React to string comparison changing on .NET Core | The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | jaredpar | "2021-08-30T17:18:52Z" | "2021-08-30T20:20:04Z" | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | React to string comparison changing on .NET Core. The default sort order for `char` / `string` changed on .NET Core. This
impacted a number of our tests which weren't explicitly using ordinal to
compare strings. The fix here makes our tests run consistently across the
various versions of .NET Core and .NET Framework
https://github.com/dotnet/runtime/issues/43956 | ./src/VisualStudio/Core/Test/GenerateType/GenerateTypeViewModelTests.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.IO
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.GenerateType
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.ProjectManagement
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.GenerateType
<[UseExportProvider]>
Public Class GenerateTypeViewModelTests
Private Shared ReadOnly s_assembly1_Name As String = "Assembly1"
Private Shared ReadOnly s_test1_Name As String = "Test1"
Private Shared ReadOnly s_submit_failed_unexpectedly As String = "Submit failed unexpectedly."
Private Shared ReadOnly s_submit_passed_unexpectedly As String = "Submit passed unexpectedly. Submit should fail here"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeExistingFileCSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#")
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Goo", viewModel.TypeName)
Assert.Equal("Goo.cs", viewModel.FileName)
Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name)
Assert.Equal(s_test1_Name + ".cs", viewModel.SelectedDocument.Name)
Assert.Equal(True, viewModel.IsExistingFile)
' Set the Radio to new file
viewModel.IsNewFile = True
Assert.Equal(True, viewModel.IsNewFile)
Assert.Equal(False, viewModel.IsExistingFile)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeExistingFileVisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
Module Program
Sub Main(args As String())
Dim x As A.B.Goo$$ = Nothing
End Sub
End Module
Namespace A
Namespace B
End Namespace
End Namespace"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "Visual Basic")
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Goo", viewModel.TypeName)
Assert.Equal("Goo.vb", viewModel.FileName)
Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name)
Assert.Equal(s_test1_Name + ".vb", viewModel.SelectedDocument.Name)
Assert.Equal(True, viewModel.IsExistingFile)
' Set the Radio to new file
viewModel.IsNewFile = True
Assert.Equal(True, viewModel.IsNewFile)
Assert.Equal(False, viewModel.IsExistingFile)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeNewFileBothLanguage() As Task
Dim documentContentMarkup = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\")
viewModel.IsNewFile = True
' Feed a filename and check if the change is effective
viewModel.FileName = "Wow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.Equal("Wow.cs", viewModel.FileName)
viewModel.FileName = "Goo\Bar\Woow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.Equal("Woow.cs", viewModel.FileName)
Assert.Equal(2, viewModel.Folders.Count)
Assert.Equal("Goo", viewModel.Folders(0))
Assert.Equal("Bar", viewModel.Folders(1))
viewModel.FileName = "\ name has space \ Goo \Bar\ Woow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.Equal("Woow.cs", viewModel.FileName)
Assert.Equal(3, viewModel.Folders.Count)
Assert.Equal("name has space", viewModel.Folders(0))
Assert.Equal("Goo", viewModel.Folders(1))
Assert.Equal("Bar", viewModel.Folders(2))
' Set it to invalid identifier
viewModel.FileName = "w?d"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
viewModel.FileName = "wow\w?d"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
viewModel.FileName = "w?d\wdd"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeProjectChangeAndDependencyBothLanguage() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true">
<ProjectReference>CS1</ProjectReference>
</Project>
<Project Language="C#" AssemblyName="CS3" CommonReferences="true">
<ProjectReference>CS2</ProjectReference>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
<Document FilePath="Test3.vb"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
' Only 2 Projects can be selected because CS2 and CS3 will introduce cyclic dependency
Assert.Equal(2, viewModel.ProjectList.Count)
Assert.Equal(2, viewModel.DocumentList.Count())
viewModel.DocumentSelectIndex = 1
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
Dim monitor = New PropertyChangedTestMonitor(viewModel)
' Check to see if the values are reset when there is a change in the project selection
viewModel.SelectedProject = projectToSelect
Assert.Equal(2, viewModel.DocumentList.Count())
Assert.Equal(0, viewModel.DocumentSelectIndex)
Assert.Equal(1, viewModel.ProjectSelectIndex)
monitor.VerifyExpectations()
monitor.Detach()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeDisableExistingFileForEmptyProject() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true"/>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if the option for Existing File is disabled
Assert.Equal(0, viewModel.DocumentList.Count())
Assert.Equal(False, viewModel.IsExistingFileEnabled)
' Select the project CS1 which has documents
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if the option for Existing File is enabled
Assert.Equal(2, viewModel.DocumentList.Count())
Assert.Equal(True, viewModel.IsExistingFileEnabled)
End Function
<WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeAllowPublicAccessOnlyForGenerationIntoOtherProject() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true"/>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
viewModel.SelectedAccessibilityString = "Default"
' Check if the AccessKind List is enabled
Assert.Equal(True, viewModel.IsAccessListEnabled)
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if access kind is set to Public and the AccessKind is set to be disabled
Assert.Equal(2, viewModel.AccessSelectIndex)
Assert.Equal(False, viewModel.IsAccessListEnabled)
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if AccessKind list is enabled again
Assert.Equal(True, viewModel.IsAccessListEnabled)
End Function
<WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_CSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
[Goo$$]
class Program
{
static void Main(string[] args)
{
}
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("class", viewModel.KindList(0))
Assert.Equal("GooAttribute", viewModel.TypeName)
End Function
<WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_VisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
<Blah$$>
Class C
End Class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Class", viewModel.KindList(0))
Assert.Equal("BlahAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithCapsAttribute_VisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
<GooAttribute$$>
Public class CCC
End class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithoutCapsAttribute_VisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
<Gooattribute$$>
Public class CCC
End class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooattributeAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithCapsAttribute_CSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
[GooAttribute$$]
public class CCC
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithoutCapsAttribute_CSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
[Gooattribute$$]
public class CCC
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooattributeAttribute", viewModel.TypeName)
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_1() As Task
Dim documentContentMarkup = <Text><![CDATA[
public class C : $$D
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.BaseList)
' Check if interface, class is present
Assert.Equal(2, viewModel.KindList.Count)
Assert.Equal("class", viewModel.KindList(0))
Assert.Equal("interface", viewModel.KindList(1))
' Check if all Accessibility are present
Assert.Equal(3, viewModel.AccessList.Count)
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_2() As Task
Dim documentContentMarkup = <Text><![CDATA[
public interface CCC : $$DDD
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True)
' Check if interface, class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("interface", viewModel.KindList(0))
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("public", viewModel.AccessList(0))
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_1() As Task
Dim documentContentMarkup = <Text><![CDATA[
Public Class C
Implements $$D
End Class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=False)
' Check if only Interface is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Interface", viewModel.KindList(0))
Assert.Equal(3, viewModel.AccessList.Count)
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_2() As Task
Dim documentContentMarkup = <Text><![CDATA[
Public Class CC
Inherits $$DD
End Class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Class", viewModel.KindList(0))
' Check if only Public is present
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("Public", viewModel.AccessList(0))
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_3() As Task
Dim documentContentMarkup = <Text><![CDATA[
Public Interface CCC
Inherits $$DDD
End Interface]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Interface", viewModel.KindList(0))
' Check if only Public is present
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("Public", viewModel.AccessList(0))
End Function
<WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithModuleOption() As Task
Dim workspaceXml = <Workspace>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test1.vb">
Module Program
Sub Main(args As String())
Dim s as A.$$B.C
End Sub
End Module
Namespace A
End Namespace </Document>
</Project>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true"/>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "", typeKindvalue:=TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)
' Check if Module is present in addition to the normal options
Assert.Equal(3, viewModel.KindList.Count)
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' C# does not have Module
Assert.Equal(2, viewModel.KindList.Count)
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
viewModel.SelectedProject = projectToSelect
Assert.Equal(3, viewModel.KindList.Count)
End Function
<WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeFileExtensionUpdate() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
Goo$$ bar;
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
' Assert the current display
Assert.Equal(viewModel.FileName, "Goo.cs")
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
viewModel.SelectedProject = projectToSelect
' Assert the new current display
Assert.Equal(viewModel.FileName, "Goo.vb")
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Assert the display is back to the way it was before
Assert.Equal(viewModel.FileName, "Goo.cs")
' Set the name with vb extension
viewModel.FileName = "Goo.vb"
' On focus change,we trigger this method
viewModel.UpdateFileNameExtension()
' Assert that the filename changes accordingly
Assert.Equal(viewModel.FileName, "Goo.cs")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeExcludeGeneratedDocumentsFromList() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">$$</Document>
<Document FilePath="Test2.cs"></Document>
<Document FilePath="TemporaryGeneratedFile_test.cs"></Document>
<Document FilePath="AssemblyInfo.cs"></Document>
<Document FilePath="Test3.cs"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp)
Dim expectedDocuments = {"Test1.cs", "Test2.cs", "AssemblyInfo.cs", "Test3.cs"}
Assert.Equal(expectedDocuments, viewModel.DocumentList.Select(Function(d) d.Document.Name).ToArray())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeIntoGeneratedDocument() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test.generated.cs">
class Program
{
static void Main(string[] args)
{
Goo$$ bar;
}
}
</Document>
<Document FilePath="Test2.cs"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp)
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Goo", viewModel.TypeName)
Assert.Equal("Goo.cs", viewModel.FileName)
Assert.Equal("Test.generated.cs", viewModel.SelectedDocument.Name)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeNewFileNameOptions() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true" FilePath="C:\A\B\CS1.csproj">
<Document FilePath="C:\A\B\CDE\F\Test1.cs">
class Program
{
static void Main(string[] args)
{
Goo$$ bar;
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
<Document FilePath="C:\A\B\ExistingFile.cs"></Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
</Project>
</Workspace>
Dim projectFolder = PopulateProjectFolders(New List(Of String)(), "\outer\", "\outer\inner\")
Dim viewModel = Await GetViewModelAsync(workspaceXml, "", projectFolders:=projectFolder)
viewModel.IsNewFile = True
' Assert the current display
Assert.Equal(viewModel.FileName, "Goo.cs")
' Set the folder to \outer\
viewModel.FileName = viewModel.ProjectFolders(0)
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename to \\something.cs
viewModel.FileName = "\\ExistingFile.cs"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename to an existing file
viewModel.FileName = "..\..\ExistingFile.cs"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename to empty
viewModel.FileName = " "
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename with more than permissible characters
viewModel.FileName = "sjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdfsjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdf.cs"
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename with keywords
viewModel.FileName = "com1\goo.cs"
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename with ".."
viewModel.FileName = "..\..\goo.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
' Set the Filename with ".."
viewModel.FileName = "..\.\..\.\goo.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
End Function
<WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeIntoNewFileWithInvalidIdentifierFolderName() As Task
Dim documentContentMarkupCSharp = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\")
viewModel.IsNewFile = True
Dim foldersAreInvalid = "Folders are not valid identifiers"
viewModel.FileName = "123\456\Wow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "@@@@\######\Woow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "....a\.....b\Wow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
Dim documentContentMarkupVB = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
viewModel = Await GetViewModelAsync(documentContentMarkupVB, "Visual Basic", projectRootFilePath:="C:\OuterFolder1\InnerFolder1\")
viewModel.IsNewFile = True
viewModel.FileName = "123\456\Wow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "@@@@\######\Woow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "....a\.....b\Wow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
End Function
<WorkItem(898563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898563")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateType_DontGenerateIntoExistingFile() As Task
' Get a Temp Folder Path
Dim projectRootFolder = Path.GetTempPath()
' Get a random filename
Dim randomFileName = Path.GetRandomFileName()
' Get the final combined path of the file
Dim pathString = Path.Combine(projectRootFolder, randomFileName)
' Create the file
Dim fs = File.Create(pathString)
Dim bytearray = New Byte() {0, 1}
fs.Write(bytearray, 0, bytearray.Length)
fs.Close()
Dim documentContentMarkupCSharp = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:=projectRootFolder)
viewModel.IsNewFile = True
viewModel.FileName = randomFileName
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Cleanup
File.Delete(pathString)
End Function
Private Function PopulateProjectFolders(list As List(Of String), ParamArray values As String()) As List(Of String)
list.AddRange(values)
Return list
End Function
Private Function GetOneProjectWorkspace(
documentContent As XElement,
languageName As String,
projectName As String,
documentName As String,
projectRootFilePath As String) As XElement
Dim documentNameWithExtension = documentName + If(languageName = "C#", ".cs", ".vb")
If projectRootFilePath Is Nothing Then
Return <Workspace>
<Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true">
<Document FilePath=<%= documentNameWithExtension %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
Else
Dim projectFilePath As String = projectRootFilePath + projectName + If(languageName = "C#", ".csproj", ".vbproj")
Dim documentFilePath As String = projectRootFilePath + documentNameWithExtension
Return <Workspace>
<Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true" FilePath=<%= projectFilePath %>>
<Document FilePath=<%= documentFilePath %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
End If
End Function
Private Async Function GetViewModelAsync(
content As XElement,
languageName As String,
Optional isNewFile As Boolean = False,
Optional accessSelectString As String = "",
Optional kindSelectString As String = "",
Optional projectName As String = "Assembly1",
Optional documentName As String = "Test1",
Optional typeKindvalue As TypeKindOptions = TypeKindOptions.AllOptions,
Optional isPublicOnlyAccessibility As Boolean = False,
Optional isAttribute As Boolean = False,
Optional projectFolders As List(Of String) = Nothing,
Optional projectRootFilePath As String = Nothing) As Tasks.Task(Of GenerateTypeDialogViewModel)
Dim workspaceXml = If(content.Name.LocalName = "Workspace", content, GetOneProjectWorkspace(content, languageName, projectName, documentName, projectRootFilePath))
Using workspace = TestWorkspace.Create(workspaceXml)
Dim testDoc = workspace.Documents.SingleOrDefault(Function(d) d.CursorPosition.HasValue)
Assert.NotNull(testDoc)
Dim document = workspace.CurrentSolution.GetDocument(testDoc.Id)
Dim tree = Await document.GetSyntaxTreeAsync()
Dim token = Await tree.GetTouchingWordAsync(testDoc.CursorPosition.Value, document.GetLanguageService(Of ISyntaxFactsService)(), CancellationToken.None)
Dim typeName = token.ToString()
Dim testProjectManagementService As IProjectManagementService = Nothing
If projectFolders IsNot Nothing Then
testProjectManagementService = New TestProjectManagementService(projectFolders)
End If
Dim syntaxFactsService = document.GetLanguageService(Of ISyntaxFactsService)()
Return New GenerateTypeDialogViewModel(
document,
New TestNotificationService(),
testProjectManagementService,
syntaxFactsService,
New GenerateTypeDialogOptions(isPublicOnlyAccessibility, typeKindvalue, isAttribute),
typeName,
If(document.Project.Language = LanguageNames.CSharp, ".cs", ".vb"),
isNewFile,
accessSelectString,
kindSelectString)
End Using
End Function
End Class
Friend Class TestProjectManagementService
Implements IProjectManagementService
Private ReadOnly _projectFolders As List(Of String)
Public Sub New(projectFolders As List(Of String))
Me._projectFolders = projectFolders
End Sub
Public Function GetDefaultNamespace(project As Project, workspace As Microsoft.CodeAnalysis.Workspace) As String Implements IProjectManagementService.GetDefaultNamespace
Return ""
End Function
Public Function GetFolders(projectId As ProjectId, workspace As Microsoft.CodeAnalysis.Workspace) As IList(Of String) Implements IProjectManagementService.GetFolders
Return Me._projectFolders
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.GenerateType
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.ProjectManagement
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.GenerateType
<[UseExportProvider]>
Public Class GenerateTypeViewModelTests
Private Shared ReadOnly s_assembly1_Name As String = "Assembly1"
Private Shared ReadOnly s_test1_Name As String = "Test1"
Private Shared ReadOnly s_submit_failed_unexpectedly As String = "Submit failed unexpectedly."
Private Shared ReadOnly s_submit_passed_unexpectedly As String = "Submit passed unexpectedly. Submit should fail here"
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeExistingFileCSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#")
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Goo", viewModel.TypeName)
Assert.Equal("Goo.cs", viewModel.FileName)
Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name)
Assert.Equal(s_test1_Name + ".cs", viewModel.SelectedDocument.Name)
Assert.Equal(True, viewModel.IsExistingFile)
' Set the Radio to new file
viewModel.IsNewFile = True
Assert.Equal(True, viewModel.IsNewFile)
Assert.Equal(False, viewModel.IsExistingFile)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeExistingFileVisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
Module Program
Sub Main(args As String())
Dim x As A.B.Goo$$ = Nothing
End Sub
End Module
Namespace A
Namespace B
End Namespace
End Namespace"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "Visual Basic")
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Goo", viewModel.TypeName)
Assert.Equal("Goo.vb", viewModel.FileName)
Assert.Equal(s_assembly1_Name, viewModel.SelectedProject.Name)
Assert.Equal(s_test1_Name + ".vb", viewModel.SelectedDocument.Name)
Assert.Equal(True, viewModel.IsExistingFile)
' Set the Radio to new file
viewModel.IsNewFile = True
Assert.Equal(True, viewModel.IsNewFile)
Assert.Equal(False, viewModel.IsExistingFile)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeNewFileBothLanguage() As Task
Dim documentContentMarkup = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\")
viewModel.IsNewFile = True
' Feed a filename and check if the change is effective
viewModel.FileName = "Wow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.Equal("Wow.cs", viewModel.FileName)
viewModel.FileName = "Goo\Bar\Woow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.Equal("Woow.cs", viewModel.FileName)
Assert.Equal(2, viewModel.Folders.Count)
Assert.Equal("Goo", viewModel.Folders(0))
Assert.Equal("Bar", viewModel.Folders(1))
viewModel.FileName = "\ name has space \ Goo \Bar\ Woow"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.Equal("Woow.cs", viewModel.FileName)
Assert.Equal(3, viewModel.Folders.Count)
Assert.Equal("name has space", viewModel.Folders(0))
Assert.Equal("Goo", viewModel.Folders(1))
Assert.Equal("Bar", viewModel.Folders(2))
' Set it to invalid identifier
viewModel.FileName = "w?d"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
viewModel.FileName = "wow\w?d"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
viewModel.FileName = "w?d\wdd"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeProjectChangeAndDependencyBothLanguage() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true">
<ProjectReference>CS1</ProjectReference>
</Project>
<Project Language="C#" AssemblyName="CS3" CommonReferences="true">
<ProjectReference>CS2</ProjectReference>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
<Document FilePath="Test3.vb"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
' Only 2 Projects can be selected because CS2 and CS3 will introduce cyclic dependency
Assert.Equal(2, viewModel.ProjectList.Count)
Assert.Equal(2, viewModel.DocumentList.Count())
viewModel.DocumentSelectIndex = 1
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
Dim monitor = New PropertyChangedTestMonitor(viewModel)
' Check to see if the values are reset when there is a change in the project selection
viewModel.SelectedProject = projectToSelect
Assert.Equal(2, viewModel.DocumentList.Count())
Assert.Equal(0, viewModel.DocumentSelectIndex)
Assert.Equal(1, viewModel.ProjectSelectIndex)
monitor.VerifyExpectations()
monitor.Detach()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeDisableExistingFileForEmptyProject() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true"/>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if the option for Existing File is disabled
Assert.Equal(0, viewModel.DocumentList.Count())
Assert.Equal(False, viewModel.IsExistingFileEnabled)
' Select the project CS1 which has documents
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if the option for Existing File is enabled
Assert.Equal(2, viewModel.DocumentList.Count())
Assert.Equal(True, viewModel.IsExistingFileEnabled)
End Function
<WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeAllowPublicAccessOnlyForGenerationIntoOtherProject() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="C#" AssemblyName="CS2" CommonReferences="true"/>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
viewModel.SelectedAccessibilityString = "Default"
' Check if the AccessKind List is enabled
Assert.Equal(True, viewModel.IsAccessListEnabled)
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS2").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if access kind is set to Public and the AccessKind is set to be disabled
Assert.Equal(2, viewModel.AccessSelectIndex)
Assert.Equal(False, viewModel.IsAccessListEnabled)
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Check if AccessKind list is enabled again
Assert.Equal(True, viewModel.IsAccessListEnabled)
End Function
<WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_CSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
[Goo$$]
class Program
{
static void Main(string[] args)
{
}
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("class", viewModel.KindList(0))
Assert.Equal("GooAttribute", viewModel.TypeName)
End Function
<WorkItem(858815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858815")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeAllowClassTypeKindForAttribute_VisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
<Blah$$>
Class C
End Class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Attribute, isAttribute:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Class", viewModel.KindList(0))
Assert.Equal("BlahAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithCapsAttribute_VisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
<GooAttribute$$>
Public class CCC
End class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithoutCapsAttribute_VisualBasic() As Task
Dim documentContentMarkup = <Text><![CDATA[
<Gooattribute$$>
Public class CCC
End class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooattributeAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithCapsAttribute_CSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
[GooAttribute$$]
public class CCC
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooAttribute", viewModel.TypeName)
End Function
<WorkItem(861544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861544")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithoutCapsAttribute_CSharp() As Task
Dim documentContentMarkup = <Text><![CDATA[
[Gooattribute$$]
public class CCC
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=False, isAttribute:=True)
Assert.Equal("GooattributeAttribute", viewModel.TypeName)
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_1() As Task
Dim documentContentMarkup = <Text><![CDATA[
public class C : $$D
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.BaseList)
' Check if interface, class is present
Assert.Equal(2, viewModel.KindList.Count)
Assert.Equal("class", viewModel.KindList(0))
Assert.Equal("interface", viewModel.KindList(1))
' Check if all Accessibility are present
Assert.Equal(3, viewModel.AccessList.Count)
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_CSharp_2() As Task
Dim documentContentMarkup = <Text><![CDATA[
public interface CCC : $$DDD
{
}]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.CSharp, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True)
' Check if interface, class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("interface", viewModel.KindList(0))
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("public", viewModel.AccessList(0))
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_1() As Task
Dim documentContentMarkup = <Text><![CDATA[
Public Class C
Implements $$D
End Class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=False)
' Check if only Interface is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Interface", viewModel.KindList(0))
Assert.Equal(3, viewModel.AccessList.Count)
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_2() As Task
Dim documentContentMarkup = <Text><![CDATA[
Public Class CC
Inherits $$DD
End Class]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Class, isPublicOnlyAccessibility:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Class", viewModel.KindList(0))
' Check if only Public is present
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("Public", viewModel.AccessList(0))
End Function
<WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeCheckOnlyPublic_VisualBasic_3() As Task
Dim documentContentMarkup = <Text><![CDATA[
Public Interface CCC
Inherits $$DDD
End Interface]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkup, LanguageNames.VisualBasic, typeKindvalue:=TypeKindOptions.Interface, isPublicOnlyAccessibility:=True)
' Check if only class is present
Assert.Equal(1, viewModel.KindList.Count)
Assert.Equal("Interface", viewModel.KindList(0))
' Check if only Public is present
Assert.Equal(1, viewModel.AccessList.Count)
Assert.Equal("Public", viewModel.AccessList(0))
End Function
<WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeWithModuleOption() As Task
Dim workspaceXml = <Workspace>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test1.vb">
Module Program
Sub Main(args As String())
Dim s as A.$$B.C
End Sub
End Module
Namespace A
End Namespace </Document>
</Project>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true"/>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "", typeKindvalue:=TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)
' Check if Module is present in addition to the normal options
Assert.Equal(3, viewModel.KindList.Count)
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' C# does not have Module
Assert.Equal(2, viewModel.KindList.Count)
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
viewModel.SelectedProject = projectToSelect
Assert.Equal(3, viewModel.KindList.Count)
End Function
<WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeFileExtensionUpdate() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
static void Main(string[] args)
{
Goo$$ bar;
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, "")
' Assert the current display
Assert.Equal(viewModel.FileName, "Goo.cs")
' Select the project CS2 which has no documents.
Dim projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "VB1").Single().Project
viewModel.SelectedProject = projectToSelect
' Assert the new current display
Assert.Equal(viewModel.FileName, "Goo.vb")
' Switch back to the initial document
projectToSelect = viewModel.ProjectList.Where(Function(p) p.Name = "CS1").Single().Project
viewModel.SelectedProject = projectToSelect
' Assert the display is back to the way it was before
Assert.Equal(viewModel.FileName, "Goo.cs")
' Set the name with vb extension
viewModel.FileName = "Goo.vb"
' On focus change,we trigger this method
viewModel.UpdateFileNameExtension()
' Assert that the filename changes accordingly
Assert.Equal(viewModel.FileName, "Goo.cs")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeExcludeGeneratedDocumentsFromList() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test1.cs">$$</Document>
<Document FilePath="Test2.cs"></Document>
<Document FilePath="TemporaryGeneratedFile_test.cs"></Document>
<Document FilePath="AssemblyInfo.cs"></Document>
<Document FilePath="Test3.cs"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp)
Dim expectedDocuments = {"Test1.cs", "Test2.cs", "AssemblyInfo.cs", "Test3.cs"}
Assert.Equal(expectedDocuments, viewModel.DocumentList.Select(Function(d) d.Document.Name).ToArray())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeIntoGeneratedDocument() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true">
<Document FilePath="Test.generated.cs">
class Program
{
static void Main(string[] args)
{
Goo$$ bar;
}
}
</Document>
<Document FilePath="Test2.cs"></Document>
</Project>
</Workspace>
Dim viewModel = Await GetViewModelAsync(workspaceXml, LanguageNames.CSharp)
' Test the default values
Assert.Equal(0, viewModel.AccessSelectIndex)
Assert.Equal(0, viewModel.KindSelectIndex)
Assert.Equal("Goo", viewModel.TypeName)
Assert.Equal("Goo.cs", viewModel.FileName)
Assert.Equal("Test.generated.cs", viewModel.SelectedDocument.Name)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeNewFileNameOptions() As Task
Dim workspaceXml = <Workspace>
<Project Language="C#" AssemblyName="CS1" CommonReferences="true" FilePath="C:\A\B\CS1.csproj">
<Document FilePath="C:\A\B\CDE\F\Test1.cs">
class Program
{
static void Main(string[] args)
{
Goo$$ bar;
}
}
</Document>
<Document FilePath="Test4.cs"></Document>
<Document FilePath="C:\A\B\ExistingFile.cs"></Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VB1" CommonReferences="true">
<Document FilePath="Test2.vb"></Document>
</Project>
</Workspace>
Dim projectFolder = PopulateProjectFolders(New List(Of String)(), "\outer\", "\outer\inner\")
Dim viewModel = Await GetViewModelAsync(workspaceXml, "", projectFolders:=projectFolder)
viewModel.IsNewFile = True
' Assert the current display
Assert.Equal(viewModel.FileName, "Goo.cs")
' Set the folder to \outer\
viewModel.FileName = viewModel.ProjectFolders(0)
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename to \\something.cs
viewModel.FileName = "\\ExistingFile.cs"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename to an existing file
viewModel.FileName = "..\..\ExistingFile.cs"
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename to empty
viewModel.FileName = " "
viewModel.UpdateFileNameExtension()
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename with more than permissible characters
viewModel.FileName = "sjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdfsjkygjksdfygujysdkgkufsdfrgujdfyhgjksuydfujkgysdjkfuygjkusydfjusyfkjsdfygjusydfgjkuysdkfjugyksdfjkusydfgjkusdfyjgukysdjfyjkusydfgjuysdfgjuysdfjgsdjfugjusdfygjuysdfjugyjdufgsgdfvsgdvgtsdvfgsvdfgsdgfgdsvfgsdvfgsvdfgsdf.cs"
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename with keywords
viewModel.FileName = "com1\goo.cs"
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Set the Filename with ".."
viewModel.FileName = "..\..\goo.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
' Set the Filename with ".."
viewModel.FileName = "..\.\..\.\goo.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
End Function
<WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateTypeIntoNewFileWithInvalidIdentifierFolderName() As Task
Dim documentContentMarkupCSharp = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:="C:\OuterFolder\InnerFolder\")
viewModel.IsNewFile = True
Dim foldersAreInvalid = "Folders are not valid identifiers"
viewModel.FileName = "123\456\Wow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "@@@@\######\Woow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "....a\.....b\Wow.cs"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
Dim documentContentMarkupVB = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
viewModel = Await GetViewModelAsync(documentContentMarkupVB, "Visual Basic", projectRootFilePath:="C:\OuterFolder1\InnerFolder1\")
viewModel.IsNewFile = True
viewModel.FileName = "123\456\Wow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "@@@@\######\Woow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
viewModel.FileName = "....a\.....b\Wow.vb"
viewModel.UpdateFileNameExtension()
Assert.True(viewModel.TrySubmit(), s_submit_failed_unexpectedly)
Assert.False(viewModel.AreFoldersValidIdentifiers, foldersAreInvalid)
End Function
<WorkItem(898563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898563")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)>
Public Async Function TestGenerateType_DontGenerateIntoExistingFile() As Task
' Get a Temp Folder Path
Dim projectRootFolder = Path.GetTempPath()
' Get a random filename
Dim randomFileName = Path.GetRandomFileName()
' Get the final combined path of the file
Dim pathString = Path.Combine(projectRootFolder, randomFileName)
' Create the file
Dim fs = File.Create(pathString)
Dim bytearray = New Byte() {0, 1}
fs.Write(bytearray, 0, bytearray.Length)
fs.Close()
Dim documentContentMarkupCSharp = <Text><![CDATA[
class Program
{
static void Main(string[] args)
{
A.B.Goo$$ bar;
}
}
namespace A
{
namespace B
{
}
}"]]></Text>
Dim viewModel = Await GetViewModelAsync(documentContentMarkupCSharp, "C#", projectRootFilePath:=projectRootFolder)
viewModel.IsNewFile = True
viewModel.FileName = randomFileName
Assert.False(viewModel.TrySubmit(), s_submit_passed_unexpectedly)
' Cleanup
File.Delete(pathString)
End Function
Private Function PopulateProjectFolders(list As List(Of String), ParamArray values As String()) As List(Of String)
list.AddRange(values)
Return list
End Function
Private Function GetOneProjectWorkspace(
documentContent As XElement,
languageName As String,
projectName As String,
documentName As String,
projectRootFilePath As String) As XElement
Dim documentNameWithExtension = documentName + If(languageName = "C#", ".cs", ".vb")
If projectRootFilePath Is Nothing Then
Return <Workspace>
<Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true">
<Document FilePath=<%= documentNameWithExtension %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
Else
Dim projectFilePath As String = projectRootFilePath + projectName + If(languageName = "C#", ".csproj", ".vbproj")
Dim documentFilePath As String = projectRootFilePath + documentNameWithExtension
Return <Workspace>
<Project Language=<%= languageName %> AssemblyName=<%= projectName %> CommonReferences="true" FilePath=<%= projectFilePath %>>
<Document FilePath=<%= documentFilePath %>><%= documentContent.NormalizedValue.Replace(vbCrLf, vbLf) %></Document>
</Project>
</Workspace>
End If
End Function
Private Async Function GetViewModelAsync(
content As XElement,
languageName As String,
Optional isNewFile As Boolean = False,
Optional accessSelectString As String = "",
Optional kindSelectString As String = "",
Optional projectName As String = "Assembly1",
Optional documentName As String = "Test1",
Optional typeKindvalue As TypeKindOptions = TypeKindOptions.AllOptions,
Optional isPublicOnlyAccessibility As Boolean = False,
Optional isAttribute As Boolean = False,
Optional projectFolders As List(Of String) = Nothing,
Optional projectRootFilePath As String = Nothing) As Tasks.Task(Of GenerateTypeDialogViewModel)
Dim workspaceXml = If(content.Name.LocalName = "Workspace", content, GetOneProjectWorkspace(content, languageName, projectName, documentName, projectRootFilePath))
Using workspace = TestWorkspace.Create(workspaceXml)
Dim testDoc = workspace.Documents.SingleOrDefault(Function(d) d.CursorPosition.HasValue)
Assert.NotNull(testDoc)
Dim document = workspace.CurrentSolution.GetDocument(testDoc.Id)
Dim tree = Await document.GetSyntaxTreeAsync()
Dim token = Await tree.GetTouchingWordAsync(testDoc.CursorPosition.Value, document.GetLanguageService(Of ISyntaxFactsService)(), CancellationToken.None)
Dim typeName = token.ToString()
Dim testProjectManagementService As IProjectManagementService = Nothing
If projectFolders IsNot Nothing Then
testProjectManagementService = New TestProjectManagementService(projectFolders)
End If
Dim syntaxFactsService = document.GetLanguageService(Of ISyntaxFactsService)()
Return New GenerateTypeDialogViewModel(
document,
New TestNotificationService(),
testProjectManagementService,
syntaxFactsService,
New GenerateTypeDialogOptions(isPublicOnlyAccessibility, typeKindvalue, isAttribute),
typeName,
If(document.Project.Language = LanguageNames.CSharp, ".cs", ".vb"),
isNewFile,
accessSelectString,
kindSelectString)
End Using
End Function
End Class
Friend Class TestProjectManagementService
Implements IProjectManagementService
Private ReadOnly _projectFolders As List(Of String)
Public Sub New(projectFolders As List(Of String))
Me._projectFolders = projectFolders
End Sub
Public Function GetDefaultNamespace(project As Project, workspace As Microsoft.CodeAnalysis.Workspace) As String Implements IProjectManagementService.GetDefaultNamespace
Return ""
End Function
Public Function GetFolders(projectId As ProjectId, workspace As Microsoft.CodeAnalysis.Workspace) As IList(Of String) Implements IProjectManagementService.GetFolders
Return Me._projectFolders
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// <para>
/// A utility class for making a decision dag (directed acyclic graph) for a pattern-matching construct.
/// A decision dag is represented by
/// the class <see cref="BoundDecisionDag"/> and is a representation of a finite state automaton that performs a
/// sequence of binary tests. Each node is represented by a <see cref="BoundDecisionDagNode"/>. There are four
/// kind of nodes: <see cref="BoundTestDecisionDagNode"/> performs one of the binary tests;
/// <see cref="BoundEvaluationDecisionDagNode"/> simply performs some computation and stores it in one or more
/// temporary variables for use in subsequent nodes (think of it as a node with a single successor);
/// <see cref="BoundWhenDecisionDagNode"/> represents the test performed by evaluating the expression of the
/// when-clause of a switch case; and <see cref="BoundLeafDecisionDagNode"/> represents a leaf node when we
/// have finally determined exactly which case matches. Each test processes a single input, and there are
/// four kinds:<see cref="BoundDagExplicitNullTest"/> tests a value for null; <see cref="BoundDagNonNullTest"/>
/// tests that a value is not null; <see cref="BoundDagTypeTest"/> checks if the value is of a given type;
/// and <see cref="BoundDagValueTest"/> checks if the value is equal to a given constant. Of the evaluations,
/// there are <see cref="BoundDagDeconstructEvaluation"/> which represents an invocation of a type's
/// "Deconstruct" method; <see cref="BoundDagFieldEvaluation"/> reads a field; <see cref="BoundDagPropertyEvaluation"/>
/// reads a property; and <see cref="BoundDagTypeEvaluation"/> converts a value from one type to another (which
/// is performed only after testing that the value is of that type).
/// </para>
/// <para>
/// In order to build this automaton, we start (in
/// <see cref="MakeBoundDecisionDag(SyntaxNode, ImmutableArray{DecisionDagBuilder.StateForCase})"/>
/// by computing a description of the initial state in a <see cref="DagState"/>, and then
/// for each such state description we decide what the test or evaluation will be at
/// that state, and compute the successor state descriptions.
/// A state description represented by a <see cref="DagState"/> is a collection of partially matched
/// cases represented
/// by <see cref="StateForCase"/>, in which some number of the tests have already been performed
/// for each case.
/// When we have computed <see cref="DagState"/> descriptions for all of the states, we create a new
/// <see cref="BoundDecisionDagNode"/> for each of them, containing
/// the state transitions (including the test to perform at each node and the successor nodes) but
/// not the state descriptions. A <see cref="BoundDecisionDag"/> containing this
/// set of nodes becomes part of the bound nodes (e.g. in <see cref="BoundSwitchStatement"/> and
/// <see cref="BoundUnconvertedSwitchExpression"/>) and is used for semantic analysis and lowering.
/// </para>
/// </summary>
internal sealed class DecisionDagBuilder
{
private readonly CSharpCompilation _compilation;
private readonly Conversions _conversions;
private readonly BindingDiagnosticBag _diagnostics;
private readonly LabelSymbol _defaultLabel;
private DecisionDagBuilder(CSharpCompilation compilation, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics)
{
this._compilation = compilation;
this._conversions = compilation.Conversions;
_diagnostics = diagnostics;
_defaultLabel = defaultLabel;
}
/// <summary>
/// Create a decision dag for a switch statement.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForSwitchStatement(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression switchGoverningExpression,
ImmutableArray<BoundSwitchSection> switchSections,
LabelSymbol defaultLabel,
BindingDiagnosticBag diagnostics)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics);
return builder.CreateDecisionDagForSwitchStatement(syntax, switchGoverningExpression, switchSections);
}
/// <summary>
/// Create a decision dag for a switch expression.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForSwitchExpression(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression switchExpressionInput,
ImmutableArray<BoundSwitchExpressionArm> switchArms,
LabelSymbol defaultLabel,
BindingDiagnosticBag diagnostics)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics);
return builder.CreateDecisionDagForSwitchExpression(syntax, switchExpressionInput, switchArms);
}
/// <summary>
/// Translate the pattern of an is-pattern expression.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForIsPattern(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression inputExpression,
BoundPattern pattern,
LabelSymbol whenTrueLabel,
LabelSymbol whenFalseLabel,
BindingDiagnosticBag diagnostics)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel: whenFalseLabel, diagnostics);
return builder.CreateDecisionDagForIsPattern(syntax, inputExpression, pattern, whenTrueLabel);
}
private BoundDecisionDag CreateDecisionDagForIsPattern(
SyntaxNode syntax,
BoundExpression inputExpression,
BoundPattern pattern,
LabelSymbol whenTrueLabel)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(inputExpression);
return MakeBoundDecisionDag(syntax, ImmutableArray.Create(MakeTestsForPattern(index: 1, pattern.Syntax, rootIdentifier, pattern, whenClause: null, whenTrueLabel)));
}
private BoundDecisionDag CreateDecisionDagForSwitchStatement(
SyntaxNode syntax,
BoundExpression switchGoverningExpression,
ImmutableArray<BoundSwitchSection> switchSections)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(switchGoverningExpression);
int i = 0;
var builder = ArrayBuilder<StateForCase>.GetInstance(switchSections.Length);
foreach (BoundSwitchSection section in switchSections)
{
foreach (BoundSwitchLabel label in section.SwitchLabels)
{
if (label.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel)
{
builder.Add(MakeTestsForPattern(++i, label.Syntax, rootIdentifier, label.Pattern, label.WhenClause, label.Label));
}
}
}
return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree());
}
/// <summary>
/// Used to create a decision dag for a switch expression.
/// </summary>
private BoundDecisionDag CreateDecisionDagForSwitchExpression(
SyntaxNode syntax,
BoundExpression switchExpressionInput,
ImmutableArray<BoundSwitchExpressionArm> switchArms)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(switchExpressionInput);
int i = 0;
var builder = ArrayBuilder<StateForCase>.GetInstance(switchArms.Length);
foreach (BoundSwitchExpressionArm arm in switchArms)
builder.Add(MakeTestsForPattern(++i, arm.Syntax, rootIdentifier, arm.Pattern, arm.WhenClause, arm.Label));
return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree());
}
/// <summary>
/// Compute the set of remaining tests for a pattern.
/// </summary>
private StateForCase MakeTestsForPattern(
int index,
SyntaxNode syntax,
BoundDagTemp input,
BoundPattern pattern,
BoundExpression? whenClause,
LabelSymbol label)
{
Tests tests = MakeAndSimplifyTestsAndBindings(input, pattern, out ImmutableArray<BoundPatternBinding> bindings);
return new StateForCase(index, syntax, tests, bindings, whenClause, label);
}
private Tests MakeAndSimplifyTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
out ImmutableArray<BoundPatternBinding> bindings)
{
var bindingsBuilder = ArrayBuilder<BoundPatternBinding>.GetInstance();
Tests tests = MakeTestsAndBindings(input, pattern, bindingsBuilder);
tests = SimplifyTestsAndBindings(tests, bindingsBuilder);
bindings = bindingsBuilder.ToImmutableAndFree();
return tests;
}
private static Tests SimplifyTestsAndBindings(
Tests tests,
ArrayBuilder<BoundPatternBinding> bindingsBuilder)
{
// Now simplify the tests and bindings. We don't need anything in tests that does not
// contribute to the result. This will, for example, permit us to match `(2, 3) is (2, _)` without
// fetching `Item2` from the input.
var usedValues = PooledHashSet<BoundDagEvaluation>.GetInstance();
foreach (BoundPatternBinding binding in bindingsBuilder)
{
BoundDagTemp temp = binding.TempContainingValue;
if (temp.Source is { })
{
usedValues.Add(temp.Source);
}
}
var result = scanAndSimplify(tests);
usedValues.Free();
return result;
Tests scanAndSimplify(Tests tests)
{
switch (tests)
{
case Tests.SequenceTests seq:
var testSequence = seq.RemainingTests;
var length = testSequence.Length;
var newSequence = ArrayBuilder<Tests>.GetInstance(length);
newSequence.AddRange(testSequence);
for (int i = length - 1; i >= 0; i--)
{
newSequence[i] = scanAndSimplify(newSequence[i]);
}
return seq.Update(newSequence);
case Tests.True _:
case Tests.False _:
return tests;
case Tests.One(BoundDagEvaluation e):
if (usedValues.Contains(e))
{
if (e.Input.Source is { })
usedValues.Add(e.Input.Source);
return tests;
}
else
{
return Tests.True.Instance;
}
case Tests.One(BoundDagTest d):
if (d.Input.Source is { })
usedValues.Add(d.Input.Source);
return tests;
case Tests.Not n:
return Tests.Not.Create(scanAndSimplify(n.Negated));
default:
throw ExceptionUtilities.UnexpectedValue(tests);
}
}
}
private Tests MakeTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
ArrayBuilder<BoundPatternBinding> bindings)
{
return MakeTestsAndBindings(input, pattern, out _, bindings);
}
/// <summary>
/// Make the tests and variable bindings for the given pattern with the given input. The pattern's
/// "output" value is placed in <paramref name="output"/>. The output is defined as the input
/// narrowed according to the pattern's *narrowed type*; see https://github.com/dotnet/csharplang/issues/2850.
/// </summary>
private Tests MakeTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
Debug.Assert(pattern.HasErrors || pattern.InputType.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || pattern.InputType.IsErrorType());
switch (pattern)
{
case BoundDeclarationPattern declaration:
return MakeTestsAndBindingsForDeclarationPattern(input, declaration, out output, bindings);
case BoundConstantPattern constant:
return MakeTestsForConstantPattern(input, constant, out output);
case BoundDiscardPattern _:
output = input;
return Tests.True.Instance;
case BoundRecursivePattern recursive:
return MakeTestsAndBindingsForRecursivePattern(input, recursive, out output, bindings);
case BoundITuplePattern iTuple:
return MakeTestsAndBindingsForITuplePattern(input, iTuple, out output, bindings);
case BoundTypePattern type:
return MakeTestsForTypePattern(input, type, out output);
case BoundRelationalPattern rel:
return MakeTestsAndBindingsForRelationalPattern(input, rel, out output);
case BoundNegatedPattern neg:
output = input;
return MakeTestsAndBindingsForNegatedPattern(input, neg, bindings);
case BoundBinaryPattern bin:
return MakeTestsAndBindingsForBinaryPattern(input, bin, out output, bindings);
default:
throw ExceptionUtilities.UnexpectedValue(pattern.Kind);
}
}
private Tests MakeTestsAndBindingsForITuplePattern(
BoundDagTemp input,
BoundITuplePattern pattern,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
var syntax = pattern.Syntax;
var patternLength = pattern.Subpatterns.Length;
var objectType = this._compilation.GetSpecialType(SpecialType.System_Object);
var getLengthProperty = (PropertySymbol)pattern.GetLengthMethod.AssociatedSymbol;
RoslynDebug.Assert(getLengthProperty.Type.SpecialType == SpecialType.System_Int32);
var getItemProperty = (PropertySymbol)pattern.GetItemMethod.AssociatedSymbol;
var iTupleType = getLengthProperty.ContainingType;
RoslynDebug.Assert(iTupleType.Name == "ITuple");
var tests = ArrayBuilder<Tests>.GetInstance(4 + patternLength * 2);
tests.Add(new Tests.One(new BoundDagTypeTest(syntax, iTupleType, input)));
var valueAsITupleEvaluation = new BoundDagTypeEvaluation(syntax, iTupleType, input);
tests.Add(new Tests.One(valueAsITupleEvaluation));
var valueAsITuple = new BoundDagTemp(syntax, iTupleType, valueAsITupleEvaluation);
output = valueAsITuple;
var lengthEvaluation = new BoundDagPropertyEvaluation(syntax, getLengthProperty, OriginalInput(valueAsITuple, getLengthProperty));
tests.Add(new Tests.One(lengthEvaluation));
var lengthTemp = new BoundDagTemp(syntax, this._compilation.GetSpecialType(SpecialType.System_Int32), lengthEvaluation);
tests.Add(new Tests.One(new BoundDagValueTest(syntax, ConstantValue.Create(patternLength), lengthTemp)));
var getItemPropertyInput = OriginalInput(valueAsITuple, getItemProperty);
for (int i = 0; i < patternLength; i++)
{
var indexEvaluation = new BoundDagIndexEvaluation(syntax, getItemProperty, i, getItemPropertyInput);
tests.Add(new Tests.One(indexEvaluation));
var indexTemp = new BoundDagTemp(syntax, objectType, indexEvaluation);
tests.Add(MakeTestsAndBindings(indexTemp, pattern.Subpatterns[i].Pattern, bindings));
}
return Tests.AndSequence.Create(tests);
}
/// <summary>
/// Get the earliest input of which the symbol is a member.
/// A BoundDagTypeEvaluation doesn't change the underlying object being pointed to.
/// So two evaluations act on the same input so long as they have the same original input.
/// We use this method to compute the original input for an evaluation.
/// </summary>
private BoundDagTemp OriginalInput(BoundDagTemp input, Symbol symbol)
{
while (input.Source is BoundDagTypeEvaluation source && IsDerivedType(source.Input.Type, symbol.ContainingType))
{
input = source.Input;
}
return input;
}
bool IsDerivedType(TypeSymbol possibleDerived, TypeSymbol possibleBase)
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return this._conversions.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo);
}
private Tests MakeTestsAndBindingsForDeclarationPattern(
BoundDagTemp input,
BoundDeclarationPattern declaration,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
TypeSymbol? type = declaration.DeclaredType?.Type;
var tests = ArrayBuilder<Tests>.GetInstance(1);
// Add a null and type test if needed.
if (!declaration.IsVar)
input = MakeConvertToType(input, declaration.Syntax, type!, isExplicitTest: false, tests);
BoundExpression? variableAccess = declaration.VariableAccess;
if (variableAccess is { })
{
Debug.Assert(variableAccess.Type!.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || variableAccess.Type.IsErrorType());
bindings.Add(new BoundPatternBinding(variableAccess, input));
}
else
{
RoslynDebug.Assert(declaration.Variable == null);
}
output = input;
return Tests.AndSequence.Create(tests);
}
private Tests MakeTestsForTypePattern(
BoundDagTemp input,
BoundTypePattern typePattern,
out BoundDagTemp output)
{
TypeSymbol type = typePattern.DeclaredType.Type;
var tests = ArrayBuilder<Tests>.GetInstance(4);
output = MakeConvertToType(input: input, syntax: typePattern.Syntax, type: type, isExplicitTest: typePattern.IsExplicitNotNullTest, tests: tests);
return Tests.AndSequence.Create(tests);
}
private static void MakeCheckNotNull(
BoundDagTemp input,
SyntaxNode syntax,
bool isExplicitTest,
ArrayBuilder<Tests> tests)
{
// Add a null test if needed
if (input.Type.CanContainNull())
tests.Add(new Tests.One(new BoundDagNonNullTest(syntax, isExplicitTest, input)));
}
/// <summary>
/// Generate a not-null check and a type check.
/// </summary>
private BoundDagTemp MakeConvertToType(
BoundDagTemp input,
SyntaxNode syntax,
TypeSymbol type,
bool isExplicitTest,
ArrayBuilder<Tests> tests)
{
MakeCheckNotNull(input, syntax, isExplicitTest, tests);
if (!input.Type.Equals(type, TypeCompareKind.AllIgnoreOptions))
{
TypeSymbol inputType = input.Type.StrippedType(); // since a null check has already been done
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly);
Conversion conversion = _conversions.ClassifyBuiltInConversion(inputType, type, ref useSiteInfo);
_diagnostics.Add(syntax, useSiteInfo);
if (input.Type.IsDynamic() ? type.SpecialType == SpecialType.System_Object : conversion.IsImplicit)
{
// type test not needed, only the type cast
}
else
{
// both type test and cast needed
tests.Add(new Tests.One(new BoundDagTypeTest(syntax, type, input)));
}
var evaluation = new BoundDagTypeEvaluation(syntax, type, input);
input = new BoundDagTemp(syntax, type, evaluation);
tests.Add(new Tests.One(evaluation));
}
return input;
}
private Tests MakeTestsForConstantPattern(
BoundDagTemp input,
BoundConstantPattern constant,
out BoundDagTemp output)
{
if (constant.ConstantValue == ConstantValue.Null)
{
output = input;
return new Tests.One(new BoundDagExplicitNullTest(constant.Syntax, input));
}
else
{
var tests = ArrayBuilder<Tests>.GetInstance(2);
var convertedInput = MakeConvertToType(input, constant.Syntax, constant.Value.Type!, isExplicitTest: false, tests);
output = convertedInput;
tests.Add(new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, convertedInput)));
return Tests.AndSequence.Create(tests);
}
}
private Tests MakeTestsAndBindingsForRecursivePattern(
BoundDagTemp input,
BoundRecursivePattern recursive,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
RoslynDebug.Assert(input.Type.IsErrorType() || recursive.HasErrors || recursive.InputType.IsErrorType() || input.Type.Equals(recursive.InputType, TypeCompareKind.AllIgnoreOptions));
var inputType = recursive.DeclaredType?.Type ?? input.Type.StrippedType();
var tests = ArrayBuilder<Tests>.GetInstance(5);
output = input = MakeConvertToType(input, recursive.Syntax, inputType, isExplicitTest: recursive.IsExplicitNotNullTest, tests);
if (!recursive.Deconstruction.IsDefault)
{
// we have a "deconstruction" form, which is either an invocation of a Deconstruct method, or a disassembly of a tuple
if (recursive.DeconstructMethod != null)
{
MethodSymbol method = recursive.DeconstructMethod;
var evaluation = new BoundDagDeconstructEvaluation(recursive.Syntax, method, OriginalInput(input, method));
tests.Add(new Tests.One(evaluation));
int extensionExtra = method.IsStatic ? 1 : 0;
int count = Math.Min(method.ParameterCount - extensionExtra, recursive.Deconstruction.Length);
for (int i = 0; i < count; i++)
{
BoundPattern pattern = recursive.Deconstruction[i].Pattern;
SyntaxNode syntax = pattern.Syntax;
var element = new BoundDagTemp(syntax, method.Parameters[i + extensionExtra].Type, evaluation, i);
tests.Add(MakeTestsAndBindings(element, pattern, bindings));
}
}
else if (Binder.IsZeroElementTupleType(inputType))
{
// Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType`
// do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests
// required to identify it. When that bug is fixed we should be able to remove this if statement.
// nothing to do, as there are no tests for the zero elements of this tuple
}
else if (inputType.IsTupleType)
{
ImmutableArray<FieldSymbol> elements = inputType.TupleElements;
ImmutableArray<TypeWithAnnotations> elementTypes = inputType.TupleElementTypesWithAnnotations;
int count = Math.Min(elementTypes.Length, recursive.Deconstruction.Length);
for (int i = 0; i < count; i++)
{
BoundPattern pattern = recursive.Deconstruction[i].Pattern;
SyntaxNode syntax = pattern.Syntax;
FieldSymbol field = elements[i];
var evaluation = new BoundDagFieldEvaluation(syntax, field, OriginalInput(input, field)); // fetch the ItemN field
tests.Add(new Tests.One(evaluation));
var element = new BoundDagTemp(syntax, field.Type, evaluation);
tests.Add(MakeTestsAndBindings(element, pattern, bindings));
}
}
else
{
// This occurs in error cases.
RoslynDebug.Assert(recursive.HasAnyErrors);
// To prevent this pattern from subsuming other patterns and triggering a cascaded diagnostic, we add a test that will fail.
tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true)));
}
}
if (!recursive.Properties.IsDefault)
{
// we have a "property" form
foreach (var subpattern in recursive.Properties)
{
BoundPattern pattern = subpattern.Pattern;
BoundDagTemp currentInput = input;
if (!tryMakeSubpatternMemberTests(subpattern.Member, ref currentInput))
{
Debug.Assert(recursive.HasAnyErrors);
tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true)));
}
else
{
tests.Add(MakeTestsAndBindings(currentInput, pattern, bindings));
}
}
}
if (recursive.VariableAccess != null)
{
// we have a "variable" declaration
bindings.Add(new BoundPatternBinding(recursive.VariableAccess, input));
}
return Tests.AndSequence.Create(tests);
bool tryMakeSubpatternMemberTests([NotNullWhen(true)] BoundPropertySubpatternMember? member, ref BoundDagTemp input)
{
if (member is null)
return false;
if (tryMakeSubpatternMemberTests(member.Receiver, ref input))
{
// If this is not the first member, add null test, unwrap nullables, and continue.
input = MakeConvertToType(input, member.Syntax, member.Receiver.Type.StrippedType(), isExplicitTest: false, tests);
}
BoundDagEvaluation evaluation;
switch (member.Symbol)
{
case PropertySymbol property:
evaluation = new BoundDagPropertyEvaluation(member.Syntax, property, OriginalInput(input, property));
break;
case FieldSymbol field:
evaluation = new BoundDagFieldEvaluation(member.Syntax, field, OriginalInput(input, field));
break;
default:
return false;
}
tests.Add(new Tests.One(evaluation));
input = new BoundDagTemp(member.Syntax, member.Type, evaluation);
return true;
}
}
private Tests MakeTestsAndBindingsForNegatedPattern(BoundDagTemp input, BoundNegatedPattern neg, ArrayBuilder<BoundPatternBinding> bindings)
{
var tests = MakeTestsAndBindings(input, neg.Negated, bindings);
return Tests.Not.Create(tests);
}
private Tests MakeTestsAndBindingsForBinaryPattern(
BoundDagTemp input,
BoundBinaryPattern bin,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
var builder = ArrayBuilder<Tests>.GetInstance(2);
if (bin.Disjunction)
{
builder.Add(MakeTestsAndBindings(input, bin.Left, bindings));
builder.Add(MakeTestsAndBindings(input, bin.Right, bindings));
var result = Tests.OrSequence.Create(builder);
if (bin.InputType.Equals(bin.NarrowedType))
{
output = input;
return result;
}
else
{
builder = ArrayBuilder<Tests>.GetInstance(2);
builder.Add(result);
output = MakeConvertToType(input: input, syntax: bin.Syntax, type: bin.NarrowedType, isExplicitTest: false, tests: builder);
return Tests.AndSequence.Create(builder);
}
}
else
{
builder.Add(MakeTestsAndBindings(input, bin.Left, out var leftOutput, bindings));
builder.Add(MakeTestsAndBindings(leftOutput, bin.Right, out var rightOutput, bindings));
output = rightOutput;
Debug.Assert(bin.HasErrors || output.Type.Equals(bin.NarrowedType, TypeCompareKind.AllIgnoreOptions));
return Tests.AndSequence.Create(builder);
}
}
private Tests MakeTestsAndBindingsForRelationalPattern(
BoundDagTemp input,
BoundRelationalPattern rel,
out BoundDagTemp output)
{
// check if the test is always true or always false
var tests = ArrayBuilder<Tests>.GetInstance(2);
output = MakeConvertToType(input, rel.Syntax, rel.Value.Type!, isExplicitTest: false, tests);
var fac = ValueSetFactory.ForType(input.Type);
var values = fac?.Related(rel.Relation.Operator(), rel.ConstantValue);
if (values?.IsEmpty == true)
{
tests.Add(Tests.False.Instance);
}
else if (values?.Complement().IsEmpty != true)
{
tests.Add(new Tests.One(new BoundDagRelationalTest(rel.Syntax, rel.Relation, rel.ConstantValue, output, rel.HasErrors)));
}
return Tests.AndSequence.Create(tests);
}
private TypeSymbol ErrorType(string name = "")
{
return new ExtendedErrorTypeSymbol(this._compilation, name, arity: 0, errorInfo: null, unreported: false);
}
/// <summary>
/// Compute and translate the decision dag, given a description of its initial state and a default
/// decision when no decision appears to match. This implementation is nonrecursive to avoid
/// overflowing the compiler's evaluation stack when compiling a large switch statement.
/// </summary>
private BoundDecisionDag MakeBoundDecisionDag(SyntaxNode syntax, ImmutableArray<StateForCase> cases)
{
// Build the state machine underlying the decision dag
DecisionDag decisionDag = MakeDecisionDag(cases);
// Note: It is useful for debugging the dag state table construction to set a breakpoint
// here and view `decisionDag.Dump()`.
;
// Compute the bound decision dag corresponding to each node of decisionDag, and store
// it in node.Dag.
var defaultDecision = new BoundLeafDecisionDagNode(syntax, _defaultLabel);
ComputeBoundDecisionDagNodes(decisionDag, defaultDecision);
var rootDecisionDagNode = decisionDag.RootNode.Dag;
RoslynDebug.Assert(rootDecisionDagNode != null);
var boundDecisionDag = new BoundDecisionDag(rootDecisionDagNode.Syntax, rootDecisionDagNode);
#if DEBUG
// Note that this uses the custom equality in `BoundDagEvaluation`
// to make "equivalent" evaluation nodes share the same ID.
var nextTempNumber = 0;
var tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance();
var sortedBoundDagNodes = boundDecisionDag.TopologicallySortedNodes;
for (int i = 0; i < sortedBoundDagNodes.Length; i++)
{
var node = sortedBoundDagNodes[i];
node.Id = i;
switch (node)
{
case BoundEvaluationDecisionDagNode { Evaluation: { Id: -1 } evaluation }:
evaluation.Id = tempIdentifier(evaluation);
// Note that "equivalent" evaluations may be different object instances.
// Therefore we have to dig into the Input.Source of evaluations and tests to set their IDs.
if (evaluation.Input.Source is { Id: -1 } source)
{
source.Id = tempIdentifier(source);
}
break;
case BoundTestDecisionDagNode { Test: var test }:
if (test.Input.Source is { Id: -1 } testSource)
{
testSource.Id = tempIdentifier(testSource);
}
break;
}
}
tempIdentifierMap.Free();
int tempIdentifier(BoundDagEvaluation e)
{
return tempIdentifierMap.TryGetValue(e, out int value)
? value
: tempIdentifierMap[e] = ++nextTempNumber;
}
#endif
return boundDecisionDag;
}
/// <summary>
/// Make a <see cref="DecisionDag"/> (state machine) starting with the given set of cases in the root node,
/// and return the node for the root.
/// </summary>
private DecisionDag MakeDecisionDag(ImmutableArray<StateForCase> casesForRootNode)
{
// A work list of DagStates whose successors need to be computed
var workList = ArrayBuilder<DagState>.GetInstance();
// A mapping used to make each DagState unique (i.e. to de-dup identical states).
var uniqueState = new Dictionary<DagState, DagState>(DagStateEquivalence.Instance);
// We "intern" the states, so that we only have a single object representing one
// semantic state. Because the decision automaton may contain states that have more than one
// predecessor, we want to represent each such state as a reference-unique object
// so that it is processed only once. This object identity uniqueness will be important later when we
// start mutating the DagState nodes to compute successors and BoundDecisionDagNodes
// for each one. That is why we have to use an equivalence relation in the dictionary `uniqueState`.
DagState uniqifyState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues)
{
var state = new DagState(cases, remainingValues);
if (uniqueState.TryGetValue(state, out DagState? existingState))
{
// We found an existing state that matches. Update its set of possible remaining values
// of each temp by taking the union of the sets on each incoming edge.
var newRemainingValues = ImmutableDictionary.CreateBuilder<BoundDagTemp, IValueSet>();
foreach (var (dagTemp, valuesForTemp) in remainingValues)
{
// If one incoming edge does not have a set of possible values for the temp,
// that means the temp can take on any value of its type.
if (existingState.RemainingValues.TryGetValue(dagTemp, out var existingValuesForTemp))
{
var newExistingValuesForTemp = existingValuesForTemp.Union(valuesForTemp);
newRemainingValues.Add(dagTemp, newExistingValuesForTemp);
}
}
if (existingState.RemainingValues.Count != newRemainingValues.Count ||
!existingState.RemainingValues.All(kv => newRemainingValues.TryGetValue(kv.Key, out IValueSet? values) && kv.Value.Equals(values)))
{
existingState.UpdateRemainingValues(newRemainingValues.ToImmutable());
if (!workList.Contains(existingState))
workList.Push(existingState);
}
return existingState;
}
else
{
// When we add a new unique state, we add it to a work list so that we
// will process it to compute its successors.
uniqueState.Add(state, state);
workList.Push(state);
return state;
}
}
// Simplify the initial state based on impossible or earlier matched cases
var rewrittenCases = ArrayBuilder<StateForCase>.GetInstance(casesForRootNode.Length);
foreach (var state in casesForRootNode)
{
if (state.IsImpossible)
continue;
rewrittenCases.Add(state);
if (state.IsFullyMatched)
break;
}
var initialState = uniqifyState(rewrittenCases.ToImmutableAndFree(), ImmutableDictionary<BoundDagTemp, IValueSet>.Empty);
// Go through the worklist of DagState nodes for which we have not yet computed
// successor states.
while (workList.Count != 0)
{
DagState state = workList.Pop();
RoslynDebug.Assert(state.SelectedTest == null);
RoslynDebug.Assert(state.TrueBranch == null);
RoslynDebug.Assert(state.FalseBranch == null);
if (state.Cases.IsDefaultOrEmpty)
{
// If this state has no more cases that could possibly match, then
// we know there is no case that will match and this node represents a "default"
// decision. We do not need to compute a successor, as it is a leaf node
continue;
}
StateForCase first = state.Cases[0];
Debug.Assert(!first.IsImpossible);
if (first.PatternIsSatisfied)
{
if (first.IsFullyMatched)
{
// The first of the remaining cases has fully matched, as there are no more tests to do.
// The language semantics of the switch statement and switch expression require that we
// execute the first matching case. There is no when clause to evaluate here,
// so this is a leaf node and required no further processing.
}
else
{
// There is a when clause to evaluate.
// In case the when clause fails, we prepare for the remaining cases.
var stateWhenFails = state.Cases.RemoveAt(0);
state.FalseBranch = uniqifyState(stateWhenFails, state.RemainingValues);
}
}
else
{
// Select the next test to do at this state, and compute successor states
switch (state.SelectedTest = state.ComputeSelectedTest())
{
case BoundDagEvaluation e:
state.TrueBranch = uniqifyState(RemoveEvaluation(state.Cases, e), state.RemainingValues);
// An evaluation is considered to always succeed, so there is no false branch
break;
case BoundDagTest d:
bool foundExplicitNullTest = false;
SplitCases(
state.Cases, state.RemainingValues, d,
out ImmutableArray<StateForCase> whenTrueDecisions,
out ImmutableArray<StateForCase> whenFalseDecisions,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
ref foundExplicitNullTest);
state.TrueBranch = uniqifyState(whenTrueDecisions, whenTrueValues);
state.FalseBranch = uniqifyState(whenFalseDecisions, whenFalseValues);
if (foundExplicitNullTest && d is BoundDagNonNullTest { IsExplicitTest: false } t)
{
// Turn an "implicit" non-null test into an explicit one
state.SelectedTest = new BoundDagNonNullTest(t.Syntax, isExplicitTest: true, t.Input, t.HasErrors);
}
break;
case var n:
throw ExceptionUtilities.UnexpectedValue(n.Kind);
}
}
}
workList.Free();
return new DecisionDag(initialState);
}
/// <summary>
/// Compute the <see cref="BoundDecisionDag"/> corresponding to each <see cref="DagState"/> of the given <see cref="DecisionDag"/>
/// and store it in <see cref="DagState.Dag"/>.
/// </summary>
private void ComputeBoundDecisionDagNodes(DecisionDag decisionDag, BoundLeafDecisionDagNode defaultDecision)
{
Debug.Assert(_defaultLabel != null);
Debug.Assert(defaultDecision != null);
// Process the states in topological order, leaves first, and assign a BoundDecisionDag to each DagState.
bool wasAcyclic = decisionDag.TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> sortedStates);
if (!wasAcyclic)
{
// Since we intend the set of DagState nodes to be acyclic by construction, we do not expect
// this to occur. Just in case it does due to bugs, we recover gracefully to avoid crashing the
// compiler in production. If you find that this happens (the assert fails), please modify the
// DagState construction process to avoid creating a cyclic state graph.
Debug.Assert(wasAcyclic); // force failure in debug builds
// If the dag contains a cycle, return a short-circuit dag instead.
decisionDag.RootNode.Dag = defaultDecision;
return;
}
// We "intern" the dag nodes, so that we only have a single object representing one
// semantic node. We do this because different states may end up mapping to the same
// set of successor states. In this case we merge them when producing the bound state machine.
var uniqueNodes = PooledDictionary<BoundDecisionDagNode, BoundDecisionDagNode>.GetInstance();
BoundDecisionDagNode uniqifyDagNode(BoundDecisionDagNode node) => uniqueNodes.GetOrAdd(node, node);
_ = uniqifyDagNode(defaultDecision);
for (int i = sortedStates.Length - 1; i >= 0; i--)
{
var state = sortedStates[i];
if (state.Cases.IsDefaultOrEmpty)
{
state.Dag = defaultDecision;
continue;
}
StateForCase first = state.Cases[0];
RoslynDebug.Assert(!(first.RemainingTests is Tests.False));
if (first.PatternIsSatisfied)
{
if (first.IsFullyMatched)
{
// there is no when clause we need to evaluate
state.Dag = finalState(first.Syntax, first.CaseLabel, first.Bindings);
}
else
{
RoslynDebug.Assert(state.TrueBranch == null);
RoslynDebug.Assert(state.FalseBranch is { });
// The final state here does not need bindings, as they will be performed before evaluating the when clause (see below)
BoundDecisionDagNode whenTrue = finalState(first.Syntax, first.CaseLabel, default);
BoundDecisionDagNode? whenFalse = state.FalseBranch.Dag;
RoslynDebug.Assert(whenFalse is { });
state.Dag = uniqifyDagNode(new BoundWhenDecisionDagNode(first.Syntax, first.Bindings, first.WhenClause, whenTrue, whenFalse));
}
BoundDecisionDagNode finalState(SyntaxNode syntax, LabelSymbol label, ImmutableArray<BoundPatternBinding> bindings)
{
BoundDecisionDagNode final = uniqifyDagNode(new BoundLeafDecisionDagNode(syntax, label));
return bindings.IsDefaultOrEmpty ? final : uniqifyDagNode(new BoundWhenDecisionDagNode(syntax, bindings, null, final, null));
}
}
else
{
switch (state.SelectedTest)
{
case BoundDagEvaluation e:
{
BoundDecisionDagNode? next = state.TrueBranch!.Dag;
RoslynDebug.Assert(next is { });
RoslynDebug.Assert(state.FalseBranch == null);
state.Dag = uniqifyDagNode(new BoundEvaluationDecisionDagNode(e.Syntax, e, next));
}
break;
case BoundDagTest d:
{
BoundDecisionDagNode? whenTrue = state.TrueBranch!.Dag;
BoundDecisionDagNode? whenFalse = state.FalseBranch!.Dag;
RoslynDebug.Assert(whenTrue is { });
RoslynDebug.Assert(whenFalse is { });
state.Dag = uniqifyDagNode(new BoundTestDecisionDagNode(d.Syntax, d, whenTrue, whenFalse));
}
break;
case var n:
throw ExceptionUtilities.UnexpectedValue(n?.Kind);
}
}
}
uniqueNodes.Free();
}
private void SplitCase(
StateForCase stateForCase,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out StateForCase whenTrue,
out StateForCase whenFalse,
ref bool foundExplicitNullTest)
{
stateForCase.RemainingTests.Filter(this, test, whenTrueValues, whenFalseValues, out Tests whenTrueTests, out Tests whenFalseTests, ref foundExplicitNullTest);
whenTrue = makeNext(whenTrueTests);
whenFalse = makeNext(whenFalseTests);
return;
StateForCase makeNext(Tests remainingTests)
{
return remainingTests.Equals(stateForCase.RemainingTests)
? stateForCase
: new StateForCase(
stateForCase.Index, stateForCase.Syntax, remainingTests,
stateForCase.Bindings, stateForCase.WhenClause, stateForCase.CaseLabel);
}
}
private void SplitCases(
ImmutableArray<StateForCase> statesForCases,
ImmutableDictionary<BoundDagTemp, IValueSet> values,
BoundDagTest test,
out ImmutableArray<StateForCase> whenTrue,
out ImmutableArray<StateForCase> whenFalse,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
ref bool foundExplicitNullTest)
{
var whenTrueBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length);
var whenFalseBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length);
bool whenTruePossible, whenFalsePossible;
(whenTrueValues, whenFalseValues, whenTruePossible, whenFalsePossible) = SplitValues(values, test);
// whenTruePossible means the test could possibly have succeeded. whenFalsePossible means it could possibly have failed.
// Tests that are either impossible or tautological (i.e. either of these false) given
// the set of values are normally removed and replaced by the known result, so we would not normally be processing
// a test that always succeeds or always fails, but they can occur in erroneous programs (e.g. testing for equality
// against a non-constant value).
foreach (var state in statesForCases)
{
SplitCase(
state, test,
whenTrueValues.TryGetValue(test.Input, out var v1) ? v1 : null,
whenFalseValues.TryGetValue(test.Input, out var v2) ? v2 : null,
out var whenTrueState, out var whenFalseState, ref foundExplicitNullTest);
// whenTrueState.IsImpossible occurs when Split results in a state for a given case where the case has been ruled
// out (because its test has failed). If not whenTruePossible, we don't want to add anything to the state. In
// either case, we do not want to add the current case to the state.
if (whenTruePossible && !whenTrueState.IsImpossible && !(whenTrueBuilder.Any() && whenTrueBuilder.Last().IsFullyMatched))
whenTrueBuilder.Add(whenTrueState);
// Similarly for the alternative state.
if (whenFalsePossible && !whenFalseState.IsImpossible && !(whenFalseBuilder.Any() && whenFalseBuilder.Last().IsFullyMatched))
whenFalseBuilder.Add(whenFalseState);
}
whenTrue = whenTrueBuilder.ToImmutableAndFree();
whenFalse = whenFalseBuilder.ToImmutableAndFree();
}
private static (
ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
bool truePossible,
bool falsePossible)
SplitValues(
ImmutableDictionary<BoundDagTemp, IValueSet> values,
BoundDagTest test)
{
switch (test)
{
case BoundDagEvaluation _:
case BoundDagExplicitNullTest _:
case BoundDagNonNullTest _:
case BoundDagTypeTest _:
return (values, values, true, true);
case BoundDagValueTest t:
return resultForRelation(BinaryOperatorKind.Equal, t.Value);
case BoundDagRelationalTest t:
return resultForRelation(t.Relation, t.Value);
default:
throw ExceptionUtilities.UnexpectedValue(test);
}
(
ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
bool truePossible,
bool falsePossible)
resultForRelation(BinaryOperatorKind relation, ConstantValue value)
{
var input = test.Input;
IValueSetFactory? valueFac = ValueSetFactory.ForType(input.Type);
if (valueFac == null || value.IsBad)
{
// If it is a type we don't track yet, assume all values are possible
return (values, values, true, true);
}
IValueSet fromTestPassing = valueFac.Related(relation.Operator(), value);
IValueSet fromTestFailing = fromTestPassing.Complement();
if (values.TryGetValue(test.Input, out IValueSet? tempValuesBeforeTest))
{
fromTestPassing = fromTestPassing.Intersect(tempValuesBeforeTest);
fromTestFailing = fromTestFailing.Intersect(tempValuesBeforeTest);
}
var whenTrueValues = values.SetItem(input, fromTestPassing);
var whenFalseValues = values.SetItem(input, fromTestFailing);
return (whenTrueValues, whenFalseValues, !fromTestPassing.IsEmpty, !fromTestFailing.IsEmpty);
}
}
private static ImmutableArray<StateForCase> RemoveEvaluation(ImmutableArray<StateForCase> cases, BoundDagEvaluation e)
{
var builder = ArrayBuilder<StateForCase>.GetInstance(cases.Length);
foreach (var stateForCase in cases)
{
var remainingTests = stateForCase.RemainingTests.RemoveEvaluation(e);
if (remainingTests is Tests.False)
{
// This can occur in error cases like `e is not int x` where there is a trailing evaluation
// in a failure branch.
}
else
{
builder.Add(new StateForCase(
Index: stateForCase.Index, Syntax: stateForCase.Syntax,
RemainingTests: remainingTests,
Bindings: stateForCase.Bindings, WhenClause: stateForCase.WhenClause, CaseLabel: stateForCase.CaseLabel));
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Given that the test <paramref name="test"/> has occurred and produced a true/false result,
/// set some flags indicating the implied status of the <paramref name="other"/> test.
/// </summary>
/// <param name="test"></param>
/// <param name="other"></param>
/// <param name="whenTrueValues">The possible values of test.Input when <paramref name="test"/> has succeeded.</param>
/// <param name="whenFalseValues">The possible values of test.Input when <paramref name="test"/> has failed.</param>
/// <param name="trueTestPermitsTrueOther">set if <paramref name="test"/> being true would permit <paramref name="other"/> to succeed</param>
/// <param name="falseTestPermitsTrueOther">set if a false result on <paramref name="test"/> would permit <paramref name="other"/> to succeed</param>
/// <param name="trueTestImpliesTrueOther">set if <paramref name="test"/> being true means <paramref name="other"/> has been proven true</param>
/// <param name="falseTestImpliesTrueOther">set if <paramref name="test"/> being false means <paramref name="other"/> has been proven true</param>
private void CheckConsistentDecision(
BoundDagTest test,
BoundDagTest other,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
SyntaxNode syntax,
out bool trueTestPermitsTrueOther,
out bool falseTestPermitsTrueOther,
out bool trueTestImpliesTrueOther,
out bool falseTestImpliesTrueOther,
ref bool foundExplicitNullTest)
{
// innocent until proven guilty
trueTestPermitsTrueOther = true;
falseTestPermitsTrueOther = true;
trueTestImpliesTrueOther = false;
falseTestImpliesTrueOther = false;
// if the tests are for unrelated things, there is no implication from one to the other
if (!test.Input.Equals(other.Input))
return;
switch (test)
{
case BoundDagNonNullTest _:
switch (other)
{
case BoundDagValueTest _:
// !(v != null) --> !(v == K)
falseTestPermitsTrueOther = false;
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v != null --> !(v == null)
trueTestPermitsTrueOther = false;
// !(v != null) --> v == null
falseTestImpliesTrueOther = true;
break;
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v != null --> v != null
trueTestImpliesTrueOther = true;
// !(v != null) --> !(v != null)
falseTestPermitsTrueOther = false;
break;
default:
// !(v != null) --> !(v is T)
falseTestPermitsTrueOther = false;
break;
}
break;
case BoundDagTypeTest t1:
switch (other)
{
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v is T --> v != null
trueTestImpliesTrueOther = true;
break;
case BoundDagTypeTest t2:
{
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly);
bool? matches = ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(t1.Type, t2.Type, ref useSiteInfo);
if (matches == false)
{
// If T1 could never be T2
// v is T1 --> !(v is T2)
trueTestPermitsTrueOther = false;
}
else if (matches == true)
{
// If T1: T2
// v is T1 --> v is T2
trueTestImpliesTrueOther = true;
}
// If every T2 is a T1, then failure of T1 implies failure of T2.
matches = Binder.ExpressionOfTypeMatchesPatternType(_conversions, t2.Type, t1.Type, ref useSiteInfo, out _);
_diagnostics.Add(syntax, useSiteInfo);
if (matches == true)
{
// If T2: T1
// !(v is T1) --> !(v is T2)
falseTestPermitsTrueOther = false;
}
}
break;
case BoundDagValueTest _:
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v is T --> !(v == null)
trueTestPermitsTrueOther = false;
break;
}
break;
case BoundDagValueTest _:
case BoundDagRelationalTest _:
switch (other)
{
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v == K --> v != null
trueTestImpliesTrueOther = true;
break;
case BoundDagTypeTest _:
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v == K --> !(v == null)
trueTestPermitsTrueOther = false;
break;
case BoundDagRelationalTest r2:
handleRelationWithValue(r2.Relation, r2.Value,
out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther);
break;
case BoundDagValueTest v2:
handleRelationWithValue(BinaryOperatorKind.Equal, v2.Value,
out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther);
break;
void handleRelationWithValue(
BinaryOperatorKind relation,
ConstantValue value,
out bool trueTestPermitsTrueOther,
out bool falseTestPermitsTrueOther,
out bool trueTestImpliesTrueOther,
out bool falseTestImpliesTrueOther)
{
// We check test.Equals(other) to handle "bad" constant values
bool sameTest = test.Equals(other);
trueTestPermitsTrueOther = whenTrueValues?.Any(relation, value) ?? true;
trueTestImpliesTrueOther = sameTest || trueTestPermitsTrueOther && (whenTrueValues?.All(relation, value) ?? false);
falseTestPermitsTrueOther = !sameTest && (whenFalseValues?.Any(relation, value) ?? true);
falseTestImpliesTrueOther = falseTestPermitsTrueOther && (whenFalseValues?.All(relation, value) ?? false);
}
}
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
switch (other)
{
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v == null --> !(v != null)
trueTestPermitsTrueOther = false;
// !(v == null) --> v != null
falseTestImpliesTrueOther = true;
break;
case BoundDagTypeTest _:
// v == null --> !(v is T)
trueTestPermitsTrueOther = false;
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v == null --> v == null
trueTestImpliesTrueOther = true;
// !(v == null) --> !(v == null)
falseTestPermitsTrueOther = false;
break;
case BoundDagValueTest _:
// v == null --> !(v == K)
trueTestPermitsTrueOther = false;
break;
}
break;
}
}
/// <summary>
/// Determine what we can learn from one successful runtime type test about another planned
/// runtime type test for the purpose of building the decision tree.
/// We accommodate a special behavior of the runtime here, which does not match the language rules.
/// A value of type `int[]` is an "instanceof" (i.e. result of the `isinst` instruction) the type
/// `uint[]` and vice versa. It is similarly so for every pair of same-sized numeric types, and
/// arrays of enums are considered to be their underlying type. We need the dag construction to
/// recognize this runtime behavior, so we pretend that matching one of them gives no information
/// on whether the other will be matched. That isn't quite correct (nothing reasonable we do
/// could be), but it comes closest to preserving the existing C#7 behavior without undesirable
/// side-effects, and permits the code-gen strategy to preserve the dynamic semantic equivalence
/// of a switch (on the one hand) and a series of if-then-else statements (on the other).
/// See, for example, https://github.com/dotnet/roslyn/issues/35661
/// </summary>
private bool? ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(
TypeSymbol expressionType,
TypeSymbol patternType,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
bool? result = Binder.ExpressionOfTypeMatchesPatternType(_conversions, expressionType, patternType, ref useSiteInfo, out Conversion conversion);
return (!conversion.Exists && isRuntimeSimilar(expressionType, patternType))
? null // runtime and compile-time test behavior differ. Pretend we don't know what happens.
: result;
static bool isRuntimeSimilar(TypeSymbol expressionType, TypeSymbol patternType)
{
while (expressionType is ArrayTypeSymbol { ElementType: var e1, IsSZArray: var sz1, Rank: var r1 } &&
patternType is ArrayTypeSymbol { ElementType: var e2, IsSZArray: var sz2, Rank: var r2 } &&
sz1 == sz2 && r1 == r2)
{
e1 = e1.EnumUnderlyingTypeOrSelf();
e2 = e2.EnumUnderlyingTypeOrSelf();
switch (e1.SpecialType, e2.SpecialType)
{
// The following support CLR behavior that is required by
// the CLI specification but violates the C# language behavior.
// See ECMA-335's definition of *array-element-compatible-with*.
case var (s1, s2) when s1 == s2:
case (SpecialType.System_SByte, SpecialType.System_Byte):
case (SpecialType.System_Byte, SpecialType.System_SByte):
case (SpecialType.System_Int16, SpecialType.System_UInt16):
case (SpecialType.System_UInt16, SpecialType.System_Int16):
case (SpecialType.System_Int32, SpecialType.System_UInt32):
case (SpecialType.System_UInt32, SpecialType.System_Int32):
case (SpecialType.System_Int64, SpecialType.System_UInt64):
case (SpecialType.System_UInt64, SpecialType.System_Int64):
case (SpecialType.System_IntPtr, SpecialType.System_UIntPtr):
case (SpecialType.System_UIntPtr, SpecialType.System_IntPtr):
// The following support behavior of the CLR that violates the CLI
// and C# specifications, but we implement them because that is the
// behavior on 32-bit runtimes.
case (SpecialType.System_Int32, SpecialType.System_IntPtr):
case (SpecialType.System_Int32, SpecialType.System_UIntPtr):
case (SpecialType.System_UInt32, SpecialType.System_IntPtr):
case (SpecialType.System_UInt32, SpecialType.System_UIntPtr):
case (SpecialType.System_IntPtr, SpecialType.System_Int32):
case (SpecialType.System_IntPtr, SpecialType.System_UInt32):
case (SpecialType.System_UIntPtr, SpecialType.System_Int32):
case (SpecialType.System_UIntPtr, SpecialType.System_UInt32):
// The following support behavior of the CLR that violates the CLI
// and C# specifications, but we implement them because that is the
// behavior on 64-bit runtimes.
case (SpecialType.System_Int64, SpecialType.System_IntPtr):
case (SpecialType.System_Int64, SpecialType.System_UIntPtr):
case (SpecialType.System_UInt64, SpecialType.System_IntPtr):
case (SpecialType.System_UInt64, SpecialType.System_UIntPtr):
case (SpecialType.System_IntPtr, SpecialType.System_Int64):
case (SpecialType.System_IntPtr, SpecialType.System_UInt64):
case (SpecialType.System_UIntPtr, SpecialType.System_Int64):
case (SpecialType.System_UIntPtr, SpecialType.System_UInt64):
return true;
default:
(expressionType, patternType) = (e1, e2);
break;
}
}
return false;
}
}
/// <summary>
/// A representation of the entire decision dag and each of its states.
/// </summary>
private sealed class DecisionDag
{
/// <summary>
/// The starting point for deciding which case matches.
/// </summary>
public readonly DagState RootNode;
public DecisionDag(DagState rootNode)
{
this.RootNode = rootNode;
}
/// <summary>
/// A successor function used to topologically sort the DagState set.
/// </summary>
private static ImmutableArray<DagState> Successor(DagState state)
{
if (state.TrueBranch != null && state.FalseBranch != null)
{
return ImmutableArray.Create(state.FalseBranch, state.TrueBranch);
}
else if (state.TrueBranch != null)
{
return ImmutableArray.Create(state.TrueBranch);
}
else if (state.FalseBranch != null)
{
return ImmutableArray.Create(state.FalseBranch);
}
else
{
return ImmutableArray<DagState>.Empty;
}
}
/// <summary>
/// Produce the states in topological order.
/// </summary>
/// <param name="result">Topologically sorted <see cref="DagState"/> nodes.</param>
/// <returns>True if the graph was acyclic.</returns>
public bool TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> result)
{
return TopologicalSort.TryIterativeSort<DagState>(SpecializedCollections.SingletonEnumerable<DagState>(this.RootNode), Successor, out result);
}
#if DEBUG
/// <summary>
/// Starting with `this` state, produce a human-readable description of the state tables.
/// This is very useful for debugging and optimizing the dag state construction.
/// </summary>
internal string Dump()
{
if (!this.TryGetTopologicallySortedReachableStates(out var allStates))
{
return "(the dag contains a cycle!)";
}
var stateIdentifierMap = PooledDictionary<DagState, int>.GetInstance();
for (int i = 0; i < allStates.Length; i++)
{
stateIdentifierMap.Add(allStates[i], i);
}
// NOTE that this numbering for temps does not work well for the invocation of Deconstruct, which produces
// multiple values. This would make them appear to be the same temp in the debug dump.
int nextTempNumber = 0;
PooledDictionary<BoundDagEvaluation, int> tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance();
int tempIdentifier(BoundDagEvaluation? e)
{
return (e == null) ? 0 : tempIdentifierMap.TryGetValue(e, out int value) ? value : tempIdentifierMap[e] = ++nextTempNumber;
}
string tempName(BoundDagTemp t)
{
return $"t{tempIdentifier(t.Source)}";
}
var resultBuilder = PooledStringBuilder.GetInstance();
var result = resultBuilder.Builder;
foreach (DagState state in allStates)
{
bool isFail = state.Cases.IsEmpty;
bool starred = isFail || state.Cases.First().PatternIsSatisfied;
result.Append($"{(starred ? "*" : "")}State " + stateIdentifierMap[state] + (isFail ? " FAIL" : ""));
var remainingValues = state.RemainingValues.Select(kvp => $"{tempName(kvp.Key)}:{kvp.Value}");
result.AppendLine($"{(remainingValues.Any() ? " REMAINING " + string.Join(" ", remainingValues) : "")}");
foreach (StateForCase cd in state.Cases)
{
result.AppendLine($" {dumpStateForCase(cd)}");
}
if (state.SelectedTest != null)
{
result.AppendLine($" Test: {dumpDagTest(state.SelectedTest)}");
}
if (state.TrueBranch != null)
{
result.AppendLine($" TrueBranch: {stateIdentifierMap[state.TrueBranch]}");
}
if (state.FalseBranch != null)
{
result.AppendLine($" FalseBranch: {stateIdentifierMap[state.FalseBranch]}");
}
}
stateIdentifierMap.Free();
tempIdentifierMap.Free();
return resultBuilder.ToStringAndFree();
string dumpStateForCase(StateForCase cd)
{
var instance = PooledStringBuilder.GetInstance();
StringBuilder builder = instance.Builder;
builder.Append($"{cd.Index}. [{cd.Syntax}] {(cd.PatternIsSatisfied ? "MATCH" : cd.RemainingTests.Dump(dumpDagTest))}");
var bindings = cd.Bindings.Select(bpb => $"{(bpb.VariableAccess is BoundLocal l ? l.LocalSymbol.Name : "<var>")}={tempName(bpb.TempContainingValue)}");
if (bindings.Any())
{
builder.Append(" BIND[");
builder.Append(string.Join("; ", bindings));
builder.Append("]");
}
if (cd.WhenClause is { })
{
builder.Append($" WHEN[{cd.WhenClause.Syntax}]");
}
return instance.ToStringAndFree();
}
string dumpDagTest(BoundDagTest d)
{
switch (d)
{
case BoundDagTypeEvaluation a:
return $"t{tempIdentifier(a)}={a.Kind}({tempName(a.Input)} as {a.Type})";
case BoundDagFieldEvaluation e:
return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Field.Name})";
case BoundDagPropertyEvaluation e:
return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Property.Name})";
case BoundDagEvaluation e:
return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)})";
case BoundDagTypeTest b:
return $"?{d.Kind}({tempName(d.Input)} is {b.Type})";
case BoundDagValueTest v:
return $"?{d.Kind}({tempName(d.Input)} == {v.Value})";
case BoundDagRelationalTest r:
var operatorName = r.Relation.Operator() switch
{
BinaryOperatorKind.LessThan => "<",
BinaryOperatorKind.LessThanOrEqual => "<=",
BinaryOperatorKind.GreaterThan => ">",
BinaryOperatorKind.GreaterThanOrEqual => ">=",
_ => "??"
};
return $"?{d.Kind}({tempName(d.Input)} {operatorName} {r.Value})";
default:
return $"?{d.Kind}({tempName(d.Input)})";
}
}
}
#endif
}
/// <summary>
/// The state at a given node of the decision finite state automaton. This is used during computation of the state
/// machine (<see cref="BoundDecisionDag"/>), and contains a representation of the meaning of the state. Because we always make
/// forward progress when a test is evaluated (the state description is monotonically smaller at each edge), the
/// graph of states is acyclic, which is why we call it a dag (directed acyclic graph).
/// </summary>
private sealed class DagState
{
/// <summary>
/// For each dag temp of a type for which we track such things (the integral types, floating-point types, and bool),
/// the possible values it can take on when control reaches this state.
/// If this dictionary is mutated after <see cref="TrueBranch"/>, <see cref="FalseBranch"/>,
/// and <see cref="Dag"/> are computed (for example to merge states), they must be cleared and recomputed,
/// as the set of possible values can affect successor states.
/// A <see cref="BoundDagTemp"/> absent from this dictionary means that all values of the type are possible.
/// </summary>
public ImmutableDictionary<BoundDagTemp, IValueSet> RemainingValues { get; private set; }
/// <summary>
/// The set of cases that may still match, and for each of them the set of tests that remain to be tested.
/// </summary>
public readonly ImmutableArray<StateForCase> Cases;
public DagState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues)
{
this.Cases = cases;
this.RemainingValues = remainingValues;
}
// If not a leaf node or a when clause, the test that will be taken at this node of the
// decision automaton.
public BoundDagTest? SelectedTest;
// We only compute the dag states for the branches after we de-dup this DagState itself.
// If all that remains is the `when` clauses, SelectedDecision is left `null` (we can
// build the leaf node easily during translation) and the FalseBranch field is populated
// with the successor on failure of the when clause (if one exists).
public DagState? TrueBranch, FalseBranch;
// After the entire graph of DagState objects is complete, we translate each into its Dag node.
public BoundDecisionDagNode? Dag;
/// <summary>
/// Decide on what test to use at this node of the decision dag. This is the principal
/// heuristic we can change to adjust the quality of the generated decision automaton.
/// See https://www.cs.tufts.edu/~nr/cs257/archive/norman-ramsey/match.pdf for some ideas.
/// </summary>
internal BoundDagTest ComputeSelectedTest()
{
return Cases[0].RemainingTests.ComputeSelectedTest();
}
internal void UpdateRemainingValues(ImmutableDictionary<BoundDagTemp, IValueSet> newRemainingValues)
{
this.RemainingValues = newRemainingValues;
this.SelectedTest = null;
this.TrueBranch = null;
this.FalseBranch = null;
}
}
/// <summary>
/// An equivalence relation between dag states used to dedup the states during dag construction.
/// After dag construction is complete we treat a DagState as using object equality as equivalent
/// states have been merged.
/// </summary>
private sealed class DagStateEquivalence : IEqualityComparer<DagState>
{
public static readonly DagStateEquivalence Instance = new DagStateEquivalence();
private DagStateEquivalence() { }
public bool Equals(DagState? x, DagState? y)
{
RoslynDebug.Assert(x is { });
RoslynDebug.Assert(y is { });
return x == y || x.Cases.SequenceEqual(y.Cases, (a, b) => a.Equals(b));
}
public int GetHashCode(DagState x)
{
return Hash.Combine(Hash.CombineValues(x.Cases), x.Cases.Length);
}
}
/// <summary>
/// As part of the description of a node of the decision automaton, we keep track of what tests
/// remain to be done for each case.
/// </summary>
private sealed class StateForCase
{
/// <summary>
/// A number that is distinct for each case and monotonically increasing from earlier to later cases.
/// Since we always keep the cases in order, this is only used to assist with debugging (e.g.
/// see DecisionDag.Dump()).
/// </summary>
public readonly int Index;
public readonly SyntaxNode Syntax;
public readonly Tests RemainingTests;
public readonly ImmutableArray<BoundPatternBinding> Bindings;
public readonly BoundExpression? WhenClause;
public readonly LabelSymbol CaseLabel;
public StateForCase(
int Index,
SyntaxNode Syntax,
Tests RemainingTests,
ImmutableArray<BoundPatternBinding> Bindings,
BoundExpression? WhenClause,
LabelSymbol CaseLabel)
{
this.Index = Index;
this.Syntax = Syntax;
this.RemainingTests = RemainingTests;
this.Bindings = Bindings;
this.WhenClause = WhenClause;
this.CaseLabel = CaseLabel;
}
/// <summary>
/// Is the pattern in a state in which it is fully matched and there is no when clause?
/// </summary>
public bool IsFullyMatched => RemainingTests is Tests.True && (WhenClause is null || WhenClause.ConstantValue == ConstantValue.True);
/// <summary>
/// Is the pattern fully matched and ready for the when clause to be evaluated (if any)?
/// </summary>
public bool PatternIsSatisfied => RemainingTests is Tests.True;
/// <summary>
/// Is the clause impossible? We do not consider a when clause with a constant false value to cause the branch to be impossible.
/// Note that we do not include the possibility that a when clause is the constant false. That is treated like any other expression.
/// </summary>
public bool IsImpossible => RemainingTests is Tests.False;
public override bool Equals(object? obj)
{
throw ExceptionUtilities.Unreachable;
}
public bool Equals(StateForCase other)
{
// We do not include Syntax, Bindings, WhereClause, or CaseLabel
// because once the Index is the same, those must be the same too.
return this == other ||
other != null &&
this.Index == other.Index &&
this.RemainingTests.Equals(other.RemainingTests);
}
public override int GetHashCode()
{
return Hash.Combine(RemainingTests.GetHashCode(), Index);
}
}
/// <summary>
/// A set of tests to be performed. This is a discriminated union; see the options (nested types) for more details.
/// </summary>
private abstract class Tests
{
private Tests() { }
/// <summary>
/// Take the set of tests and split them into two, one for when the test has succeeded, and one for when the test has failed.
/// </summary>
public abstract void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest);
public virtual BoundDagTest ComputeSelectedTest() => throw ExceptionUtilities.Unreachable;
public virtual Tests RemoveEvaluation(BoundDagEvaluation e) => this;
public abstract string Dump(Func<BoundDagTest, string> dump);
/// <summary>
/// No tests to be performed; the result is true (success).
/// </summary>
public sealed class True : Tests
{
public static readonly True Instance = new True();
public override string Dump(Func<BoundDagTest, string> dump) => "TRUE";
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
whenTrue = whenFalse = this;
}
}
/// <summary>
/// No tests to be performed; the result is false (failure).
/// </summary>
public sealed class False : Tests
{
public static readonly False Instance = new False();
public override string Dump(Func<BoundDagTest, string> dump) => "FALSE";
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
whenTrue = whenFalse = this;
}
}
/// <summary>
/// A single test to be performed, described by a <see cref="BoundDagTest"/>.
/// Note that the test might be a <see cref="BoundDagEvaluation"/>, in which case it is deemed to have
/// succeeded after being evaluated.
/// </summary>
public sealed class One : Tests
{
public readonly BoundDagTest Test;
public One(BoundDagTest test) => this.Test = test;
public void Deconstruct(out BoundDagTest Test) => Test = this.Test;
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
builder.CheckConsistentDecision(
test: test,
other: Test,
whenTrueValues: whenTrueValues,
whenFalseValues: whenFalseValues,
syntax: test.Syntax,
trueTestPermitsTrueOther: out bool trueDecisionPermitsTrueOther,
falseTestPermitsTrueOther: out bool falseDecisionPermitsTrueOther,
trueTestImpliesTrueOther: out bool trueDecisionImpliesTrueOther,
falseTestImpliesTrueOther: out bool falseDecisionImpliesTrueOther,
foundExplicitNullTest: ref foundExplicitNullTest);
whenTrue = trueDecisionImpliesTrueOther ? Tests.True.Instance : trueDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance;
whenFalse = falseDecisionImpliesTrueOther ? Tests.True.Instance : falseDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance;
}
public override BoundDagTest ComputeSelectedTest() => this.Test;
public override Tests RemoveEvaluation(BoundDagEvaluation e) => e.Equals(Test) ? Tests.True.Instance : (Tests)this;
public override string Dump(Func<BoundDagTest, string> dump) => dump(this.Test);
public override bool Equals(object? obj) => this == obj || obj is One other && this.Test.Equals(other.Test);
public override int GetHashCode() => this.Test.GetHashCode();
}
public sealed class Not : Tests
{
// Negation is pushed to the level of a single test by demorgan's laws
public readonly Tests Negated;
private Not(Tests negated) => Negated = negated;
public static Tests Create(Tests negated) => negated switch
{
Tests.True _ => Tests.False.Instance,
Tests.False _ => Tests.True.Instance,
Tests.Not n => n.Negated, // double negative
Tests.AndSequence a => new Not(a),
Tests.OrSequence a => Tests.AndSequence.Create(NegateSequenceElements(a.RemainingTests)), // use demorgan to prefer and sequences
Tests.One o => new Not(o),
_ => throw ExceptionUtilities.UnexpectedValue(negated),
};
private static ArrayBuilder<Tests> NegateSequenceElements(ImmutableArray<Tests> seq)
{
var builder = ArrayBuilder<Tests>.GetInstance(seq.Length);
foreach (var t in seq)
builder.Add(Not.Create(t));
return builder;
}
public override Tests RemoveEvaluation(BoundDagEvaluation e) => Create(Negated.RemoveEvaluation(e));
public override BoundDagTest ComputeSelectedTest() => Negated.ComputeSelectedTest();
public override string Dump(Func<BoundDagTest, string> dump) => $"Not ({Negated.Dump(dump)})";
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
Negated.Filter(builder, test, whenTrueValues, whenFalseValues, out var whenTestTrue, out var whenTestFalse, ref foundExplicitNullTest);
whenTrue = Not.Create(whenTestTrue);
whenFalse = Not.Create(whenTestFalse);
}
public override bool Equals(object? obj) => this == obj || obj is Not n && Negated.Equals(n.Negated);
public override int GetHashCode() => Hash.Combine(Negated.GetHashCode(), typeof(Not).GetHashCode());
}
public abstract class SequenceTests : Tests
{
public readonly ImmutableArray<Tests> RemainingTests;
protected SequenceTests(ImmutableArray<Tests> remainingTests)
{
Debug.Assert(remainingTests.Length > 1);
this.RemainingTests = remainingTests;
}
public abstract Tests Update(ArrayBuilder<Tests> remainingTests);
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
var trueBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length);
var falseBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length);
foreach (var other in RemainingTests)
{
other.Filter(builder, test, whenTrueValues, whenFalseValues, out Tests oneTrue, out Tests oneFalse, ref foundExplicitNullTest);
trueBuilder.Add(oneTrue);
falseBuilder.Add(oneFalse);
}
whenTrue = Update(trueBuilder);
whenFalse = Update(falseBuilder);
}
public override Tests RemoveEvaluation(BoundDagEvaluation e)
{
var builder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length);
foreach (var test in RemainingTests)
builder.Add(test.RemoveEvaluation(e));
return Update(builder);
}
public override bool Equals(object? obj) =>
this == obj || obj is SequenceTests other && this.GetType() == other.GetType() && RemainingTests.SequenceEqual(other.RemainingTests);
public override int GetHashCode()
{
int length = this.RemainingTests.Length;
int value = Hash.Combine(length, this.GetType().GetHashCode());
value = Hash.Combine(Hash.CombineValues(this.RemainingTests), value);
return value;
}
}
/// <summary>
/// A sequence of tests that must be performed, each of which must succeed.
/// The sequence is deemed to succeed if no element fails.
/// </summary>
public sealed class AndSequence : SequenceTests
{
private AndSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { }
public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests);
public static Tests Create(ArrayBuilder<Tests> remainingTests)
{
for (int i = remainingTests.Count - 1; i >= 0; i--)
{
switch (remainingTests[i])
{
case True _:
remainingTests.RemoveAt(i);
break;
case False f:
remainingTests.Free();
return f;
case AndSequence seq:
var testsToInsert = seq.RemainingTests;
remainingTests.RemoveAt(i);
for (int j = 0, n = testsToInsert.Length; j < n; j++)
remainingTests.Insert(i + j, testsToInsert[j]);
break;
}
}
var result = remainingTests.Count switch
{
0 => True.Instance,
1 => remainingTests[0],
_ => new AndSequence(remainingTests.ToImmutable()),
};
remainingTests.Free();
return result;
}
public override BoundDagTest ComputeSelectedTest()
{
// Our simple heuristic is to perform the first test of the
// first possible matched case, with two exceptions.
if (RemainingTests[0] is One { Test: { Kind: BoundKind.DagNonNullTest } planA })
{
switch (RemainingTests[1])
{
// In the specific case of a null check following by a type test, we skip the
// null check and perform the type test directly. That's because the type test
// has the side-effect of performing the null check for us.
case One { Test: { Kind: BoundKind.DagTypeTest } planB1 }:
return (planA.Input == planB1.Input) ? planB1 : planA;
// In the specific case of a null check following by a value test (which occurs for
// pattern matching a string constant pattern), we skip the
// null check and perform the value test directly. That's because the value test
// has the side-effect of performing the null check for us.
case One { Test: { Kind: BoundKind.DagValueTest } planB2 }:
return (planA.Input == planB2.Input) ? planB2 : planA;
}
}
return RemainingTests[0].ComputeSelectedTest();
}
public override string Dump(Func<BoundDagTest, string> dump)
{
return $"AND({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})";
}
}
/// <summary>
/// A sequence of tests that must be performed, any of which must succeed.
/// The sequence is deemed to succeed if some element succeeds.
/// </summary>
public sealed class OrSequence : SequenceTests
{
private OrSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { }
public override BoundDagTest ComputeSelectedTest() => this.RemainingTests[0].ComputeSelectedTest();
public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests);
public static Tests Create(ArrayBuilder<Tests> remainingTests)
{
for (int i = remainingTests.Count - 1; i >= 0; i--)
{
switch (remainingTests[i])
{
case False _:
remainingTests.RemoveAt(i);
break;
case True t:
remainingTests.Free();
return t;
case OrSequence seq:
remainingTests.RemoveAt(i);
var testsToInsert = seq.RemainingTests;
for (int j = 0, n = testsToInsert.Length; j < n; j++)
remainingTests.Insert(i + j, testsToInsert[j]);
break;
}
}
var result = remainingTests.Count switch
{
0 => False.Instance,
1 => remainingTests[0],
_ => new OrSequence(remainingTests.ToImmutable()),
};
remainingTests.Free();
return result;
}
public override string Dump(Func<BoundDagTest, string> dump)
{
return $"OR({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})";
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// <para>
/// A utility class for making a decision dag (directed acyclic graph) for a pattern-matching construct.
/// A decision dag is represented by
/// the class <see cref="BoundDecisionDag"/> and is a representation of a finite state automaton that performs a
/// sequence of binary tests. Each node is represented by a <see cref="BoundDecisionDagNode"/>. There are four
/// kind of nodes: <see cref="BoundTestDecisionDagNode"/> performs one of the binary tests;
/// <see cref="BoundEvaluationDecisionDagNode"/> simply performs some computation and stores it in one or more
/// temporary variables for use in subsequent nodes (think of it as a node with a single successor);
/// <see cref="BoundWhenDecisionDagNode"/> represents the test performed by evaluating the expression of the
/// when-clause of a switch case; and <see cref="BoundLeafDecisionDagNode"/> represents a leaf node when we
/// have finally determined exactly which case matches. Each test processes a single input, and there are
/// four kinds:<see cref="BoundDagExplicitNullTest"/> tests a value for null; <see cref="BoundDagNonNullTest"/>
/// tests that a value is not null; <see cref="BoundDagTypeTest"/> checks if the value is of a given type;
/// and <see cref="BoundDagValueTest"/> checks if the value is equal to a given constant. Of the evaluations,
/// there are <see cref="BoundDagDeconstructEvaluation"/> which represents an invocation of a type's
/// "Deconstruct" method; <see cref="BoundDagFieldEvaluation"/> reads a field; <see cref="BoundDagPropertyEvaluation"/>
/// reads a property; and <see cref="BoundDagTypeEvaluation"/> converts a value from one type to another (which
/// is performed only after testing that the value is of that type).
/// </para>
/// <para>
/// In order to build this automaton, we start (in
/// <see cref="MakeBoundDecisionDag(SyntaxNode, ImmutableArray{DecisionDagBuilder.StateForCase})"/>
/// by computing a description of the initial state in a <see cref="DagState"/>, and then
/// for each such state description we decide what the test or evaluation will be at
/// that state, and compute the successor state descriptions.
/// A state description represented by a <see cref="DagState"/> is a collection of partially matched
/// cases represented
/// by <see cref="StateForCase"/>, in which some number of the tests have already been performed
/// for each case.
/// When we have computed <see cref="DagState"/> descriptions for all of the states, we create a new
/// <see cref="BoundDecisionDagNode"/> for each of them, containing
/// the state transitions (including the test to perform at each node and the successor nodes) but
/// not the state descriptions. A <see cref="BoundDecisionDag"/> containing this
/// set of nodes becomes part of the bound nodes (e.g. in <see cref="BoundSwitchStatement"/> and
/// <see cref="BoundUnconvertedSwitchExpression"/>) and is used for semantic analysis and lowering.
/// </para>
/// </summary>
internal sealed class DecisionDagBuilder
{
private readonly CSharpCompilation _compilation;
private readonly Conversions _conversions;
private readonly BindingDiagnosticBag _diagnostics;
private readonly LabelSymbol _defaultLabel;
private DecisionDagBuilder(CSharpCompilation compilation, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics)
{
this._compilation = compilation;
this._conversions = compilation.Conversions;
_diagnostics = diagnostics;
_defaultLabel = defaultLabel;
}
/// <summary>
/// Create a decision dag for a switch statement.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForSwitchStatement(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression switchGoverningExpression,
ImmutableArray<BoundSwitchSection> switchSections,
LabelSymbol defaultLabel,
BindingDiagnosticBag diagnostics)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics);
return builder.CreateDecisionDagForSwitchStatement(syntax, switchGoverningExpression, switchSections);
}
/// <summary>
/// Create a decision dag for a switch expression.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForSwitchExpression(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression switchExpressionInput,
ImmutableArray<BoundSwitchExpressionArm> switchArms,
LabelSymbol defaultLabel,
BindingDiagnosticBag diagnostics)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics);
return builder.CreateDecisionDagForSwitchExpression(syntax, switchExpressionInput, switchArms);
}
/// <summary>
/// Translate the pattern of an is-pattern expression.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForIsPattern(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression inputExpression,
BoundPattern pattern,
LabelSymbol whenTrueLabel,
LabelSymbol whenFalseLabel,
BindingDiagnosticBag diagnostics)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel: whenFalseLabel, diagnostics);
return builder.CreateDecisionDagForIsPattern(syntax, inputExpression, pattern, whenTrueLabel);
}
private BoundDecisionDag CreateDecisionDagForIsPattern(
SyntaxNode syntax,
BoundExpression inputExpression,
BoundPattern pattern,
LabelSymbol whenTrueLabel)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(inputExpression);
return MakeBoundDecisionDag(syntax, ImmutableArray.Create(MakeTestsForPattern(index: 1, pattern.Syntax, rootIdentifier, pattern, whenClause: null, whenTrueLabel)));
}
private BoundDecisionDag CreateDecisionDagForSwitchStatement(
SyntaxNode syntax,
BoundExpression switchGoverningExpression,
ImmutableArray<BoundSwitchSection> switchSections)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(switchGoverningExpression);
int i = 0;
var builder = ArrayBuilder<StateForCase>.GetInstance(switchSections.Length);
foreach (BoundSwitchSection section in switchSections)
{
foreach (BoundSwitchLabel label in section.SwitchLabels)
{
if (label.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel)
{
builder.Add(MakeTestsForPattern(++i, label.Syntax, rootIdentifier, label.Pattern, label.WhenClause, label.Label));
}
}
}
return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree());
}
/// <summary>
/// Used to create a decision dag for a switch expression.
/// </summary>
private BoundDecisionDag CreateDecisionDagForSwitchExpression(
SyntaxNode syntax,
BoundExpression switchExpressionInput,
ImmutableArray<BoundSwitchExpressionArm> switchArms)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(switchExpressionInput);
int i = 0;
var builder = ArrayBuilder<StateForCase>.GetInstance(switchArms.Length);
foreach (BoundSwitchExpressionArm arm in switchArms)
builder.Add(MakeTestsForPattern(++i, arm.Syntax, rootIdentifier, arm.Pattern, arm.WhenClause, arm.Label));
return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree());
}
/// <summary>
/// Compute the set of remaining tests for a pattern.
/// </summary>
private StateForCase MakeTestsForPattern(
int index,
SyntaxNode syntax,
BoundDagTemp input,
BoundPattern pattern,
BoundExpression? whenClause,
LabelSymbol label)
{
Tests tests = MakeAndSimplifyTestsAndBindings(input, pattern, out ImmutableArray<BoundPatternBinding> bindings);
return new StateForCase(index, syntax, tests, bindings, whenClause, label);
}
private Tests MakeAndSimplifyTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
out ImmutableArray<BoundPatternBinding> bindings)
{
var bindingsBuilder = ArrayBuilder<BoundPatternBinding>.GetInstance();
Tests tests = MakeTestsAndBindings(input, pattern, bindingsBuilder);
tests = SimplifyTestsAndBindings(tests, bindingsBuilder);
bindings = bindingsBuilder.ToImmutableAndFree();
return tests;
}
private static Tests SimplifyTestsAndBindings(
Tests tests,
ArrayBuilder<BoundPatternBinding> bindingsBuilder)
{
// Now simplify the tests and bindings. We don't need anything in tests that does not
// contribute to the result. This will, for example, permit us to match `(2, 3) is (2, _)` without
// fetching `Item2` from the input.
var usedValues = PooledHashSet<BoundDagEvaluation>.GetInstance();
foreach (BoundPatternBinding binding in bindingsBuilder)
{
BoundDagTemp temp = binding.TempContainingValue;
if (temp.Source is { })
{
usedValues.Add(temp.Source);
}
}
var result = scanAndSimplify(tests);
usedValues.Free();
return result;
Tests scanAndSimplify(Tests tests)
{
switch (tests)
{
case Tests.SequenceTests seq:
var testSequence = seq.RemainingTests;
var length = testSequence.Length;
var newSequence = ArrayBuilder<Tests>.GetInstance(length);
newSequence.AddRange(testSequence);
for (int i = length - 1; i >= 0; i--)
{
newSequence[i] = scanAndSimplify(newSequence[i]);
}
return seq.Update(newSequence);
case Tests.True _:
case Tests.False _:
return tests;
case Tests.One(BoundDagEvaluation e):
if (usedValues.Contains(e))
{
if (e.Input.Source is { })
usedValues.Add(e.Input.Source);
return tests;
}
else
{
return Tests.True.Instance;
}
case Tests.One(BoundDagTest d):
if (d.Input.Source is { })
usedValues.Add(d.Input.Source);
return tests;
case Tests.Not n:
return Tests.Not.Create(scanAndSimplify(n.Negated));
default:
throw ExceptionUtilities.UnexpectedValue(tests);
}
}
}
private Tests MakeTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
ArrayBuilder<BoundPatternBinding> bindings)
{
return MakeTestsAndBindings(input, pattern, out _, bindings);
}
/// <summary>
/// Make the tests and variable bindings for the given pattern with the given input. The pattern's
/// "output" value is placed in <paramref name="output"/>. The output is defined as the input
/// narrowed according to the pattern's *narrowed type*; see https://github.com/dotnet/csharplang/issues/2850.
/// </summary>
private Tests MakeTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
Debug.Assert(pattern.HasErrors || pattern.InputType.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || pattern.InputType.IsErrorType());
switch (pattern)
{
case BoundDeclarationPattern declaration:
return MakeTestsAndBindingsForDeclarationPattern(input, declaration, out output, bindings);
case BoundConstantPattern constant:
return MakeTestsForConstantPattern(input, constant, out output);
case BoundDiscardPattern _:
output = input;
return Tests.True.Instance;
case BoundRecursivePattern recursive:
return MakeTestsAndBindingsForRecursivePattern(input, recursive, out output, bindings);
case BoundITuplePattern iTuple:
return MakeTestsAndBindingsForITuplePattern(input, iTuple, out output, bindings);
case BoundTypePattern type:
return MakeTestsForTypePattern(input, type, out output);
case BoundRelationalPattern rel:
return MakeTestsAndBindingsForRelationalPattern(input, rel, out output);
case BoundNegatedPattern neg:
output = input;
return MakeTestsAndBindingsForNegatedPattern(input, neg, bindings);
case BoundBinaryPattern bin:
return MakeTestsAndBindingsForBinaryPattern(input, bin, out output, bindings);
default:
throw ExceptionUtilities.UnexpectedValue(pattern.Kind);
}
}
private Tests MakeTestsAndBindingsForITuplePattern(
BoundDagTemp input,
BoundITuplePattern pattern,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
var syntax = pattern.Syntax;
var patternLength = pattern.Subpatterns.Length;
var objectType = this._compilation.GetSpecialType(SpecialType.System_Object);
var getLengthProperty = (PropertySymbol)pattern.GetLengthMethod.AssociatedSymbol;
RoslynDebug.Assert(getLengthProperty.Type.SpecialType == SpecialType.System_Int32);
var getItemProperty = (PropertySymbol)pattern.GetItemMethod.AssociatedSymbol;
var iTupleType = getLengthProperty.ContainingType;
RoslynDebug.Assert(iTupleType.Name == "ITuple");
var tests = ArrayBuilder<Tests>.GetInstance(4 + patternLength * 2);
tests.Add(new Tests.One(new BoundDagTypeTest(syntax, iTupleType, input)));
var valueAsITupleEvaluation = new BoundDagTypeEvaluation(syntax, iTupleType, input);
tests.Add(new Tests.One(valueAsITupleEvaluation));
var valueAsITuple = new BoundDagTemp(syntax, iTupleType, valueAsITupleEvaluation);
output = valueAsITuple;
var lengthEvaluation = new BoundDagPropertyEvaluation(syntax, getLengthProperty, OriginalInput(valueAsITuple, getLengthProperty));
tests.Add(new Tests.One(lengthEvaluation));
var lengthTemp = new BoundDagTemp(syntax, this._compilation.GetSpecialType(SpecialType.System_Int32), lengthEvaluation);
tests.Add(new Tests.One(new BoundDagValueTest(syntax, ConstantValue.Create(patternLength), lengthTemp)));
var getItemPropertyInput = OriginalInput(valueAsITuple, getItemProperty);
for (int i = 0; i < patternLength; i++)
{
var indexEvaluation = new BoundDagIndexEvaluation(syntax, getItemProperty, i, getItemPropertyInput);
tests.Add(new Tests.One(indexEvaluation));
var indexTemp = new BoundDagTemp(syntax, objectType, indexEvaluation);
tests.Add(MakeTestsAndBindings(indexTemp, pattern.Subpatterns[i].Pattern, bindings));
}
return Tests.AndSequence.Create(tests);
}
/// <summary>
/// Get the earliest input of which the symbol is a member.
/// A BoundDagTypeEvaluation doesn't change the underlying object being pointed to.
/// So two evaluations act on the same input so long as they have the same original input.
/// We use this method to compute the original input for an evaluation.
/// </summary>
private BoundDagTemp OriginalInput(BoundDagTemp input, Symbol symbol)
{
while (input.Source is BoundDagTypeEvaluation source && IsDerivedType(source.Input.Type, symbol.ContainingType))
{
input = source.Input;
}
return input;
}
bool IsDerivedType(TypeSymbol possibleDerived, TypeSymbol possibleBase)
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return this._conversions.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo);
}
private Tests MakeTestsAndBindingsForDeclarationPattern(
BoundDagTemp input,
BoundDeclarationPattern declaration,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
TypeSymbol? type = declaration.DeclaredType?.Type;
var tests = ArrayBuilder<Tests>.GetInstance(1);
// Add a null and type test if needed.
if (!declaration.IsVar)
input = MakeConvertToType(input, declaration.Syntax, type!, isExplicitTest: false, tests);
BoundExpression? variableAccess = declaration.VariableAccess;
if (variableAccess is { })
{
Debug.Assert(variableAccess.Type!.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || variableAccess.Type.IsErrorType());
bindings.Add(new BoundPatternBinding(variableAccess, input));
}
else
{
RoslynDebug.Assert(declaration.Variable == null);
}
output = input;
return Tests.AndSequence.Create(tests);
}
private Tests MakeTestsForTypePattern(
BoundDagTemp input,
BoundTypePattern typePattern,
out BoundDagTemp output)
{
TypeSymbol type = typePattern.DeclaredType.Type;
var tests = ArrayBuilder<Tests>.GetInstance(4);
output = MakeConvertToType(input: input, syntax: typePattern.Syntax, type: type, isExplicitTest: typePattern.IsExplicitNotNullTest, tests: tests);
return Tests.AndSequence.Create(tests);
}
private static void MakeCheckNotNull(
BoundDagTemp input,
SyntaxNode syntax,
bool isExplicitTest,
ArrayBuilder<Tests> tests)
{
// Add a null test if needed
if (input.Type.CanContainNull())
tests.Add(new Tests.One(new BoundDagNonNullTest(syntax, isExplicitTest, input)));
}
/// <summary>
/// Generate a not-null check and a type check.
/// </summary>
private BoundDagTemp MakeConvertToType(
BoundDagTemp input,
SyntaxNode syntax,
TypeSymbol type,
bool isExplicitTest,
ArrayBuilder<Tests> tests)
{
MakeCheckNotNull(input, syntax, isExplicitTest, tests);
if (!input.Type.Equals(type, TypeCompareKind.AllIgnoreOptions))
{
TypeSymbol inputType = input.Type.StrippedType(); // since a null check has already been done
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly);
Conversion conversion = _conversions.ClassifyBuiltInConversion(inputType, type, ref useSiteInfo);
_diagnostics.Add(syntax, useSiteInfo);
if (input.Type.IsDynamic() ? type.SpecialType == SpecialType.System_Object : conversion.IsImplicit)
{
// type test not needed, only the type cast
}
else
{
// both type test and cast needed
tests.Add(new Tests.One(new BoundDagTypeTest(syntax, type, input)));
}
var evaluation = new BoundDagTypeEvaluation(syntax, type, input);
input = new BoundDagTemp(syntax, type, evaluation);
tests.Add(new Tests.One(evaluation));
}
return input;
}
private Tests MakeTestsForConstantPattern(
BoundDagTemp input,
BoundConstantPattern constant,
out BoundDagTemp output)
{
if (constant.ConstantValue == ConstantValue.Null)
{
output = input;
return new Tests.One(new BoundDagExplicitNullTest(constant.Syntax, input));
}
else
{
var tests = ArrayBuilder<Tests>.GetInstance(2);
var convertedInput = MakeConvertToType(input, constant.Syntax, constant.Value.Type!, isExplicitTest: false, tests);
output = convertedInput;
tests.Add(new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, convertedInput)));
return Tests.AndSequence.Create(tests);
}
}
private Tests MakeTestsAndBindingsForRecursivePattern(
BoundDagTemp input,
BoundRecursivePattern recursive,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
RoslynDebug.Assert(input.Type.IsErrorType() || recursive.HasErrors || recursive.InputType.IsErrorType() || input.Type.Equals(recursive.InputType, TypeCompareKind.AllIgnoreOptions));
var inputType = recursive.DeclaredType?.Type ?? input.Type.StrippedType();
var tests = ArrayBuilder<Tests>.GetInstance(5);
output = input = MakeConvertToType(input, recursive.Syntax, inputType, isExplicitTest: recursive.IsExplicitNotNullTest, tests);
if (!recursive.Deconstruction.IsDefault)
{
// we have a "deconstruction" form, which is either an invocation of a Deconstruct method, or a disassembly of a tuple
if (recursive.DeconstructMethod != null)
{
MethodSymbol method = recursive.DeconstructMethod;
var evaluation = new BoundDagDeconstructEvaluation(recursive.Syntax, method, OriginalInput(input, method));
tests.Add(new Tests.One(evaluation));
int extensionExtra = method.IsStatic ? 1 : 0;
int count = Math.Min(method.ParameterCount - extensionExtra, recursive.Deconstruction.Length);
for (int i = 0; i < count; i++)
{
BoundPattern pattern = recursive.Deconstruction[i].Pattern;
SyntaxNode syntax = pattern.Syntax;
var element = new BoundDagTemp(syntax, method.Parameters[i + extensionExtra].Type, evaluation, i);
tests.Add(MakeTestsAndBindings(element, pattern, bindings));
}
}
else if (Binder.IsZeroElementTupleType(inputType))
{
// Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType`
// do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests
// required to identify it. When that bug is fixed we should be able to remove this if statement.
// nothing to do, as there are no tests for the zero elements of this tuple
}
else if (inputType.IsTupleType)
{
ImmutableArray<FieldSymbol> elements = inputType.TupleElements;
ImmutableArray<TypeWithAnnotations> elementTypes = inputType.TupleElementTypesWithAnnotations;
int count = Math.Min(elementTypes.Length, recursive.Deconstruction.Length);
for (int i = 0; i < count; i++)
{
BoundPattern pattern = recursive.Deconstruction[i].Pattern;
SyntaxNode syntax = pattern.Syntax;
FieldSymbol field = elements[i];
var evaluation = new BoundDagFieldEvaluation(syntax, field, OriginalInput(input, field)); // fetch the ItemN field
tests.Add(new Tests.One(evaluation));
var element = new BoundDagTemp(syntax, field.Type, evaluation);
tests.Add(MakeTestsAndBindings(element, pattern, bindings));
}
}
else
{
// This occurs in error cases.
RoslynDebug.Assert(recursive.HasAnyErrors);
// To prevent this pattern from subsuming other patterns and triggering a cascaded diagnostic, we add a test that will fail.
tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true)));
}
}
if (!recursive.Properties.IsDefault)
{
// we have a "property" form
foreach (var subpattern in recursive.Properties)
{
BoundPattern pattern = subpattern.Pattern;
BoundDagTemp currentInput = input;
if (!tryMakeSubpatternMemberTests(subpattern.Member, ref currentInput))
{
Debug.Assert(recursive.HasAnyErrors);
tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true)));
}
else
{
tests.Add(MakeTestsAndBindings(currentInput, pattern, bindings));
}
}
}
if (recursive.VariableAccess != null)
{
// we have a "variable" declaration
bindings.Add(new BoundPatternBinding(recursive.VariableAccess, input));
}
return Tests.AndSequence.Create(tests);
bool tryMakeSubpatternMemberTests([NotNullWhen(true)] BoundPropertySubpatternMember? member, ref BoundDagTemp input)
{
if (member is null)
return false;
if (tryMakeSubpatternMemberTests(member.Receiver, ref input))
{
// If this is not the first member, add null test, unwrap nullables, and continue.
input = MakeConvertToType(input, member.Syntax, member.Receiver.Type.StrippedType(), isExplicitTest: false, tests);
}
BoundDagEvaluation evaluation;
switch (member.Symbol)
{
case PropertySymbol property:
evaluation = new BoundDagPropertyEvaluation(member.Syntax, property, OriginalInput(input, property));
break;
case FieldSymbol field:
evaluation = new BoundDagFieldEvaluation(member.Syntax, field, OriginalInput(input, field));
break;
default:
return false;
}
tests.Add(new Tests.One(evaluation));
input = new BoundDagTemp(member.Syntax, member.Type, evaluation);
return true;
}
}
private Tests MakeTestsAndBindingsForNegatedPattern(BoundDagTemp input, BoundNegatedPattern neg, ArrayBuilder<BoundPatternBinding> bindings)
{
var tests = MakeTestsAndBindings(input, neg.Negated, bindings);
return Tests.Not.Create(tests);
}
private Tests MakeTestsAndBindingsForBinaryPattern(
BoundDagTemp input,
BoundBinaryPattern bin,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
var builder = ArrayBuilder<Tests>.GetInstance(2);
if (bin.Disjunction)
{
builder.Add(MakeTestsAndBindings(input, bin.Left, bindings));
builder.Add(MakeTestsAndBindings(input, bin.Right, bindings));
var result = Tests.OrSequence.Create(builder);
if (bin.InputType.Equals(bin.NarrowedType))
{
output = input;
return result;
}
else
{
builder = ArrayBuilder<Tests>.GetInstance(2);
builder.Add(result);
output = MakeConvertToType(input: input, syntax: bin.Syntax, type: bin.NarrowedType, isExplicitTest: false, tests: builder);
return Tests.AndSequence.Create(builder);
}
}
else
{
builder.Add(MakeTestsAndBindings(input, bin.Left, out var leftOutput, bindings));
builder.Add(MakeTestsAndBindings(leftOutput, bin.Right, out var rightOutput, bindings));
output = rightOutput;
Debug.Assert(bin.HasErrors || output.Type.Equals(bin.NarrowedType, TypeCompareKind.AllIgnoreOptions));
return Tests.AndSequence.Create(builder);
}
}
private Tests MakeTestsAndBindingsForRelationalPattern(
BoundDagTemp input,
BoundRelationalPattern rel,
out BoundDagTemp output)
{
// check if the test is always true or always false
var tests = ArrayBuilder<Tests>.GetInstance(2);
output = MakeConvertToType(input, rel.Syntax, rel.Value.Type!, isExplicitTest: false, tests);
var fac = ValueSetFactory.ForType(input.Type);
var values = fac?.Related(rel.Relation.Operator(), rel.ConstantValue);
if (values?.IsEmpty == true)
{
tests.Add(Tests.False.Instance);
}
else if (values?.Complement().IsEmpty != true)
{
tests.Add(new Tests.One(new BoundDagRelationalTest(rel.Syntax, rel.Relation, rel.ConstantValue, output, rel.HasErrors)));
}
return Tests.AndSequence.Create(tests);
}
private TypeSymbol ErrorType(string name = "")
{
return new ExtendedErrorTypeSymbol(this._compilation, name, arity: 0, errorInfo: null, unreported: false);
}
/// <summary>
/// Compute and translate the decision dag, given a description of its initial state and a default
/// decision when no decision appears to match. This implementation is nonrecursive to avoid
/// overflowing the compiler's evaluation stack when compiling a large switch statement.
/// </summary>
private BoundDecisionDag MakeBoundDecisionDag(SyntaxNode syntax, ImmutableArray<StateForCase> cases)
{
// Build the state machine underlying the decision dag
DecisionDag decisionDag = MakeDecisionDag(cases);
// Note: It is useful for debugging the dag state table construction to set a breakpoint
// here and view `decisionDag.Dump()`.
;
// Compute the bound decision dag corresponding to each node of decisionDag, and store
// it in node.Dag.
var defaultDecision = new BoundLeafDecisionDagNode(syntax, _defaultLabel);
ComputeBoundDecisionDagNodes(decisionDag, defaultDecision);
var rootDecisionDagNode = decisionDag.RootNode.Dag;
RoslynDebug.Assert(rootDecisionDagNode != null);
var boundDecisionDag = new BoundDecisionDag(rootDecisionDagNode.Syntax, rootDecisionDagNode);
#if DEBUG
// Note that this uses the custom equality in `BoundDagEvaluation`
// to make "equivalent" evaluation nodes share the same ID.
var nextTempNumber = 0;
var tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance();
var sortedBoundDagNodes = boundDecisionDag.TopologicallySortedNodes;
for (int i = 0; i < sortedBoundDagNodes.Length; i++)
{
var node = sortedBoundDagNodes[i];
node.Id = i;
switch (node)
{
case BoundEvaluationDecisionDagNode { Evaluation: { Id: -1 } evaluation }:
evaluation.Id = tempIdentifier(evaluation);
// Note that "equivalent" evaluations may be different object instances.
// Therefore we have to dig into the Input.Source of evaluations and tests to set their IDs.
if (evaluation.Input.Source is { Id: -1 } source)
{
source.Id = tempIdentifier(source);
}
break;
case BoundTestDecisionDagNode { Test: var test }:
if (test.Input.Source is { Id: -1 } testSource)
{
testSource.Id = tempIdentifier(testSource);
}
break;
}
}
tempIdentifierMap.Free();
int tempIdentifier(BoundDagEvaluation e)
{
return tempIdentifierMap.TryGetValue(e, out int value)
? value
: tempIdentifierMap[e] = ++nextTempNumber;
}
#endif
return boundDecisionDag;
}
/// <summary>
/// Make a <see cref="DecisionDag"/> (state machine) starting with the given set of cases in the root node,
/// and return the node for the root.
/// </summary>
private DecisionDag MakeDecisionDag(ImmutableArray<StateForCase> casesForRootNode)
{
// A work list of DagStates whose successors need to be computed
var workList = ArrayBuilder<DagState>.GetInstance();
// A mapping used to make each DagState unique (i.e. to de-dup identical states).
var uniqueState = new Dictionary<DagState, DagState>(DagStateEquivalence.Instance);
// We "intern" the states, so that we only have a single object representing one
// semantic state. Because the decision automaton may contain states that have more than one
// predecessor, we want to represent each such state as a reference-unique object
// so that it is processed only once. This object identity uniqueness will be important later when we
// start mutating the DagState nodes to compute successors and BoundDecisionDagNodes
// for each one. That is why we have to use an equivalence relation in the dictionary `uniqueState`.
DagState uniqifyState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues)
{
var state = new DagState(cases, remainingValues);
if (uniqueState.TryGetValue(state, out DagState? existingState))
{
// We found an existing state that matches. Update its set of possible remaining values
// of each temp by taking the union of the sets on each incoming edge.
var newRemainingValues = ImmutableDictionary.CreateBuilder<BoundDagTemp, IValueSet>();
foreach (var (dagTemp, valuesForTemp) in remainingValues)
{
// If one incoming edge does not have a set of possible values for the temp,
// that means the temp can take on any value of its type.
if (existingState.RemainingValues.TryGetValue(dagTemp, out var existingValuesForTemp))
{
var newExistingValuesForTemp = existingValuesForTemp.Union(valuesForTemp);
newRemainingValues.Add(dagTemp, newExistingValuesForTemp);
}
}
if (existingState.RemainingValues.Count != newRemainingValues.Count ||
!existingState.RemainingValues.All(kv => newRemainingValues.TryGetValue(kv.Key, out IValueSet? values) && kv.Value.Equals(values)))
{
existingState.UpdateRemainingValues(newRemainingValues.ToImmutable());
if (!workList.Contains(existingState))
workList.Push(existingState);
}
return existingState;
}
else
{
// When we add a new unique state, we add it to a work list so that we
// will process it to compute its successors.
uniqueState.Add(state, state);
workList.Push(state);
return state;
}
}
// Simplify the initial state based on impossible or earlier matched cases
var rewrittenCases = ArrayBuilder<StateForCase>.GetInstance(casesForRootNode.Length);
foreach (var state in casesForRootNode)
{
if (state.IsImpossible)
continue;
rewrittenCases.Add(state);
if (state.IsFullyMatched)
break;
}
var initialState = uniqifyState(rewrittenCases.ToImmutableAndFree(), ImmutableDictionary<BoundDagTemp, IValueSet>.Empty);
// Go through the worklist of DagState nodes for which we have not yet computed
// successor states.
while (workList.Count != 0)
{
DagState state = workList.Pop();
RoslynDebug.Assert(state.SelectedTest == null);
RoslynDebug.Assert(state.TrueBranch == null);
RoslynDebug.Assert(state.FalseBranch == null);
if (state.Cases.IsDefaultOrEmpty)
{
// If this state has no more cases that could possibly match, then
// we know there is no case that will match and this node represents a "default"
// decision. We do not need to compute a successor, as it is a leaf node
continue;
}
StateForCase first = state.Cases[0];
Debug.Assert(!first.IsImpossible);
if (first.PatternIsSatisfied)
{
if (first.IsFullyMatched)
{
// The first of the remaining cases has fully matched, as there are no more tests to do.
// The language semantics of the switch statement and switch expression require that we
// execute the first matching case. There is no when clause to evaluate here,
// so this is a leaf node and required no further processing.
}
else
{
// There is a when clause to evaluate.
// In case the when clause fails, we prepare for the remaining cases.
var stateWhenFails = state.Cases.RemoveAt(0);
state.FalseBranch = uniqifyState(stateWhenFails, state.RemainingValues);
}
}
else
{
// Select the next test to do at this state, and compute successor states
switch (state.SelectedTest = state.ComputeSelectedTest())
{
case BoundDagEvaluation e:
state.TrueBranch = uniqifyState(RemoveEvaluation(state.Cases, e), state.RemainingValues);
// An evaluation is considered to always succeed, so there is no false branch
break;
case BoundDagTest d:
bool foundExplicitNullTest = false;
SplitCases(
state.Cases, state.RemainingValues, d,
out ImmutableArray<StateForCase> whenTrueDecisions,
out ImmutableArray<StateForCase> whenFalseDecisions,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
ref foundExplicitNullTest);
state.TrueBranch = uniqifyState(whenTrueDecisions, whenTrueValues);
state.FalseBranch = uniqifyState(whenFalseDecisions, whenFalseValues);
if (foundExplicitNullTest && d is BoundDagNonNullTest { IsExplicitTest: false } t)
{
// Turn an "implicit" non-null test into an explicit one
state.SelectedTest = new BoundDagNonNullTest(t.Syntax, isExplicitTest: true, t.Input, t.HasErrors);
}
break;
case var n:
throw ExceptionUtilities.UnexpectedValue(n.Kind);
}
}
}
workList.Free();
return new DecisionDag(initialState);
}
/// <summary>
/// Compute the <see cref="BoundDecisionDag"/> corresponding to each <see cref="DagState"/> of the given <see cref="DecisionDag"/>
/// and store it in <see cref="DagState.Dag"/>.
/// </summary>
private void ComputeBoundDecisionDagNodes(DecisionDag decisionDag, BoundLeafDecisionDagNode defaultDecision)
{
Debug.Assert(_defaultLabel != null);
Debug.Assert(defaultDecision != null);
// Process the states in topological order, leaves first, and assign a BoundDecisionDag to each DagState.
bool wasAcyclic = decisionDag.TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> sortedStates);
if (!wasAcyclic)
{
// Since we intend the set of DagState nodes to be acyclic by construction, we do not expect
// this to occur. Just in case it does due to bugs, we recover gracefully to avoid crashing the
// compiler in production. If you find that this happens (the assert fails), please modify the
// DagState construction process to avoid creating a cyclic state graph.
Debug.Assert(wasAcyclic); // force failure in debug builds
// If the dag contains a cycle, return a short-circuit dag instead.
decisionDag.RootNode.Dag = defaultDecision;
return;
}
// We "intern" the dag nodes, so that we only have a single object representing one
// semantic node. We do this because different states may end up mapping to the same
// set of successor states. In this case we merge them when producing the bound state machine.
var uniqueNodes = PooledDictionary<BoundDecisionDagNode, BoundDecisionDagNode>.GetInstance();
BoundDecisionDagNode uniqifyDagNode(BoundDecisionDagNode node) => uniqueNodes.GetOrAdd(node, node);
_ = uniqifyDagNode(defaultDecision);
for (int i = sortedStates.Length - 1; i >= 0; i--)
{
var state = sortedStates[i];
if (state.Cases.IsDefaultOrEmpty)
{
state.Dag = defaultDecision;
continue;
}
StateForCase first = state.Cases[0];
RoslynDebug.Assert(!(first.RemainingTests is Tests.False));
if (first.PatternIsSatisfied)
{
if (first.IsFullyMatched)
{
// there is no when clause we need to evaluate
state.Dag = finalState(first.Syntax, first.CaseLabel, first.Bindings);
}
else
{
RoslynDebug.Assert(state.TrueBranch == null);
RoslynDebug.Assert(state.FalseBranch is { });
// The final state here does not need bindings, as they will be performed before evaluating the when clause (see below)
BoundDecisionDagNode whenTrue = finalState(first.Syntax, first.CaseLabel, default);
BoundDecisionDagNode? whenFalse = state.FalseBranch.Dag;
RoslynDebug.Assert(whenFalse is { });
// Note: we may share `when` clauses between multiple DAG nodes, but we deal with that safely during lowering
state.Dag = uniqifyDagNode(new BoundWhenDecisionDagNode(first.Syntax, first.Bindings, first.WhenClause, whenTrue, whenFalse));
}
BoundDecisionDagNode finalState(SyntaxNode syntax, LabelSymbol label, ImmutableArray<BoundPatternBinding> bindings)
{
BoundDecisionDagNode final = uniqifyDagNode(new BoundLeafDecisionDagNode(syntax, label));
return bindings.IsDefaultOrEmpty ? final : uniqifyDagNode(new BoundWhenDecisionDagNode(syntax, bindings, null, final, null));
}
}
else
{
switch (state.SelectedTest)
{
case BoundDagEvaluation e:
{
BoundDecisionDagNode? next = state.TrueBranch!.Dag;
RoslynDebug.Assert(next is { });
RoslynDebug.Assert(state.FalseBranch == null);
state.Dag = uniqifyDagNode(new BoundEvaluationDecisionDagNode(e.Syntax, e, next));
}
break;
case BoundDagTest d:
{
BoundDecisionDagNode? whenTrue = state.TrueBranch!.Dag;
BoundDecisionDagNode? whenFalse = state.FalseBranch!.Dag;
RoslynDebug.Assert(whenTrue is { });
RoslynDebug.Assert(whenFalse is { });
state.Dag = uniqifyDagNode(new BoundTestDecisionDagNode(d.Syntax, d, whenTrue, whenFalse));
}
break;
case var n:
throw ExceptionUtilities.UnexpectedValue(n?.Kind);
}
}
}
uniqueNodes.Free();
}
private void SplitCase(
StateForCase stateForCase,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out StateForCase whenTrue,
out StateForCase whenFalse,
ref bool foundExplicitNullTest)
{
stateForCase.RemainingTests.Filter(this, test, whenTrueValues, whenFalseValues, out Tests whenTrueTests, out Tests whenFalseTests, ref foundExplicitNullTest);
whenTrue = makeNext(whenTrueTests);
whenFalse = makeNext(whenFalseTests);
return;
StateForCase makeNext(Tests remainingTests)
{
return remainingTests.Equals(stateForCase.RemainingTests)
? stateForCase
: new StateForCase(
stateForCase.Index, stateForCase.Syntax, remainingTests,
stateForCase.Bindings, stateForCase.WhenClause, stateForCase.CaseLabel);
}
}
private void SplitCases(
ImmutableArray<StateForCase> statesForCases,
ImmutableDictionary<BoundDagTemp, IValueSet> values,
BoundDagTest test,
out ImmutableArray<StateForCase> whenTrue,
out ImmutableArray<StateForCase> whenFalse,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
ref bool foundExplicitNullTest)
{
var whenTrueBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length);
var whenFalseBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length);
bool whenTruePossible, whenFalsePossible;
(whenTrueValues, whenFalseValues, whenTruePossible, whenFalsePossible) = SplitValues(values, test);
// whenTruePossible means the test could possibly have succeeded. whenFalsePossible means it could possibly have failed.
// Tests that are either impossible or tautological (i.e. either of these false) given
// the set of values are normally removed and replaced by the known result, so we would not normally be processing
// a test that always succeeds or always fails, but they can occur in erroneous programs (e.g. testing for equality
// against a non-constant value).
foreach (var state in statesForCases)
{
SplitCase(
state, test,
whenTrueValues.TryGetValue(test.Input, out var v1) ? v1 : null,
whenFalseValues.TryGetValue(test.Input, out var v2) ? v2 : null,
out var whenTrueState, out var whenFalseState, ref foundExplicitNullTest);
// whenTrueState.IsImpossible occurs when Split results in a state for a given case where the case has been ruled
// out (because its test has failed). If not whenTruePossible, we don't want to add anything to the state. In
// either case, we do not want to add the current case to the state.
if (whenTruePossible && !whenTrueState.IsImpossible && !(whenTrueBuilder.Any() && whenTrueBuilder.Last().IsFullyMatched))
whenTrueBuilder.Add(whenTrueState);
// Similarly for the alternative state.
if (whenFalsePossible && !whenFalseState.IsImpossible && !(whenFalseBuilder.Any() && whenFalseBuilder.Last().IsFullyMatched))
whenFalseBuilder.Add(whenFalseState);
}
whenTrue = whenTrueBuilder.ToImmutableAndFree();
whenFalse = whenFalseBuilder.ToImmutableAndFree();
}
private static (
ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
bool truePossible,
bool falsePossible)
SplitValues(
ImmutableDictionary<BoundDagTemp, IValueSet> values,
BoundDagTest test)
{
switch (test)
{
case BoundDagEvaluation _:
case BoundDagExplicitNullTest _:
case BoundDagNonNullTest _:
case BoundDagTypeTest _:
return (values, values, true, true);
case BoundDagValueTest t:
return resultForRelation(BinaryOperatorKind.Equal, t.Value);
case BoundDagRelationalTest t:
return resultForRelation(t.Relation, t.Value);
default:
throw ExceptionUtilities.UnexpectedValue(test);
}
(
ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues,
ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues,
bool truePossible,
bool falsePossible)
resultForRelation(BinaryOperatorKind relation, ConstantValue value)
{
var input = test.Input;
IValueSetFactory? valueFac = ValueSetFactory.ForType(input.Type);
if (valueFac == null || value.IsBad)
{
// If it is a type we don't track yet, assume all values are possible
return (values, values, true, true);
}
IValueSet fromTestPassing = valueFac.Related(relation.Operator(), value);
IValueSet fromTestFailing = fromTestPassing.Complement();
if (values.TryGetValue(test.Input, out IValueSet? tempValuesBeforeTest))
{
fromTestPassing = fromTestPassing.Intersect(tempValuesBeforeTest);
fromTestFailing = fromTestFailing.Intersect(tempValuesBeforeTest);
}
var whenTrueValues = values.SetItem(input, fromTestPassing);
var whenFalseValues = values.SetItem(input, fromTestFailing);
return (whenTrueValues, whenFalseValues, !fromTestPassing.IsEmpty, !fromTestFailing.IsEmpty);
}
}
private static ImmutableArray<StateForCase> RemoveEvaluation(ImmutableArray<StateForCase> cases, BoundDagEvaluation e)
{
var builder = ArrayBuilder<StateForCase>.GetInstance(cases.Length);
foreach (var stateForCase in cases)
{
var remainingTests = stateForCase.RemainingTests.RemoveEvaluation(e);
if (remainingTests is Tests.False)
{
// This can occur in error cases like `e is not int x` where there is a trailing evaluation
// in a failure branch.
}
else
{
builder.Add(new StateForCase(
Index: stateForCase.Index, Syntax: stateForCase.Syntax,
RemainingTests: remainingTests,
Bindings: stateForCase.Bindings, WhenClause: stateForCase.WhenClause, CaseLabel: stateForCase.CaseLabel));
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Given that the test <paramref name="test"/> has occurred and produced a true/false result,
/// set some flags indicating the implied status of the <paramref name="other"/> test.
/// </summary>
/// <param name="test"></param>
/// <param name="other"></param>
/// <param name="whenTrueValues">The possible values of test.Input when <paramref name="test"/> has succeeded.</param>
/// <param name="whenFalseValues">The possible values of test.Input when <paramref name="test"/> has failed.</param>
/// <param name="trueTestPermitsTrueOther">set if <paramref name="test"/> being true would permit <paramref name="other"/> to succeed</param>
/// <param name="falseTestPermitsTrueOther">set if a false result on <paramref name="test"/> would permit <paramref name="other"/> to succeed</param>
/// <param name="trueTestImpliesTrueOther">set if <paramref name="test"/> being true means <paramref name="other"/> has been proven true</param>
/// <param name="falseTestImpliesTrueOther">set if <paramref name="test"/> being false means <paramref name="other"/> has been proven true</param>
private void CheckConsistentDecision(
BoundDagTest test,
BoundDagTest other,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
SyntaxNode syntax,
out bool trueTestPermitsTrueOther,
out bool falseTestPermitsTrueOther,
out bool trueTestImpliesTrueOther,
out bool falseTestImpliesTrueOther,
ref bool foundExplicitNullTest)
{
// innocent until proven guilty
trueTestPermitsTrueOther = true;
falseTestPermitsTrueOther = true;
trueTestImpliesTrueOther = false;
falseTestImpliesTrueOther = false;
// if the tests are for unrelated things, there is no implication from one to the other
if (!test.Input.Equals(other.Input))
return;
switch (test)
{
case BoundDagNonNullTest _:
switch (other)
{
case BoundDagValueTest _:
// !(v != null) --> !(v == K)
falseTestPermitsTrueOther = false;
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v != null --> !(v == null)
trueTestPermitsTrueOther = false;
// !(v != null) --> v == null
falseTestImpliesTrueOther = true;
break;
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v != null --> v != null
trueTestImpliesTrueOther = true;
// !(v != null) --> !(v != null)
falseTestPermitsTrueOther = false;
break;
default:
// !(v != null) --> !(v is T)
falseTestPermitsTrueOther = false;
break;
}
break;
case BoundDagTypeTest t1:
switch (other)
{
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v is T --> v != null
trueTestImpliesTrueOther = true;
break;
case BoundDagTypeTest t2:
{
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly);
bool? matches = ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(t1.Type, t2.Type, ref useSiteInfo);
if (matches == false)
{
// If T1 could never be T2
// v is T1 --> !(v is T2)
trueTestPermitsTrueOther = false;
}
else if (matches == true)
{
// If T1: T2
// v is T1 --> v is T2
trueTestImpliesTrueOther = true;
}
// If every T2 is a T1, then failure of T1 implies failure of T2.
matches = Binder.ExpressionOfTypeMatchesPatternType(_conversions, t2.Type, t1.Type, ref useSiteInfo, out _);
_diagnostics.Add(syntax, useSiteInfo);
if (matches == true)
{
// If T2: T1
// !(v is T1) --> !(v is T2)
falseTestPermitsTrueOther = false;
}
}
break;
case BoundDagValueTest _:
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v is T --> !(v == null)
trueTestPermitsTrueOther = false;
break;
}
break;
case BoundDagValueTest _:
case BoundDagRelationalTest _:
switch (other)
{
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v == K --> v != null
trueTestImpliesTrueOther = true;
break;
case BoundDagTypeTest _:
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v == K --> !(v == null)
trueTestPermitsTrueOther = false;
break;
case BoundDagRelationalTest r2:
handleRelationWithValue(r2.Relation, r2.Value,
out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther);
break;
case BoundDagValueTest v2:
handleRelationWithValue(BinaryOperatorKind.Equal, v2.Value,
out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther);
break;
void handleRelationWithValue(
BinaryOperatorKind relation,
ConstantValue value,
out bool trueTestPermitsTrueOther,
out bool falseTestPermitsTrueOther,
out bool trueTestImpliesTrueOther,
out bool falseTestImpliesTrueOther)
{
// We check test.Equals(other) to handle "bad" constant values
bool sameTest = test.Equals(other);
trueTestPermitsTrueOther = whenTrueValues?.Any(relation, value) ?? true;
trueTestImpliesTrueOther = sameTest || trueTestPermitsTrueOther && (whenTrueValues?.All(relation, value) ?? false);
falseTestPermitsTrueOther = !sameTest && (whenFalseValues?.Any(relation, value) ?? true);
falseTestImpliesTrueOther = falseTestPermitsTrueOther && (whenFalseValues?.All(relation, value) ?? false);
}
}
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
switch (other)
{
case BoundDagNonNullTest n2:
if (n2.IsExplicitTest)
foundExplicitNullTest = true;
// v == null --> !(v != null)
trueTestPermitsTrueOther = false;
// !(v == null) --> v != null
falseTestImpliesTrueOther = true;
break;
case BoundDagTypeTest _:
// v == null --> !(v is T)
trueTestPermitsTrueOther = false;
break;
case BoundDagExplicitNullTest _:
foundExplicitNullTest = true;
// v == null --> v == null
trueTestImpliesTrueOther = true;
// !(v == null) --> !(v == null)
falseTestPermitsTrueOther = false;
break;
case BoundDagValueTest _:
// v == null --> !(v == K)
trueTestPermitsTrueOther = false;
break;
}
break;
}
}
/// <summary>
/// Determine what we can learn from one successful runtime type test about another planned
/// runtime type test for the purpose of building the decision tree.
/// We accommodate a special behavior of the runtime here, which does not match the language rules.
/// A value of type `int[]` is an "instanceof" (i.e. result of the `isinst` instruction) the type
/// `uint[]` and vice versa. It is similarly so for every pair of same-sized numeric types, and
/// arrays of enums are considered to be their underlying type. We need the dag construction to
/// recognize this runtime behavior, so we pretend that matching one of them gives no information
/// on whether the other will be matched. That isn't quite correct (nothing reasonable we do
/// could be), but it comes closest to preserving the existing C#7 behavior without undesirable
/// side-effects, and permits the code-gen strategy to preserve the dynamic semantic equivalence
/// of a switch (on the one hand) and a series of if-then-else statements (on the other).
/// See, for example, https://github.com/dotnet/roslyn/issues/35661
/// </summary>
private bool? ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(
TypeSymbol expressionType,
TypeSymbol patternType,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
bool? result = Binder.ExpressionOfTypeMatchesPatternType(_conversions, expressionType, patternType, ref useSiteInfo, out Conversion conversion);
return (!conversion.Exists && isRuntimeSimilar(expressionType, patternType))
? null // runtime and compile-time test behavior differ. Pretend we don't know what happens.
: result;
static bool isRuntimeSimilar(TypeSymbol expressionType, TypeSymbol patternType)
{
while (expressionType is ArrayTypeSymbol { ElementType: var e1, IsSZArray: var sz1, Rank: var r1 } &&
patternType is ArrayTypeSymbol { ElementType: var e2, IsSZArray: var sz2, Rank: var r2 } &&
sz1 == sz2 && r1 == r2)
{
e1 = e1.EnumUnderlyingTypeOrSelf();
e2 = e2.EnumUnderlyingTypeOrSelf();
switch (e1.SpecialType, e2.SpecialType)
{
// The following support CLR behavior that is required by
// the CLI specification but violates the C# language behavior.
// See ECMA-335's definition of *array-element-compatible-with*.
case var (s1, s2) when s1 == s2:
case (SpecialType.System_SByte, SpecialType.System_Byte):
case (SpecialType.System_Byte, SpecialType.System_SByte):
case (SpecialType.System_Int16, SpecialType.System_UInt16):
case (SpecialType.System_UInt16, SpecialType.System_Int16):
case (SpecialType.System_Int32, SpecialType.System_UInt32):
case (SpecialType.System_UInt32, SpecialType.System_Int32):
case (SpecialType.System_Int64, SpecialType.System_UInt64):
case (SpecialType.System_UInt64, SpecialType.System_Int64):
case (SpecialType.System_IntPtr, SpecialType.System_UIntPtr):
case (SpecialType.System_UIntPtr, SpecialType.System_IntPtr):
// The following support behavior of the CLR that violates the CLI
// and C# specifications, but we implement them because that is the
// behavior on 32-bit runtimes.
case (SpecialType.System_Int32, SpecialType.System_IntPtr):
case (SpecialType.System_Int32, SpecialType.System_UIntPtr):
case (SpecialType.System_UInt32, SpecialType.System_IntPtr):
case (SpecialType.System_UInt32, SpecialType.System_UIntPtr):
case (SpecialType.System_IntPtr, SpecialType.System_Int32):
case (SpecialType.System_IntPtr, SpecialType.System_UInt32):
case (SpecialType.System_UIntPtr, SpecialType.System_Int32):
case (SpecialType.System_UIntPtr, SpecialType.System_UInt32):
// The following support behavior of the CLR that violates the CLI
// and C# specifications, but we implement them because that is the
// behavior on 64-bit runtimes.
case (SpecialType.System_Int64, SpecialType.System_IntPtr):
case (SpecialType.System_Int64, SpecialType.System_UIntPtr):
case (SpecialType.System_UInt64, SpecialType.System_IntPtr):
case (SpecialType.System_UInt64, SpecialType.System_UIntPtr):
case (SpecialType.System_IntPtr, SpecialType.System_Int64):
case (SpecialType.System_IntPtr, SpecialType.System_UInt64):
case (SpecialType.System_UIntPtr, SpecialType.System_Int64):
case (SpecialType.System_UIntPtr, SpecialType.System_UInt64):
return true;
default:
(expressionType, patternType) = (e1, e2);
break;
}
}
return false;
}
}
/// <summary>
/// A representation of the entire decision dag and each of its states.
/// </summary>
private sealed class DecisionDag
{
/// <summary>
/// The starting point for deciding which case matches.
/// </summary>
public readonly DagState RootNode;
public DecisionDag(DagState rootNode)
{
this.RootNode = rootNode;
}
/// <summary>
/// A successor function used to topologically sort the DagState set.
/// </summary>
private static ImmutableArray<DagState> Successor(DagState state)
{
if (state.TrueBranch != null && state.FalseBranch != null)
{
return ImmutableArray.Create(state.FalseBranch, state.TrueBranch);
}
else if (state.TrueBranch != null)
{
return ImmutableArray.Create(state.TrueBranch);
}
else if (state.FalseBranch != null)
{
return ImmutableArray.Create(state.FalseBranch);
}
else
{
return ImmutableArray<DagState>.Empty;
}
}
/// <summary>
/// Produce the states in topological order.
/// </summary>
/// <param name="result">Topologically sorted <see cref="DagState"/> nodes.</param>
/// <returns>True if the graph was acyclic.</returns>
public bool TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> result)
{
return TopologicalSort.TryIterativeSort<DagState>(SpecializedCollections.SingletonEnumerable<DagState>(this.RootNode), Successor, out result);
}
#if DEBUG
/// <summary>
/// Starting with `this` state, produce a human-readable description of the state tables.
/// This is very useful for debugging and optimizing the dag state construction.
/// </summary>
internal string Dump()
{
if (!this.TryGetTopologicallySortedReachableStates(out var allStates))
{
return "(the dag contains a cycle!)";
}
var stateIdentifierMap = PooledDictionary<DagState, int>.GetInstance();
for (int i = 0; i < allStates.Length; i++)
{
stateIdentifierMap.Add(allStates[i], i);
}
// NOTE that this numbering for temps does not work well for the invocation of Deconstruct, which produces
// multiple values. This would make them appear to be the same temp in the debug dump.
int nextTempNumber = 0;
PooledDictionary<BoundDagEvaluation, int> tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance();
int tempIdentifier(BoundDagEvaluation? e)
{
return (e == null) ? 0 : tempIdentifierMap.TryGetValue(e, out int value) ? value : tempIdentifierMap[e] = ++nextTempNumber;
}
string tempName(BoundDagTemp t)
{
return $"t{tempIdentifier(t.Source)}";
}
var resultBuilder = PooledStringBuilder.GetInstance();
var result = resultBuilder.Builder;
foreach (DagState state in allStates)
{
bool isFail = state.Cases.IsEmpty;
bool starred = isFail || state.Cases.First().PatternIsSatisfied;
result.Append($"{(starred ? "*" : "")}State " + stateIdentifierMap[state] + (isFail ? " FAIL" : ""));
var remainingValues = state.RemainingValues.Select(kvp => $"{tempName(kvp.Key)}:{kvp.Value}");
result.AppendLine($"{(remainingValues.Any() ? " REMAINING " + string.Join(" ", remainingValues) : "")}");
foreach (StateForCase cd in state.Cases)
{
result.AppendLine($" {dumpStateForCase(cd)}");
}
if (state.SelectedTest != null)
{
result.AppendLine($" Test: {dumpDagTest(state.SelectedTest)}");
}
if (state.TrueBranch != null)
{
result.AppendLine($" TrueBranch: {stateIdentifierMap[state.TrueBranch]}");
}
if (state.FalseBranch != null)
{
result.AppendLine($" FalseBranch: {stateIdentifierMap[state.FalseBranch]}");
}
}
stateIdentifierMap.Free();
tempIdentifierMap.Free();
return resultBuilder.ToStringAndFree();
string dumpStateForCase(StateForCase cd)
{
var instance = PooledStringBuilder.GetInstance();
StringBuilder builder = instance.Builder;
builder.Append($"{cd.Index}. [{cd.Syntax}] {(cd.PatternIsSatisfied ? "MATCH" : cd.RemainingTests.Dump(dumpDagTest))}");
var bindings = cd.Bindings.Select(bpb => $"{(bpb.VariableAccess is BoundLocal l ? l.LocalSymbol.Name : "<var>")}={tempName(bpb.TempContainingValue)}");
if (bindings.Any())
{
builder.Append(" BIND[");
builder.Append(string.Join("; ", bindings));
builder.Append("]");
}
if (cd.WhenClause is { })
{
builder.Append($" WHEN[{cd.WhenClause.Syntax}]");
}
return instance.ToStringAndFree();
}
string dumpDagTest(BoundDagTest d)
{
switch (d)
{
case BoundDagTypeEvaluation a:
return $"t{tempIdentifier(a)}={a.Kind}({tempName(a.Input)} as {a.Type})";
case BoundDagFieldEvaluation e:
return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Field.Name})";
case BoundDagPropertyEvaluation e:
return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Property.Name})";
case BoundDagEvaluation e:
return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)})";
case BoundDagTypeTest b:
return $"?{d.Kind}({tempName(d.Input)} is {b.Type})";
case BoundDagValueTest v:
return $"?{d.Kind}({tempName(d.Input)} == {v.Value})";
case BoundDagRelationalTest r:
var operatorName = r.Relation.Operator() switch
{
BinaryOperatorKind.LessThan => "<",
BinaryOperatorKind.LessThanOrEqual => "<=",
BinaryOperatorKind.GreaterThan => ">",
BinaryOperatorKind.GreaterThanOrEqual => ">=",
_ => "??"
};
return $"?{d.Kind}({tempName(d.Input)} {operatorName} {r.Value})";
default:
return $"?{d.Kind}({tempName(d.Input)})";
}
}
}
#endif
}
/// <summary>
/// The state at a given node of the decision finite state automaton. This is used during computation of the state
/// machine (<see cref="BoundDecisionDag"/>), and contains a representation of the meaning of the state. Because we always make
/// forward progress when a test is evaluated (the state description is monotonically smaller at each edge), the
/// graph of states is acyclic, which is why we call it a dag (directed acyclic graph).
/// </summary>
private sealed class DagState
{
/// <summary>
/// For each dag temp of a type for which we track such things (the integral types, floating-point types, and bool),
/// the possible values it can take on when control reaches this state.
/// If this dictionary is mutated after <see cref="TrueBranch"/>, <see cref="FalseBranch"/>,
/// and <see cref="Dag"/> are computed (for example to merge states), they must be cleared and recomputed,
/// as the set of possible values can affect successor states.
/// A <see cref="BoundDagTemp"/> absent from this dictionary means that all values of the type are possible.
/// </summary>
public ImmutableDictionary<BoundDagTemp, IValueSet> RemainingValues { get; private set; }
/// <summary>
/// The set of cases that may still match, and for each of them the set of tests that remain to be tested.
/// </summary>
public readonly ImmutableArray<StateForCase> Cases;
public DagState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues)
{
this.Cases = cases;
this.RemainingValues = remainingValues;
}
// If not a leaf node or a when clause, the test that will be taken at this node of the
// decision automaton.
public BoundDagTest? SelectedTest;
// We only compute the dag states for the branches after we de-dup this DagState itself.
// If all that remains is the `when` clauses, SelectedDecision is left `null` (we can
// build the leaf node easily during translation) and the FalseBranch field is populated
// with the successor on failure of the when clause (if one exists).
public DagState? TrueBranch, FalseBranch;
// After the entire graph of DagState objects is complete, we translate each into its Dag node.
public BoundDecisionDagNode? Dag;
/// <summary>
/// Decide on what test to use at this node of the decision dag. This is the principal
/// heuristic we can change to adjust the quality of the generated decision automaton.
/// See https://www.cs.tufts.edu/~nr/cs257/archive/norman-ramsey/match.pdf for some ideas.
/// </summary>
internal BoundDagTest ComputeSelectedTest()
{
return Cases[0].RemainingTests.ComputeSelectedTest();
}
internal void UpdateRemainingValues(ImmutableDictionary<BoundDagTemp, IValueSet> newRemainingValues)
{
this.RemainingValues = newRemainingValues;
this.SelectedTest = null;
this.TrueBranch = null;
this.FalseBranch = null;
}
}
/// <summary>
/// An equivalence relation between dag states used to dedup the states during dag construction.
/// After dag construction is complete we treat a DagState as using object equality as equivalent
/// states have been merged.
/// </summary>
private sealed class DagStateEquivalence : IEqualityComparer<DagState>
{
public static readonly DagStateEquivalence Instance = new DagStateEquivalence();
private DagStateEquivalence() { }
public bool Equals(DagState? x, DagState? y)
{
RoslynDebug.Assert(x is { });
RoslynDebug.Assert(y is { });
return x == y || x.Cases.SequenceEqual(y.Cases, (a, b) => a.Equals(b));
}
public int GetHashCode(DagState x)
{
return Hash.Combine(Hash.CombineValues(x.Cases), x.Cases.Length);
}
}
/// <summary>
/// As part of the description of a node of the decision automaton, we keep track of what tests
/// remain to be done for each case.
/// </summary>
private sealed class StateForCase
{
/// <summary>
/// A number that is distinct for each case and monotonically increasing from earlier to later cases.
/// Since we always keep the cases in order, this is only used to assist with debugging (e.g.
/// see DecisionDag.Dump()).
/// </summary>
public readonly int Index;
public readonly SyntaxNode Syntax;
public readonly Tests RemainingTests;
public readonly ImmutableArray<BoundPatternBinding> Bindings;
public readonly BoundExpression? WhenClause;
public readonly LabelSymbol CaseLabel;
public StateForCase(
int Index,
SyntaxNode Syntax,
Tests RemainingTests,
ImmutableArray<BoundPatternBinding> Bindings,
BoundExpression? WhenClause,
LabelSymbol CaseLabel)
{
this.Index = Index;
this.Syntax = Syntax;
this.RemainingTests = RemainingTests;
this.Bindings = Bindings;
this.WhenClause = WhenClause;
this.CaseLabel = CaseLabel;
}
/// <summary>
/// Is the pattern in a state in which it is fully matched and there is no when clause?
/// </summary>
public bool IsFullyMatched => RemainingTests is Tests.True && (WhenClause is null || WhenClause.ConstantValue == ConstantValue.True);
/// <summary>
/// Is the pattern fully matched and ready for the when clause to be evaluated (if any)?
/// </summary>
public bool PatternIsSatisfied => RemainingTests is Tests.True;
/// <summary>
/// Is the clause impossible? We do not consider a when clause with a constant false value to cause the branch to be impossible.
/// Note that we do not include the possibility that a when clause is the constant false. That is treated like any other expression.
/// </summary>
public bool IsImpossible => RemainingTests is Tests.False;
public override bool Equals(object? obj)
{
throw ExceptionUtilities.Unreachable;
}
public bool Equals(StateForCase other)
{
// We do not include Syntax, Bindings, WhereClause, or CaseLabel
// because once the Index is the same, those must be the same too.
return this == other ||
other != null &&
this.Index == other.Index &&
this.RemainingTests.Equals(other.RemainingTests);
}
public override int GetHashCode()
{
return Hash.Combine(RemainingTests.GetHashCode(), Index);
}
}
/// <summary>
/// A set of tests to be performed. This is a discriminated union; see the options (nested types) for more details.
/// </summary>
private abstract class Tests
{
private Tests() { }
/// <summary>
/// Take the set of tests and split them into two, one for when the test has succeeded, and one for when the test has failed.
/// </summary>
public abstract void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest);
public virtual BoundDagTest ComputeSelectedTest() => throw ExceptionUtilities.Unreachable;
public virtual Tests RemoveEvaluation(BoundDagEvaluation e) => this;
public abstract string Dump(Func<BoundDagTest, string> dump);
/// <summary>
/// No tests to be performed; the result is true (success).
/// </summary>
public sealed class True : Tests
{
public static readonly True Instance = new True();
public override string Dump(Func<BoundDagTest, string> dump) => "TRUE";
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
whenTrue = whenFalse = this;
}
}
/// <summary>
/// No tests to be performed; the result is false (failure).
/// </summary>
public sealed class False : Tests
{
public static readonly False Instance = new False();
public override string Dump(Func<BoundDagTest, string> dump) => "FALSE";
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
whenTrue = whenFalse = this;
}
}
/// <summary>
/// A single test to be performed, described by a <see cref="BoundDagTest"/>.
/// Note that the test might be a <see cref="BoundDagEvaluation"/>, in which case it is deemed to have
/// succeeded after being evaluated.
/// </summary>
public sealed class One : Tests
{
public readonly BoundDagTest Test;
public One(BoundDagTest test) => this.Test = test;
public void Deconstruct(out BoundDagTest Test) => Test = this.Test;
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
builder.CheckConsistentDecision(
test: test,
other: Test,
whenTrueValues: whenTrueValues,
whenFalseValues: whenFalseValues,
syntax: test.Syntax,
trueTestPermitsTrueOther: out bool trueDecisionPermitsTrueOther,
falseTestPermitsTrueOther: out bool falseDecisionPermitsTrueOther,
trueTestImpliesTrueOther: out bool trueDecisionImpliesTrueOther,
falseTestImpliesTrueOther: out bool falseDecisionImpliesTrueOther,
foundExplicitNullTest: ref foundExplicitNullTest);
whenTrue = trueDecisionImpliesTrueOther ? Tests.True.Instance : trueDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance;
whenFalse = falseDecisionImpliesTrueOther ? Tests.True.Instance : falseDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance;
}
public override BoundDagTest ComputeSelectedTest() => this.Test;
public override Tests RemoveEvaluation(BoundDagEvaluation e) => e.Equals(Test) ? Tests.True.Instance : (Tests)this;
public override string Dump(Func<BoundDagTest, string> dump) => dump(this.Test);
public override bool Equals(object? obj) => this == obj || obj is One other && this.Test.Equals(other.Test);
public override int GetHashCode() => this.Test.GetHashCode();
}
public sealed class Not : Tests
{
// Negation is pushed to the level of a single test by demorgan's laws
public readonly Tests Negated;
private Not(Tests negated) => Negated = negated;
public static Tests Create(Tests negated) => negated switch
{
Tests.True _ => Tests.False.Instance,
Tests.False _ => Tests.True.Instance,
Tests.Not n => n.Negated, // double negative
Tests.AndSequence a => new Not(a),
Tests.OrSequence a => Tests.AndSequence.Create(NegateSequenceElements(a.RemainingTests)), // use demorgan to prefer and sequences
Tests.One o => new Not(o),
_ => throw ExceptionUtilities.UnexpectedValue(negated),
};
private static ArrayBuilder<Tests> NegateSequenceElements(ImmutableArray<Tests> seq)
{
var builder = ArrayBuilder<Tests>.GetInstance(seq.Length);
foreach (var t in seq)
builder.Add(Not.Create(t));
return builder;
}
public override Tests RemoveEvaluation(BoundDagEvaluation e) => Create(Negated.RemoveEvaluation(e));
public override BoundDagTest ComputeSelectedTest() => Negated.ComputeSelectedTest();
public override string Dump(Func<BoundDagTest, string> dump) => $"Not ({Negated.Dump(dump)})";
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
Negated.Filter(builder, test, whenTrueValues, whenFalseValues, out var whenTestTrue, out var whenTestFalse, ref foundExplicitNullTest);
whenTrue = Not.Create(whenTestTrue);
whenFalse = Not.Create(whenTestFalse);
}
public override bool Equals(object? obj) => this == obj || obj is Not n && Negated.Equals(n.Negated);
public override int GetHashCode() => Hash.Combine(Negated.GetHashCode(), typeof(Not).GetHashCode());
}
public abstract class SequenceTests : Tests
{
public readonly ImmutableArray<Tests> RemainingTests;
protected SequenceTests(ImmutableArray<Tests> remainingTests)
{
Debug.Assert(remainingTests.Length > 1);
this.RemainingTests = remainingTests;
}
public abstract Tests Update(ArrayBuilder<Tests> remainingTests);
public override void Filter(
DecisionDagBuilder builder,
BoundDagTest test,
IValueSet? whenTrueValues,
IValueSet? whenFalseValues,
out Tests whenTrue,
out Tests whenFalse,
ref bool foundExplicitNullTest)
{
var trueBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length);
var falseBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length);
foreach (var other in RemainingTests)
{
other.Filter(builder, test, whenTrueValues, whenFalseValues, out Tests oneTrue, out Tests oneFalse, ref foundExplicitNullTest);
trueBuilder.Add(oneTrue);
falseBuilder.Add(oneFalse);
}
whenTrue = Update(trueBuilder);
whenFalse = Update(falseBuilder);
}
public override Tests RemoveEvaluation(BoundDagEvaluation e)
{
var builder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length);
foreach (var test in RemainingTests)
builder.Add(test.RemoveEvaluation(e));
return Update(builder);
}
public override bool Equals(object? obj) =>
this == obj || obj is SequenceTests other && this.GetType() == other.GetType() && RemainingTests.SequenceEqual(other.RemainingTests);
public override int GetHashCode()
{
int length = this.RemainingTests.Length;
int value = Hash.Combine(length, this.GetType().GetHashCode());
value = Hash.Combine(Hash.CombineValues(this.RemainingTests), value);
return value;
}
}
/// <summary>
/// A sequence of tests that must be performed, each of which must succeed.
/// The sequence is deemed to succeed if no element fails.
/// </summary>
public sealed class AndSequence : SequenceTests
{
private AndSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { }
public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests);
public static Tests Create(ArrayBuilder<Tests> remainingTests)
{
for (int i = remainingTests.Count - 1; i >= 0; i--)
{
switch (remainingTests[i])
{
case True _:
remainingTests.RemoveAt(i);
break;
case False f:
remainingTests.Free();
return f;
case AndSequence seq:
var testsToInsert = seq.RemainingTests;
remainingTests.RemoveAt(i);
for (int j = 0, n = testsToInsert.Length; j < n; j++)
remainingTests.Insert(i + j, testsToInsert[j]);
break;
}
}
var result = remainingTests.Count switch
{
0 => True.Instance,
1 => remainingTests[0],
_ => new AndSequence(remainingTests.ToImmutable()),
};
remainingTests.Free();
return result;
}
public override BoundDagTest ComputeSelectedTest()
{
// Our simple heuristic is to perform the first test of the
// first possible matched case, with two exceptions.
if (RemainingTests[0] is One { Test: { Kind: BoundKind.DagNonNullTest } planA })
{
switch (RemainingTests[1])
{
// In the specific case of a null check following by a type test, we skip the
// null check and perform the type test directly. That's because the type test
// has the side-effect of performing the null check for us.
case One { Test: { Kind: BoundKind.DagTypeTest } planB1 }:
return (planA.Input == planB1.Input) ? planB1 : planA;
// In the specific case of a null check following by a value test (which occurs for
// pattern matching a string constant pattern), we skip the
// null check and perform the value test directly. That's because the value test
// has the side-effect of performing the null check for us.
case One { Test: { Kind: BoundKind.DagValueTest } planB2 }:
return (planA.Input == planB2.Input) ? planB2 : planA;
}
}
return RemainingTests[0].ComputeSelectedTest();
}
public override string Dump(Func<BoundDagTest, string> dump)
{
return $"AND({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})";
}
}
/// <summary>
/// A sequence of tests that must be performed, any of which must succeed.
/// The sequence is deemed to succeed if some element succeeds.
/// </summary>
public sealed class OrSequence : SequenceTests
{
private OrSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { }
public override BoundDagTest ComputeSelectedTest() => this.RemainingTests[0].ComputeSelectedTest();
public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests);
public static Tests Create(ArrayBuilder<Tests> remainingTests)
{
for (int i = remainingTests.Count - 1; i >= 0; i--)
{
switch (remainingTests[i])
{
case False _:
remainingTests.RemoveAt(i);
break;
case True t:
remainingTests.Free();
return t;
case OrSequence seq:
remainingTests.RemoveAt(i);
var testsToInsert = seq.RemainingTests;
for (int j = 0, n = testsToInsert.Length; j < n; j++)
remainingTests.Insert(i + j, testsToInsert[j]);
break;
}
}
var result = remainingTests.Count switch
{
0 => False.Instance,
1 => remainingTests[0],
_ => new OrSequence(remainingTests.ToImmutable()),
};
remainingTests.Free();
return result;
}
public override string Dump(Func<BoundDagTest, string> dump)
{
return $"OR({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})";
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.DecisionDagRewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
/// <summary>
/// A common base class for lowering a decision dag.
/// </summary>
private abstract partial class DecisionDagRewriter : PatternLocalRewriter
{
/// <summary>
/// Get the builder for code in the given section of the switch.
/// For an is-pattern expression, this is a singleton.
/// </summary>
protected abstract ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section);
/// <summary>
/// The lowered decision dag. This includes all of the code to decide which pattern
/// is matched, but not the code to assign to pattern variables and evaluate when clauses.
/// </summary>
private ArrayBuilder<BoundStatement> _loweredDecisionDag;
/// <summary>
/// The label in the code for the beginning of code for each node of the dag.
/// </summary>
protected readonly PooledDictionary<BoundDecisionDagNode, LabelSymbol> _dagNodeLabels = PooledDictionary<BoundDecisionDagNode, LabelSymbol>.GetInstance();
protected DecisionDagRewriter(
SyntaxNode node,
LocalRewriter localRewriter,
bool generateInstrumentation)
: base(node, localRewriter, generateInstrumentation)
{
}
private void ComputeLabelSet(BoundDecisionDag decisionDag)
{
// Nodes with more than one predecessor are assigned a label
var hasPredecessor = PooledHashSet<BoundDecisionDagNode>.GetInstance();
foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes)
{
switch (node)
{
case BoundWhenDecisionDagNode w:
GetDagNodeLabel(node);
if (w.WhenFalse != null)
{
GetDagNodeLabel(w.WhenFalse);
}
break;
case BoundLeafDecisionDagNode d:
// Leaf can branch directly to the target
_dagNodeLabels[node] = d.Label;
break;
case BoundEvaluationDecisionDagNode e:
notePredecessor(e.Next);
break;
case BoundTestDecisionDagNode p:
notePredecessor(p.WhenTrue);
notePredecessor(p.WhenFalse);
break;
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
hasPredecessor.Free();
return;
void notePredecessor(BoundDecisionDagNode successor)
{
if (successor != null && !hasPredecessor.Add(successor))
{
GetDagNodeLabel(successor);
}
}
}
protected new void Free()
{
_dagNodeLabels.Free();
base.Free();
}
protected virtual LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag)
{
if (!_dagNodeLabels.TryGetValue(dag, out LabelSymbol label))
{
_dagNodeLabels.Add(dag, label = dag is BoundLeafDecisionDagNode d ? d.Label : _factory.GenerateLabel("dagNode"));
}
return label;
}
/// <summary>
/// A utility class that is used to scan a when clause to determine if it might assign a pattern variable
/// declared in that case, directly or indirectly. Used to determine if we can skip the allocation of
/// pattern-matching temporary variables and use user-declared pattern variables instead, because we can
/// conclude that they are not mutated by a when clause while the pattern-matching automaton is running.
/// </summary>
protected sealed class WhenClauseMightAssignPatternVariableWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private bool _mightAssignSomething;
public bool MightAssignSomething(BoundExpression expr)
{
if (expr == null)
return false;
this._mightAssignSomething = false;
this.Visit(expr);
return this._mightAssignSomething;
}
public override BoundNode Visit(BoundNode node)
{
// A constant expression cannot mutate anything
if (node is BoundExpression { ConstantValue: { } })
return null;
// Stop visiting once we determine something might get assigned
return this._mightAssignSomething ? null : base.Visit(node);
}
public override BoundNode VisitCall(BoundCall node)
{
bool mightMutate =
// might be a call to a local function that assigns something
node.Method.MethodKind == MethodKind.LocalFunction ||
// or perhaps we are passing a variable by ref and mutating it that way, e.g. `int.Parse(..., out x)`
!node.ArgumentRefKindsOpt.IsDefault ||
// or perhaps we are calling a mutating method of a value type
MethodMayMutateReceiver(node.ReceiverOpt, node.Method);
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitCall(node);
return null;
}
private static bool MethodMayMutateReceiver(BoundExpression receiver, MethodSymbol method)
{
return
method != null &&
!method.IsStatic &&
!method.IsEffectivelyReadOnly &&
receiver.Type?.IsReferenceType == false &&
// methods of primitive types do not mutate their receiver
!method.ContainingType.SpecialType.IsPrimitiveRecursiveStruct();
}
public override BoundNode VisitPropertyAccess(BoundPropertyAccess node)
{
bool mightMutate =
// We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller
MethodMayMutateReceiver(node.ReceiverOpt, node.PropertySymbol.GetMethod);
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitPropertyAccess(node);
return null;
}
public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitConversion(BoundConversion node)
{
visitConversion(node.Conversion);
if (!_mightAssignSomething)
base.VisitConversion(node);
return null;
void visitConversion(Conversion conversion)
{
switch (conversion.Kind)
{
case ConversionKind.MethodGroup:
if (conversion.Method.MethodKind == MethodKind.LocalFunction)
{
_mightAssignSomething = true;
}
break;
default:
if (!conversion.UnderlyingConversions.IsDefault)
{
foreach (var underlying in conversion.UnderlyingConversions)
{
visitConversion(underlying);
if (_mightAssignSomething)
return;
}
}
break;
}
}
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
bool mightMutate =
node.MethodOpt?.MethodKind == MethodKind.LocalFunction;
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitDelegateCreationExpression(node);
return null;
}
public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitIncrementOperator(BoundIncrementOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node)
{
// perhaps we are passing a variable by ref and mutating it that way
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitDynamicInvocation(node);
return null;
}
public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node)
{
// perhaps we are passing a variable by ref and mutating it that way
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitObjectCreationExpression(node);
return null;
}
public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node)
{
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitDynamicObjectCreationExpression(node);
return null;
}
public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node)
{
// Although ref indexers are not declarable in C#, they may be usable
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitObjectInitializerMember(node);
return null;
}
public override BoundNode VisitIndexerAccess(BoundIndexerAccess node)
{
bool mightMutate =
!node.ArgumentRefKindsOpt.IsDefault ||
// We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller
MethodMayMutateReceiver(node.ReceiverOpt, node.Indexer.GetMethod);
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitIndexerAccess(node);
return null;
}
public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node)
{
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitDynamicIndexerAccess(node);
return null;
}
}
protected BoundDecisionDag ShareTempsIfPossibleAndEvaluateInput(
BoundDecisionDag decisionDag,
BoundExpression loweredSwitchGoverningExpression,
ArrayBuilder<BoundStatement> result,
out BoundExpression savedInputExpression)
{
// Note that a when-clause can contain an assignment to a
// pattern variable declared in a different when-clause (e.g. in the same section, or
// in a different section via the use of a local function), so we need to analyze all
// of the when clauses to see if they are all simple enough to conclude that they do
// not mutate pattern variables.
var mightAssignWalker = new WhenClauseMightAssignPatternVariableWalker();
bool canShareTemps =
!decisionDag.TopologicallySortedNodes
.Any(node => node is BoundWhenDecisionDagNode w && mightAssignWalker.MightAssignSomething(w.WhenExpression));
if (canShareTemps)
{
decisionDag = ShareTempsAndEvaluateInput(loweredSwitchGoverningExpression, decisionDag, expr => result.Add(_factory.ExpressionStatement(expr)), out savedInputExpression);
}
else
{
// assign the input expression to its temp.
BoundExpression inputTemp = _tempAllocator.GetTemp(BoundDagTemp.ForOriginalInput(loweredSwitchGoverningExpression));
Debug.Assert(inputTemp != loweredSwitchGoverningExpression);
result.Add(_factory.Assignment(inputTemp, loweredSwitchGoverningExpression));
savedInputExpression = inputTemp;
}
return decisionDag;
}
protected ImmutableArray<BoundStatement> LowerDecisionDagCore(BoundDecisionDag decisionDag)
{
_loweredDecisionDag = ArrayBuilder<BoundStatement>.GetInstance();
ComputeLabelSet(decisionDag);
ImmutableArray<BoundDecisionDagNode> sortedNodes = decisionDag.TopologicallySortedNodes;
var firstNode = sortedNodes[0];
switch (firstNode)
{
case BoundWhenDecisionDagNode _:
case BoundLeafDecisionDagNode _:
// If the first node is a leaf or when clause rather than the code for the
// lowered decision dag, jump there to start.
_loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(firstNode)));
break;
}
// Code for each when clause goes in the separate code section for its switch section.
foreach (BoundDecisionDagNode node in sortedNodes)
{
if (node is BoundWhenDecisionDagNode w)
{
LowerWhenClause(w);
}
}
ImmutableArray<BoundDecisionDagNode> nodesToLower = sortedNodes.WhereAsArray(n => n.Kind != BoundKind.WhenDecisionDagNode && n.Kind != BoundKind.LeafDecisionDagNode);
var loweredNodes = PooledHashSet<BoundDecisionDagNode>.GetInstance();
for (int i = 0, length = nodesToLower.Length; i < length; i++)
{
BoundDecisionDagNode node = nodesToLower[i];
// A node may have been lowered as part of a switch dispatch, but if it had a label, we'll need to lower it individually as well
bool alreadyLowered = loweredNodes.Contains(node);
if (alreadyLowered && !_dagNodeLabels.TryGetValue(node, out _))
{
continue;
}
if (_dagNodeLabels.TryGetValue(node, out LabelSymbol label))
{
_loweredDecisionDag.Add(_factory.Label(label));
}
// If we can generate an IL switch instruction, do so
if (!alreadyLowered && GenerateSwitchDispatch(node, loweredNodes))
{
continue;
}
// If we can generate a type test and cast more efficiently as an `is` followed by a null check, do so
if (GenerateTypeTestAndCast(node, loweredNodes, nodesToLower, i))
{
continue;
}
// We pass the node that will follow so we can permit a test to fall through if appropriate
BoundDecisionDagNode nextNode = ((i + 1) < length) ? nodesToLower[i + 1] : null;
if (nextNode != null && loweredNodes.Contains(nextNode))
{
nextNode = null;
}
LowerDecisionDagNode(node, nextNode);
}
loweredNodes.Free();
var result = _loweredDecisionDag.ToImmutableAndFree();
_loweredDecisionDag = null;
return result;
}
/// <summary>
/// If we have a type test followed by a cast to that type, and the types are reference types,
/// then we can replace the pair of them by a conversion using `as` and a null check.
/// </summary>
/// <returns>true if we generated code for the test</returns>
private bool GenerateTypeTestAndCast(
BoundDecisionDagNode node,
HashSet<BoundDecisionDagNode> loweredNodes,
ImmutableArray<BoundDecisionDagNode> nodesToLower,
int indexOfNode)
{
Debug.Assert(node == nodesToLower[indexOfNode]);
if (node is BoundTestDecisionDagNode testNode &&
testNode.WhenTrue is BoundEvaluationDecisionDagNode evaluationNode &&
TryLowerTypeTestAndCast(testNode.Test, evaluationNode.Evaluation, out BoundExpression sideEffect, out BoundExpression test)
)
{
var whenTrue = evaluationNode.Next;
var whenFalse = testNode.WhenFalse;
bool canEliminateEvaluationNode = !this._dagNodeLabels.ContainsKey(evaluationNode);
if (canEliminateEvaluationNode)
loweredNodes.Add(evaluationNode);
var nextNode =
(indexOfNode + 2 < nodesToLower.Length) &&
canEliminateEvaluationNode &&
nodesToLower[indexOfNode + 1] == evaluationNode &&
!loweredNodes.Contains(nodesToLower[indexOfNode + 2]) ? nodesToLower[indexOfNode + 2] : null;
_loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect));
GenerateTest(test, whenTrue, whenFalse, nextNode);
return true;
}
return false;
}
private void GenerateTest(BoundExpression test, BoundDecisionDagNode whenTrue, BoundDecisionDagNode whenFalse, BoundDecisionDagNode nextNode)
{
// Because we have already "optimized" away tests for a constant switch expression, the test should be nontrivial.
_factory.Syntax = test.Syntax;
Debug.Assert(test != null);
if (nextNode == whenFalse)
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true));
// fall through to false path
}
else if (nextNode == whenTrue)
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenFalse), jumpIfTrue: false));
// fall through to true path
}
else
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true));
_loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(whenFalse)));
}
}
/// <summary>
/// Generate a switch dispatch for a contiguous sequence of dag nodes if applicable.
/// Returns true if it was applicable.
/// </summary>
private bool GenerateSwitchDispatch(BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes)
{
Debug.Assert(!loweredNodes.Contains(node));
if (!canGenerateSwitchDispatch(node))
return false;
var input = ((BoundTestDecisionDagNode)node).Test.Input;
ValueDispatchNode n = GatherValueDispatchNodes(node, loweredNodes, input);
LowerValueDispatchNode(n, _tempAllocator.GetTemp(input));
return true;
bool canGenerateSwitchDispatch(BoundDecisionDagNode node)
{
switch (node)
{
// These are the forms worth optimizing.
case BoundTestDecisionDagNode { WhenFalse: BoundTestDecisionDagNode test2 } test1:
return canDispatch(test1, test2);
case BoundTestDecisionDagNode { WhenTrue: BoundTestDecisionDagNode test2 } test1:
return canDispatch(test1, test2);
default:
// Other cases are just as well done with a single test.
return false;
}
bool canDispatch(BoundTestDecisionDagNode test1, BoundTestDecisionDagNode test2)
{
if (this._dagNodeLabels.ContainsKey(test2))
return false;
Debug.Assert(!loweredNodes.Contains(test2));
var t1 = test1.Test;
var t2 = test2.Test;
if (!(t1 is BoundDagValueTest || t1 is BoundDagRelationalTest))
return false;
if (!(t2 is BoundDagValueTest || t2 is BoundDagRelationalTest))
return false;
if (!t1.Input.Equals(t2.Input))
return false;
return true;
}
}
}
private ValueDispatchNode GatherValueDispatchNodes(
BoundDecisionDagNode node,
HashSet<BoundDecisionDagNode> loweredNodes,
BoundDagTemp input)
{
IValueSetFactory fac = ValueSetFactory.ForType(input.Type);
return GatherValueDispatchNodes(node, loweredNodes, input, fac);
}
private ValueDispatchNode GatherValueDispatchNodes(
BoundDecisionDagNode node,
HashSet<BoundDecisionDagNode> loweredNodes,
BoundDagTemp input,
IValueSetFactory fac)
{
if (loweredNodes.Contains(node))
{
bool foundLabel = this._dagNodeLabels.TryGetValue(node, out LabelSymbol label);
Debug.Assert(foundLabel);
return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label);
}
if (!(node is BoundTestDecisionDagNode testNode && testNode.Test.Input.Equals(input)))
{
var label = GetDagNodeLabel(node);
return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label);
}
switch (testNode.Test)
{
case BoundDagRelationalTest relational:
{
loweredNodes.Add(testNode);
var whenTrue = GatherValueDispatchNodes(testNode.WhenTrue, loweredNodes, input, fac);
var whenFalse = GatherValueDispatchNodes(testNode.WhenFalse, loweredNodes, input, fac);
return ValueDispatchNode.RelationalDispatch.CreateBalanced(testNode.Syntax, relational.Value, relational.OperatorKind, whenTrue: whenTrue, whenFalse: whenFalse);
}
case BoundDagValueTest value:
{
// Gather up the (value, label) pairs, starting with the first one
loweredNodes.Add(testNode);
var cases = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance();
cases.Add((value: value.Value, label: GetDagNodeLabel(testNode.WhenTrue)));
BoundTestDecisionDagNode previous = testNode;
while (previous.WhenFalse is BoundTestDecisionDagNode p &&
p.Test is BoundDagValueTest vd &&
vd.Input.Equals(input) &&
!this._dagNodeLabels.ContainsKey(p) &&
!loweredNodes.Contains(p))
{
cases.Add((value: vd.Value, label: GetDagNodeLabel(p.WhenTrue)));
loweredNodes.Add(p);
previous = p;
}
var otherwise = GatherValueDispatchNodes(previous.WhenFalse, loweredNodes, input, fac);
return PushEqualityTestsIntoTree(value.Syntax, otherwise, cases.ToImmutableAndFree(), fac);
}
default:
{
var label = GetDagNodeLabel(node);
return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label);
}
}
}
/// <summary>
/// Push the set of equality tests down to the level of the leaves in the value dispatch tree.
/// </summary>
private ValueDispatchNode PushEqualityTestsIntoTree(
SyntaxNode syntax,
ValueDispatchNode otherwise,
ImmutableArray<(ConstantValue value, LabelSymbol label)> cases,
IValueSetFactory fac)
{
if (cases.IsEmpty)
return otherwise;
switch (otherwise)
{
case ValueDispatchNode.LeafDispatchNode leaf:
return new ValueDispatchNode.SwitchDispatch(syntax, cases, leaf.Label);
case ValueDispatchNode.SwitchDispatch sd:
return new ValueDispatchNode.SwitchDispatch(sd.Syntax, sd.Cases.Concat(cases), sd.Otherwise);
case ValueDispatchNode.RelationalDispatch { Operator: var op, Value: var value, WhenTrue: var whenTrue, WhenFalse: var whenFalse } rel:
var (whenTrueCases, whenFalseCases) = splitCases(cases, op, value);
Debug.Assert(cases.Length == whenTrueCases.Length + whenFalseCases.Length);
whenTrue = PushEqualityTestsIntoTree(syntax, whenTrue, whenTrueCases, fac);
whenFalse = PushEqualityTestsIntoTree(syntax, whenFalse, whenFalseCases, fac);
var result = rel.WithTrueAndFalseChildren(whenTrue: whenTrue, whenFalse: whenFalse);
return result;
default:
throw ExceptionUtilities.UnexpectedValue(otherwise);
}
(ImmutableArray<(ConstantValue value, LabelSymbol label)> whenTrueCases, ImmutableArray<(ConstantValue value, LabelSymbol label)> whenFalseCases)
splitCases(ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, BinaryOperatorKind op, ConstantValue value)
{
var whenTrueBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance();
var whenFalseBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance();
op = op.Operator();
foreach (var pair in cases)
{
(fac.Related(op, pair.value, value) ? whenTrueBuilder : whenFalseBuilder).Add(pair);
}
return (whenTrueBuilder.ToImmutableAndFree(), whenFalseBuilder.ToImmutableAndFree());
}
}
private void LowerValueDispatchNode(ValueDispatchNode n, BoundExpression input)
{
switch (n)
{
case ValueDispatchNode.LeafDispatchNode leaf:
_loweredDecisionDag.Add(_factory.Goto(leaf.Label));
return;
case ValueDispatchNode.SwitchDispatch eq:
LowerSwitchDispatchNode(eq, input);
return;
case ValueDispatchNode.RelationalDispatch rel:
LowerRelationalDispatchNode(rel, input);
return;
default:
throw ExceptionUtilities.UnexpectedValue(n);
}
}
private void LowerRelationalDispatchNode(ValueDispatchNode.RelationalDispatch rel, BoundExpression input)
{
var test = MakeRelationalTest(rel.Syntax, input, rel.Operator, rel.Value);
if (rel.WhenTrue is ValueDispatchNode.LeafDispatchNode whenTrue)
{
LabelSymbol trueLabel = whenTrue.Label;
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, trueLabel, jumpIfTrue: true));
LowerValueDispatchNode(rel.WhenFalse, input);
}
else if (rel.WhenFalse is ValueDispatchNode.LeafDispatchNode whenFalse)
{
LabelSymbol falseLabel = whenFalse.Label;
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false));
LowerValueDispatchNode(rel.WhenTrue, input);
}
else
{
LabelSymbol falseLabel = _factory.GenerateLabel("relationalDispatch");
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false));
LowerValueDispatchNode(rel.WhenTrue, input);
_loweredDecisionDag.Add(_factory.Label(falseLabel));
LowerValueDispatchNode(rel.WhenFalse, input);
}
}
/// <summary>
/// A comparer for sorting cases containing values of type float, double, or decimal.
/// </summary>
private sealed class CasesComparer : IComparer<(ConstantValue value, LabelSymbol label)>
{
private readonly IValueSetFactory _fac;
public CasesComparer(TypeSymbol type)
{
_fac = ValueSetFactory.ForType(type);
Debug.Assert(_fac is { });
}
int IComparer<(ConstantValue value, LabelSymbol label)>.Compare((ConstantValue value, LabelSymbol label) left, (ConstantValue value, LabelSymbol label) right)
{
var x = left.value;
var y = right.value;
Debug.Assert(x.Discriminator switch
{
ConstantValueTypeDiscriminator.Decimal => true,
ConstantValueTypeDiscriminator.Single => true,
ConstantValueTypeDiscriminator.Double => true,
ConstantValueTypeDiscriminator.NInt => true,
ConstantValueTypeDiscriminator.NUInt => true,
_ => false
});
Debug.Assert(y.Discriminator == x.Discriminator);
// Sort NaN values into the "highest" position so they fall naturally into the last bucket
// when partitioned using less-than.
return
isNaN(x) ? 1 :
isNaN(y) ? -1 :
_fac.Related(BinaryOperatorKind.LessThanOrEqual, x, y) ?
(_fac.Related(BinaryOperatorKind.LessThanOrEqual, y, x) ? 0 : -1) :
1;
static bool isNaN(ConstantValue value) =>
(value.Discriminator == ConstantValueTypeDiscriminator.Single || value.Discriminator == ConstantValueTypeDiscriminator.Double) &&
double.IsNaN(value.DoubleValue);
}
}
private void LowerSwitchDispatchNode(ValueDispatchNode.SwitchDispatch node, BoundExpression input)
{
LabelSymbol defaultLabel = node.Otherwise;
if (input.Type.IsValidV6SwitchGoverningType())
{
// If we are emitting a hash table based string switch,
// we need to generate a helper method for computing
// string hash value in <PrivateImplementationDetails> class.
MethodSymbol stringEquality = null;
if (input.Type.SpecialType == SpecialType.System_String)
{
EnsureStringHashFunction(node.Cases.Length, node.Syntax);
stringEquality = _localRewriter.UnsafeGetSpecialTypeMethod(node.Syntax, SpecialMember.System_String__op_Equality);
}
var dispatch = new BoundSwitchDispatch(node.Syntax, input, node.Cases, defaultLabel, stringEquality);
_loweredDecisionDag.Add(dispatch);
}
else if (input.Type.IsNativeIntegerType)
{
// Native types need to be dispatched using a larger underlying type so that any
// possible high bits are not truncated.
ImmutableArray<(ConstantValue value, LabelSymbol label)> cases;
switch (input.Type.SpecialType)
{
case SpecialType.System_IntPtr:
{
input = _factory.Convert(_factory.SpecialType(SpecialType.System_Int64), input);
cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((long)p.value.Int32Value), p.label));
break;
}
case SpecialType.System_UIntPtr:
{
input = _factory.Convert(_factory.SpecialType(SpecialType.System_UInt64), input);
cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((ulong)p.value.UInt32Value), p.label));
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(input.Type);
}
var dispatch = new BoundSwitchDispatch(node.Syntax, input, cases, defaultLabel, equalityMethod: null);
_loweredDecisionDag.Add(dispatch);
}
else
{
// The emitter does not know how to produce a "switch" instruction for float, double, or decimal
// (in part because there is no such instruction) so we fake it here by generating a decision tree.
var lessThanOrEqualOperator = input.Type.SpecialType switch
{
SpecialType.System_Single => BinaryOperatorKind.FloatLessThanOrEqual,
SpecialType.System_Double => BinaryOperatorKind.DoubleLessThanOrEqual,
SpecialType.System_Decimal => BinaryOperatorKind.DecimalLessThanOrEqual,
_ => throw ExceptionUtilities.UnexpectedValue(input.Type.SpecialType)
};
var cases = node.Cases.Sort(new CasesComparer(input.Type));
lowerFloatDispatch(0, cases.Length);
void lowerFloatDispatch(int firstIndex, int count)
{
if (count <= 3)
{
for (int i = firstIndex, limit = firstIndex + count; i < limit; i++)
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(MakeValueTest(node.Syntax, input, cases[i].value), cases[i].label, jumpIfTrue: true));
}
_loweredDecisionDag.Add(_factory.Goto(defaultLabel));
}
else
{
int half = count / 2;
var gt = _factory.GenerateLabel("greaterThanMidpoint");
_loweredDecisionDag.Add(_factory.ConditionalGoto(MakeRelationalTest(node.Syntax, input, lessThanOrEqualOperator, cases[firstIndex + half - 1].value), gt, jumpIfTrue: false));
lowerFloatDispatch(firstIndex, half);
_loweredDecisionDag.Add(_factory.Label(gt));
lowerFloatDispatch(firstIndex + half, count - half);
}
}
}
}
/// <summary>
/// Checks whether we are generating a hash table based string switch and
/// we need to generate a new helper method for computing string hash value.
/// Creates the method if needed.
/// </summary>
private void EnsureStringHashFunction(int labelsCount, SyntaxNode syntaxNode)
{
var module = _localRewriter.EmitModule;
if (module == null)
{
// we're not generating code, so we don't need the hash function
return;
}
// For string switch statements, we need to determine if we are generating a hash
// table based jump table or a non hash jump table, i.e. linear string comparisons
// with each case label. We use the Dev10 Heuristic to determine this
// (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details).
if (!CodeAnalysis.CodeGen.SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(module, labelsCount))
{
return;
}
// If we are generating a hash table based jump table, we use a simple customizable
// hash function to hash the string constants corresponding to the case labels.
// See SwitchStringJumpTableEmitter.ComputeStringHash().
// We need to emit this function to compute the hash value into the compiler generated
// <PrivateImplementationDetails> class.
// If we have at least one string switch statement in a module that needs a
// hash table based jump table, we generate a single public string hash synthesized method
// that is shared across the module.
// If we have already generated the helper, possibly for another switch
// or on another thread, we don't need to regenerate it.
var privateImplClass = module.GetPrivateImplClass(syntaxNode, _localRewriter._diagnostics.DiagnosticBag);
if (privateImplClass.GetMethod(CodeAnalysis.CodeGen.PrivateImplementationDetails.SynthesizedStringHashFunctionName) != null)
{
return;
}
// cannot emit hash method if have no access to Chars.
var charsMember = _localRewriter._compilation.GetSpecialTypeMember(SpecialMember.System_String__Chars);
if ((object)charsMember == null || charsMember.HasUseSiteError)
{
return;
}
TypeSymbol returnType = _factory.SpecialType(SpecialType.System_UInt32);
TypeSymbol paramType = _factory.SpecialType(SpecialType.System_String);
var method = new SynthesizedStringSwitchHashMethod(module.SourceModule, privateImplClass, returnType, paramType);
privateImplClass.TryAddSynthesizedMethod(method.GetCciAdapter());
}
private void LowerWhenClause(BoundWhenDecisionDagNode whenClause)
{
// This node is used even when there is no when clause, to record bindings. In the case that there
// is no when clause, whenClause.WhenExpression and whenClause.WhenFalse are null, and the syntax for this
// node is the case clause.
// We need to assign the pattern variables in the code where they are in scope, so we produce a branch
// to the section where they are in scope and evaluate the when clause there.
var whenTrue = (BoundLeafDecisionDagNode)whenClause.WhenTrue;
LabelSymbol labelToSectionScope = GetDagNodeLabel(whenClause);
ArrayBuilder<BoundStatement> sectionBuilder = BuilderForSection(whenClause.Syntax);
sectionBuilder.Add(_factory.Label(labelToSectionScope));
foreach (BoundPatternBinding binding in whenClause.Bindings)
{
BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess);
// Since a switch does not add variables to the enclosing scope, the pattern variables
// are locals even in a script and rewriting them should have no effect.
Debug.Assert(left.Kind == BoundKind.Local && left == binding.VariableAccess);
BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue);
if (left != right)
{
sectionBuilder.Add(_factory.Assignment(left, right));
}
}
var whenFalse = whenClause.WhenFalse;
var trueLabel = GetDagNodeLabel(whenTrue);
if (whenClause.WhenExpression != null && whenClause.WhenExpression.ConstantValue != ConstantValue.True)
{
_factory.Syntax = whenClause.Syntax;
BoundStatement conditionalGoto = _factory.ConditionalGoto(_localRewriter.VisitExpression(whenClause.WhenExpression), trueLabel, jumpIfTrue: true);
// Only add instrumentation (such as a sequence point) if the node is not compiler-generated.
if (GenerateInstrumentation && !whenClause.WhenExpression.WasCompilerGenerated)
{
conditionalGoto = _localRewriter._instrumenter.InstrumentSwitchWhenClauseConditionalGotoBody(whenClause.WhenExpression, conditionalGoto);
}
sectionBuilder.Add(conditionalGoto);
Debug.Assert(whenFalse != null);
// We hide the jump back into the decision dag, as it is not logically part of the when clause
BoundStatement jump = _factory.Goto(GetDagNodeLabel(whenFalse));
sectionBuilder.Add(GenerateInstrumentation ? _factory.HiddenSequencePoint(jump) : jump);
}
else
{
Debug.Assert(whenFalse == null);
sectionBuilder.Add(_factory.Goto(trueLabel));
}
}
/// <summary>
/// Translate the decision dag for node, given that it will be followed by the translation for nextNode.
/// </summary>
private void LowerDecisionDagNode(BoundDecisionDagNode node, BoundDecisionDagNode nextNode)
{
_factory.Syntax = node.Syntax;
switch (node)
{
case BoundEvaluationDecisionDagNode evaluationNode:
{
BoundExpression sideEffect = LowerEvaluation(evaluationNode.Evaluation);
Debug.Assert(sideEffect != null);
_loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect));
// We add a hidden sequence point after the evaluation's side-effect, which may be a call out
// to user code such as `Deconstruct` or a property get, to permit edit-and-continue to
// synchronize on changes.
if (GenerateInstrumentation)
_loweredDecisionDag.Add(_factory.HiddenSequencePoint());
if (nextNode != evaluationNode.Next)
{
// We only need a goto if we would not otherwise fall through to the desired state
_loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(evaluationNode.Next)));
}
}
break;
case BoundTestDecisionDagNode testNode:
{
BoundExpression test = base.LowerTest(testNode.Test);
GenerateTest(test, testNode.WhenTrue, testNode.WhenFalse, nextNode);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.SyntheticBoundNodeFactory;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
/// <summary>
/// A common base class for lowering a decision dag.
/// </summary>
private abstract partial class DecisionDagRewriter : PatternLocalRewriter
{
/// <summary>
/// Get the builder for code in the given section of the switch.
/// For an is-pattern expression, this is a singleton.
/// </summary>
protected abstract ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section);
/// <summary>
/// The lowered decision dag. This includes all of the code to decide which pattern
/// is matched, but not the code to assign to pattern variables and evaluate when clauses.
/// </summary>
private ArrayBuilder<BoundStatement> _loweredDecisionDag;
/// <summary>
/// The label in the code for the beginning of code for each node of the dag.
/// </summary>
protected readonly PooledDictionary<BoundDecisionDagNode, LabelSymbol> _dagNodeLabels = PooledDictionary<BoundDecisionDagNode, LabelSymbol>.GetInstance();
#nullable enable
// When different branches of the DAG share `when` expressions, the
// shared expression will be lowered as a shared section and the `when` nodes that need
// to will jump there. After the expression is evaluated, we need to jump to different
// labels depending on the `when` node we came from. To achieve that, each `when` node
// gets an identifier and sets a local before jumping into the shared `when` expression.
private int _nextWhenNodeIdentifier = 0;
internal LocalSymbol? _whenNodeIdentifierLocal;
#nullable disable
protected DecisionDagRewriter(
SyntaxNode node,
LocalRewriter localRewriter,
bool generateInstrumentation)
: base(node, localRewriter, generateInstrumentation)
{
}
private void ComputeLabelSet(BoundDecisionDag decisionDag)
{
// Nodes with more than one predecessor are assigned a label
var hasPredecessor = PooledHashSet<BoundDecisionDagNode>.GetInstance();
foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes)
{
switch (node)
{
case BoundWhenDecisionDagNode w:
GetDagNodeLabel(node);
if (w.WhenFalse != null)
{
GetDagNodeLabel(w.WhenFalse);
}
break;
case BoundLeafDecisionDagNode d:
// Leaf can branch directly to the target
_dagNodeLabels[node] = d.Label;
break;
case BoundEvaluationDecisionDagNode e:
notePredecessor(e.Next);
break;
case BoundTestDecisionDagNode p:
notePredecessor(p.WhenTrue);
notePredecessor(p.WhenFalse);
break;
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
hasPredecessor.Free();
return;
void notePredecessor(BoundDecisionDagNode successor)
{
if (successor != null && !hasPredecessor.Add(successor))
{
GetDagNodeLabel(successor);
}
}
}
protected new void Free()
{
_dagNodeLabels.Free();
base.Free();
}
protected virtual LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag)
{
if (!_dagNodeLabels.TryGetValue(dag, out LabelSymbol label))
{
_dagNodeLabels.Add(dag, label = dag is BoundLeafDecisionDagNode d ? d.Label : _factory.GenerateLabel("dagNode"));
}
return label;
}
/// <summary>
/// A utility class that is used to scan a when clause to determine if it might assign a pattern variable
/// declared in that case, directly or indirectly. Used to determine if we can skip the allocation of
/// pattern-matching temporary variables and use user-declared pattern variables instead, because we can
/// conclude that they are not mutated by a when clause while the pattern-matching automaton is running.
/// </summary>
protected sealed class WhenClauseMightAssignPatternVariableWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private bool _mightAssignSomething;
public bool MightAssignSomething(BoundExpression expr)
{
if (expr == null)
return false;
this._mightAssignSomething = false;
this.Visit(expr);
return this._mightAssignSomething;
}
public override BoundNode Visit(BoundNode node)
{
// A constant expression cannot mutate anything
if (node is BoundExpression { ConstantValue: { } })
return null;
// Stop visiting once we determine something might get assigned
return this._mightAssignSomething ? null : base.Visit(node);
}
public override BoundNode VisitCall(BoundCall node)
{
bool mightMutate =
// might be a call to a local function that assigns something
node.Method.MethodKind == MethodKind.LocalFunction ||
// or perhaps we are passing a variable by ref and mutating it that way, e.g. `int.Parse(..., out x)`
!node.ArgumentRefKindsOpt.IsDefault ||
// or perhaps we are calling a mutating method of a value type
MethodMayMutateReceiver(node.ReceiverOpt, node.Method);
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitCall(node);
return null;
}
private static bool MethodMayMutateReceiver(BoundExpression receiver, MethodSymbol method)
{
return
method != null &&
!method.IsStatic &&
!method.IsEffectivelyReadOnly &&
receiver.Type?.IsReferenceType == false &&
// methods of primitive types do not mutate their receiver
!method.ContainingType.SpecialType.IsPrimitiveRecursiveStruct();
}
public override BoundNode VisitPropertyAccess(BoundPropertyAccess node)
{
bool mightMutate =
// We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller
MethodMayMutateReceiver(node.ReceiverOpt, node.PropertySymbol.GetMethod);
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitPropertyAccess(node);
return null;
}
public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitConversion(BoundConversion node)
{
visitConversion(node.Conversion);
if (!_mightAssignSomething)
base.VisitConversion(node);
return null;
void visitConversion(Conversion conversion)
{
switch (conversion.Kind)
{
case ConversionKind.MethodGroup:
if (conversion.Method.MethodKind == MethodKind.LocalFunction)
{
_mightAssignSomething = true;
}
break;
default:
if (!conversion.UnderlyingConversions.IsDefault)
{
foreach (var underlying in conversion.UnderlyingConversions)
{
visitConversion(underlying);
if (_mightAssignSomething)
return;
}
}
break;
}
}
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
bool mightMutate =
node.MethodOpt?.MethodKind == MethodKind.LocalFunction;
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitDelegateCreationExpression(node);
return null;
}
public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitIncrementOperator(BoundIncrementOperator node)
{
_mightAssignSomething = true;
return null;
}
public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node)
{
// perhaps we are passing a variable by ref and mutating it that way
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitDynamicInvocation(node);
return null;
}
public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node)
{
// perhaps we are passing a variable by ref and mutating it that way
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitObjectCreationExpression(node);
return null;
}
public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node)
{
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitDynamicObjectCreationExpression(node);
return null;
}
public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node)
{
// Although ref indexers are not declarable in C#, they may be usable
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitObjectInitializerMember(node);
return null;
}
public override BoundNode VisitIndexerAccess(BoundIndexerAccess node)
{
bool mightMutate =
!node.ArgumentRefKindsOpt.IsDefault ||
// We only need to check the get accessor because an assignment would cause _mightAssignSomething to be set to true in the caller
MethodMayMutateReceiver(node.ReceiverOpt, node.Indexer.GetMethod);
if (mightMutate)
_mightAssignSomething = true;
else
base.VisitIndexerAccess(node);
return null;
}
public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node)
{
if (!node.ArgumentRefKindsOpt.IsDefault)
_mightAssignSomething = true;
else
base.VisitDynamicIndexerAccess(node);
return null;
}
}
protected BoundDecisionDag ShareTempsIfPossibleAndEvaluateInput(
BoundDecisionDag decisionDag,
BoundExpression loweredSwitchGoverningExpression,
ArrayBuilder<BoundStatement> result,
out BoundExpression savedInputExpression)
{
// Note that a when-clause can contain an assignment to a
// pattern variable declared in a different when-clause (e.g. in the same section, or
// in a different section via the use of a local function), so we need to analyze all
// of the when clauses to see if they are all simple enough to conclude that they do
// not mutate pattern variables.
var mightAssignWalker = new WhenClauseMightAssignPatternVariableWalker();
bool canShareTemps =
!decisionDag.TopologicallySortedNodes
.Any(node => node is BoundWhenDecisionDagNode w && mightAssignWalker.MightAssignSomething(w.WhenExpression));
if (canShareTemps)
{
decisionDag = ShareTempsAndEvaluateInput(loweredSwitchGoverningExpression, decisionDag, expr => result.Add(_factory.ExpressionStatement(expr)), out savedInputExpression);
}
else
{
// assign the input expression to its temp.
BoundExpression inputTemp = _tempAllocator.GetTemp(BoundDagTemp.ForOriginalInput(loweredSwitchGoverningExpression));
Debug.Assert(inputTemp != loweredSwitchGoverningExpression);
result.Add(_factory.Assignment(inputTemp, loweredSwitchGoverningExpression));
savedInputExpression = inputTemp;
}
return decisionDag;
}
protected ImmutableArray<BoundStatement> LowerDecisionDagCore(BoundDecisionDag decisionDag)
{
_loweredDecisionDag = ArrayBuilder<BoundStatement>.GetInstance();
ComputeLabelSet(decisionDag);
ImmutableArray<BoundDecisionDagNode> sortedNodes = decisionDag.TopologicallySortedNodes;
var firstNode = sortedNodes[0];
switch (firstNode)
{
case BoundWhenDecisionDagNode _:
case BoundLeafDecisionDagNode _:
// If the first node is a leaf or when clause rather than the code for the
// lowered decision dag, jump there to start.
_loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(firstNode)));
break;
}
// Code for each when clause goes in the separate code section for its switch section.
LowerWhenClauses(sortedNodes);
ImmutableArray<BoundDecisionDagNode> nodesToLower = sortedNodes.WhereAsArray(n => n.Kind != BoundKind.WhenDecisionDagNode && n.Kind != BoundKind.LeafDecisionDagNode);
var loweredNodes = PooledHashSet<BoundDecisionDagNode>.GetInstance();
for (int i = 0, length = nodesToLower.Length; i < length; i++)
{
BoundDecisionDagNode node = nodesToLower[i];
// A node may have been lowered as part of a switch dispatch, but if it had a label, we'll need to lower it individually as well
bool alreadyLowered = loweredNodes.Contains(node);
if (alreadyLowered && !_dagNodeLabels.TryGetValue(node, out _))
{
continue;
}
if (_dagNodeLabels.TryGetValue(node, out LabelSymbol label))
{
_loweredDecisionDag.Add(_factory.Label(label));
}
// If we can generate an IL switch instruction, do so
if (!alreadyLowered && GenerateSwitchDispatch(node, loweredNodes))
{
continue;
}
// If we can generate a type test and cast more efficiently as an `is` followed by a null check, do so
if (GenerateTypeTestAndCast(node, loweredNodes, nodesToLower, i))
{
continue;
}
// We pass the node that will follow so we can permit a test to fall through if appropriate
BoundDecisionDagNode nextNode = ((i + 1) < length) ? nodesToLower[i + 1] : null;
if (nextNode != null && loweredNodes.Contains(nextNode))
{
nextNode = null;
}
LowerDecisionDagNode(node, nextNode);
}
loweredNodes.Free();
var result = _loweredDecisionDag.ToImmutableAndFree();
_loweredDecisionDag = null;
return result;
}
/// <summary>
/// If we have a type test followed by a cast to that type, and the types are reference types,
/// then we can replace the pair of them by a conversion using `as` and a null check.
/// </summary>
/// <returns>true if we generated code for the test</returns>
private bool GenerateTypeTestAndCast(
BoundDecisionDagNode node,
HashSet<BoundDecisionDagNode> loweredNodes,
ImmutableArray<BoundDecisionDagNode> nodesToLower,
int indexOfNode)
{
Debug.Assert(node == nodesToLower[indexOfNode]);
if (node is BoundTestDecisionDagNode testNode &&
testNode.WhenTrue is BoundEvaluationDecisionDagNode evaluationNode &&
TryLowerTypeTestAndCast(testNode.Test, evaluationNode.Evaluation, out BoundExpression sideEffect, out BoundExpression test)
)
{
var whenTrue = evaluationNode.Next;
var whenFalse = testNode.WhenFalse;
bool canEliminateEvaluationNode = !this._dagNodeLabels.ContainsKey(evaluationNode);
if (canEliminateEvaluationNode)
loweredNodes.Add(evaluationNode);
var nextNode =
(indexOfNode + 2 < nodesToLower.Length) &&
canEliminateEvaluationNode &&
nodesToLower[indexOfNode + 1] == evaluationNode &&
!loweredNodes.Contains(nodesToLower[indexOfNode + 2]) ? nodesToLower[indexOfNode + 2] : null;
_loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect));
GenerateTest(test, whenTrue, whenFalse, nextNode);
return true;
}
return false;
}
private void GenerateTest(BoundExpression test, BoundDecisionDagNode whenTrue, BoundDecisionDagNode whenFalse, BoundDecisionDagNode nextNode)
{
// Because we have already "optimized" away tests for a constant switch expression, the test should be nontrivial.
_factory.Syntax = test.Syntax;
Debug.Assert(test != null);
if (nextNode == whenFalse)
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true));
// fall through to false path
}
else if (nextNode == whenTrue)
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenFalse), jumpIfTrue: false));
// fall through to true path
}
else
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, GetDagNodeLabel(whenTrue), jumpIfTrue: true));
_loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(whenFalse)));
}
}
/// <summary>
/// Generate a switch dispatch for a contiguous sequence of dag nodes if applicable.
/// Returns true if it was applicable.
/// </summary>
private bool GenerateSwitchDispatch(BoundDecisionDagNode node, HashSet<BoundDecisionDagNode> loweredNodes)
{
Debug.Assert(!loweredNodes.Contains(node));
if (!canGenerateSwitchDispatch(node))
return false;
var input = ((BoundTestDecisionDagNode)node).Test.Input;
ValueDispatchNode n = GatherValueDispatchNodes(node, loweredNodes, input);
LowerValueDispatchNode(n, _tempAllocator.GetTemp(input));
return true;
bool canGenerateSwitchDispatch(BoundDecisionDagNode node)
{
switch (node)
{
// These are the forms worth optimizing.
case BoundTestDecisionDagNode { WhenFalse: BoundTestDecisionDagNode test2 } test1:
return canDispatch(test1, test2);
case BoundTestDecisionDagNode { WhenTrue: BoundTestDecisionDagNode test2 } test1:
return canDispatch(test1, test2);
default:
// Other cases are just as well done with a single test.
return false;
}
bool canDispatch(BoundTestDecisionDagNode test1, BoundTestDecisionDagNode test2)
{
if (this._dagNodeLabels.ContainsKey(test2))
return false;
Debug.Assert(!loweredNodes.Contains(test2));
var t1 = test1.Test;
var t2 = test2.Test;
if (!(t1 is BoundDagValueTest || t1 is BoundDagRelationalTest))
return false;
if (!(t2 is BoundDagValueTest || t2 is BoundDagRelationalTest))
return false;
if (!t1.Input.Equals(t2.Input))
return false;
return true;
}
}
}
private ValueDispatchNode GatherValueDispatchNodes(
BoundDecisionDagNode node,
HashSet<BoundDecisionDagNode> loweredNodes,
BoundDagTemp input)
{
IValueSetFactory fac = ValueSetFactory.ForType(input.Type);
return GatherValueDispatchNodes(node, loweredNodes, input, fac);
}
private ValueDispatchNode GatherValueDispatchNodes(
BoundDecisionDagNode node,
HashSet<BoundDecisionDagNode> loweredNodes,
BoundDagTemp input,
IValueSetFactory fac)
{
if (loweredNodes.Contains(node))
{
bool foundLabel = this._dagNodeLabels.TryGetValue(node, out LabelSymbol label);
Debug.Assert(foundLabel);
return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label);
}
if (!(node is BoundTestDecisionDagNode testNode && testNode.Test.Input.Equals(input)))
{
var label = GetDagNodeLabel(node);
return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label);
}
switch (testNode.Test)
{
case BoundDagRelationalTest relational:
{
loweredNodes.Add(testNode);
var whenTrue = GatherValueDispatchNodes(testNode.WhenTrue, loweredNodes, input, fac);
var whenFalse = GatherValueDispatchNodes(testNode.WhenFalse, loweredNodes, input, fac);
return ValueDispatchNode.RelationalDispatch.CreateBalanced(testNode.Syntax, relational.Value, relational.OperatorKind, whenTrue: whenTrue, whenFalse: whenFalse);
}
case BoundDagValueTest value:
{
// Gather up the (value, label) pairs, starting with the first one
loweredNodes.Add(testNode);
var cases = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance();
cases.Add((value: value.Value, label: GetDagNodeLabel(testNode.WhenTrue)));
BoundTestDecisionDagNode previous = testNode;
while (previous.WhenFalse is BoundTestDecisionDagNode p &&
p.Test is BoundDagValueTest vd &&
vd.Input.Equals(input) &&
!this._dagNodeLabels.ContainsKey(p) &&
!loweredNodes.Contains(p))
{
cases.Add((value: vd.Value, label: GetDagNodeLabel(p.WhenTrue)));
loweredNodes.Add(p);
previous = p;
}
var otherwise = GatherValueDispatchNodes(previous.WhenFalse, loweredNodes, input, fac);
return PushEqualityTestsIntoTree(value.Syntax, otherwise, cases.ToImmutableAndFree(), fac);
}
default:
{
var label = GetDagNodeLabel(node);
return new ValueDispatchNode.LeafDispatchNode(node.Syntax, label);
}
}
}
/// <summary>
/// Push the set of equality tests down to the level of the leaves in the value dispatch tree.
/// </summary>
private ValueDispatchNode PushEqualityTestsIntoTree(
SyntaxNode syntax,
ValueDispatchNode otherwise,
ImmutableArray<(ConstantValue value, LabelSymbol label)> cases,
IValueSetFactory fac)
{
if (cases.IsEmpty)
return otherwise;
switch (otherwise)
{
case ValueDispatchNode.LeafDispatchNode leaf:
return new ValueDispatchNode.SwitchDispatch(syntax, cases, leaf.Label);
case ValueDispatchNode.SwitchDispatch sd:
return new ValueDispatchNode.SwitchDispatch(sd.Syntax, sd.Cases.Concat(cases), sd.Otherwise);
case ValueDispatchNode.RelationalDispatch { Operator: var op, Value: var value, WhenTrue: var whenTrue, WhenFalse: var whenFalse } rel:
var (whenTrueCases, whenFalseCases) = splitCases(cases, op, value);
Debug.Assert(cases.Length == whenTrueCases.Length + whenFalseCases.Length);
whenTrue = PushEqualityTestsIntoTree(syntax, whenTrue, whenTrueCases, fac);
whenFalse = PushEqualityTestsIntoTree(syntax, whenFalse, whenFalseCases, fac);
var result = rel.WithTrueAndFalseChildren(whenTrue: whenTrue, whenFalse: whenFalse);
return result;
default:
throw ExceptionUtilities.UnexpectedValue(otherwise);
}
(ImmutableArray<(ConstantValue value, LabelSymbol label)> whenTrueCases, ImmutableArray<(ConstantValue value, LabelSymbol label)> whenFalseCases)
splitCases(ImmutableArray<(ConstantValue value, LabelSymbol label)> cases, BinaryOperatorKind op, ConstantValue value)
{
var whenTrueBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance();
var whenFalseBuilder = ArrayBuilder<(ConstantValue value, LabelSymbol label)>.GetInstance();
op = op.Operator();
foreach (var pair in cases)
{
(fac.Related(op, pair.value, value) ? whenTrueBuilder : whenFalseBuilder).Add(pair);
}
return (whenTrueBuilder.ToImmutableAndFree(), whenFalseBuilder.ToImmutableAndFree());
}
}
private void LowerValueDispatchNode(ValueDispatchNode n, BoundExpression input)
{
switch (n)
{
case ValueDispatchNode.LeafDispatchNode leaf:
_loweredDecisionDag.Add(_factory.Goto(leaf.Label));
return;
case ValueDispatchNode.SwitchDispatch eq:
LowerSwitchDispatchNode(eq, input);
return;
case ValueDispatchNode.RelationalDispatch rel:
LowerRelationalDispatchNode(rel, input);
return;
default:
throw ExceptionUtilities.UnexpectedValue(n);
}
}
private void LowerRelationalDispatchNode(ValueDispatchNode.RelationalDispatch rel, BoundExpression input)
{
var test = MakeRelationalTest(rel.Syntax, input, rel.Operator, rel.Value);
if (rel.WhenTrue is ValueDispatchNode.LeafDispatchNode whenTrue)
{
LabelSymbol trueLabel = whenTrue.Label;
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, trueLabel, jumpIfTrue: true));
LowerValueDispatchNode(rel.WhenFalse, input);
}
else if (rel.WhenFalse is ValueDispatchNode.LeafDispatchNode whenFalse)
{
LabelSymbol falseLabel = whenFalse.Label;
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false));
LowerValueDispatchNode(rel.WhenTrue, input);
}
else
{
LabelSymbol falseLabel = _factory.GenerateLabel("relationalDispatch");
_loweredDecisionDag.Add(_factory.ConditionalGoto(test, falseLabel, jumpIfTrue: false));
LowerValueDispatchNode(rel.WhenTrue, input);
_loweredDecisionDag.Add(_factory.Label(falseLabel));
LowerValueDispatchNode(rel.WhenFalse, input);
}
}
/// <summary>
/// A comparer for sorting cases containing values of type float, double, or decimal.
/// </summary>
private sealed class CasesComparer : IComparer<(ConstantValue value, LabelSymbol label)>
{
private readonly IValueSetFactory _fac;
public CasesComparer(TypeSymbol type)
{
_fac = ValueSetFactory.ForType(type);
Debug.Assert(_fac is { });
}
int IComparer<(ConstantValue value, LabelSymbol label)>.Compare((ConstantValue value, LabelSymbol label) left, (ConstantValue value, LabelSymbol label) right)
{
var x = left.value;
var y = right.value;
Debug.Assert(x.Discriminator switch
{
ConstantValueTypeDiscriminator.Decimal => true,
ConstantValueTypeDiscriminator.Single => true,
ConstantValueTypeDiscriminator.Double => true,
ConstantValueTypeDiscriminator.NInt => true,
ConstantValueTypeDiscriminator.NUInt => true,
_ => false
});
Debug.Assert(y.Discriminator == x.Discriminator);
// Sort NaN values into the "highest" position so they fall naturally into the last bucket
// when partitioned using less-than.
return
isNaN(x) ? 1 :
isNaN(y) ? -1 :
_fac.Related(BinaryOperatorKind.LessThanOrEqual, x, y) ?
(_fac.Related(BinaryOperatorKind.LessThanOrEqual, y, x) ? 0 : -1) :
1;
static bool isNaN(ConstantValue value) =>
(value.Discriminator == ConstantValueTypeDiscriminator.Single || value.Discriminator == ConstantValueTypeDiscriminator.Double) &&
double.IsNaN(value.DoubleValue);
}
}
private void LowerSwitchDispatchNode(ValueDispatchNode.SwitchDispatch node, BoundExpression input)
{
LabelSymbol defaultLabel = node.Otherwise;
if (input.Type.IsValidV6SwitchGoverningType())
{
// If we are emitting a hash table based string switch,
// we need to generate a helper method for computing
// string hash value in <PrivateImplementationDetails> class.
MethodSymbol stringEquality = null;
if (input.Type.SpecialType == SpecialType.System_String)
{
EnsureStringHashFunction(node.Cases.Length, node.Syntax);
stringEquality = _localRewriter.UnsafeGetSpecialTypeMethod(node.Syntax, SpecialMember.System_String__op_Equality);
}
var dispatch = new BoundSwitchDispatch(node.Syntax, input, node.Cases, defaultLabel, stringEquality);
_loweredDecisionDag.Add(dispatch);
}
else if (input.Type.IsNativeIntegerType)
{
// Native types need to be dispatched using a larger underlying type so that any
// possible high bits are not truncated.
ImmutableArray<(ConstantValue value, LabelSymbol label)> cases;
switch (input.Type.SpecialType)
{
case SpecialType.System_IntPtr:
{
input = _factory.Convert(_factory.SpecialType(SpecialType.System_Int64), input);
cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((long)p.value.Int32Value), p.label));
break;
}
case SpecialType.System_UIntPtr:
{
input = _factory.Convert(_factory.SpecialType(SpecialType.System_UInt64), input);
cases = node.Cases.SelectAsArray(p => (ConstantValue.Create((ulong)p.value.UInt32Value), p.label));
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(input.Type);
}
var dispatch = new BoundSwitchDispatch(node.Syntax, input, cases, defaultLabel, equalityMethod: null);
_loweredDecisionDag.Add(dispatch);
}
else
{
// The emitter does not know how to produce a "switch" instruction for float, double, or decimal
// (in part because there is no such instruction) so we fake it here by generating a decision tree.
var lessThanOrEqualOperator = input.Type.SpecialType switch
{
SpecialType.System_Single => BinaryOperatorKind.FloatLessThanOrEqual,
SpecialType.System_Double => BinaryOperatorKind.DoubleLessThanOrEqual,
SpecialType.System_Decimal => BinaryOperatorKind.DecimalLessThanOrEqual,
_ => throw ExceptionUtilities.UnexpectedValue(input.Type.SpecialType)
};
var cases = node.Cases.Sort(new CasesComparer(input.Type));
lowerFloatDispatch(0, cases.Length);
void lowerFloatDispatch(int firstIndex, int count)
{
if (count <= 3)
{
for (int i = firstIndex, limit = firstIndex + count; i < limit; i++)
{
_loweredDecisionDag.Add(_factory.ConditionalGoto(MakeValueTest(node.Syntax, input, cases[i].value), cases[i].label, jumpIfTrue: true));
}
_loweredDecisionDag.Add(_factory.Goto(defaultLabel));
}
else
{
int half = count / 2;
var gt = _factory.GenerateLabel("greaterThanMidpoint");
_loweredDecisionDag.Add(_factory.ConditionalGoto(MakeRelationalTest(node.Syntax, input, lessThanOrEqualOperator, cases[firstIndex + half - 1].value), gt, jumpIfTrue: false));
lowerFloatDispatch(firstIndex, half);
_loweredDecisionDag.Add(_factory.Label(gt));
lowerFloatDispatch(firstIndex + half, count - half);
}
}
}
}
/// <summary>
/// Checks whether we are generating a hash table based string switch and
/// we need to generate a new helper method for computing string hash value.
/// Creates the method if needed.
/// </summary>
private void EnsureStringHashFunction(int labelsCount, SyntaxNode syntaxNode)
{
var module = _localRewriter.EmitModule;
if (module == null)
{
// we're not generating code, so we don't need the hash function
return;
}
// For string switch statements, we need to determine if we are generating a hash
// table based jump table or a non hash jump table, i.e. linear string comparisons
// with each case label. We use the Dev10 Heuristic to determine this
// (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details).
if (!CodeAnalysis.CodeGen.SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(module, labelsCount))
{
return;
}
// If we are generating a hash table based jump table, we use a simple customizable
// hash function to hash the string constants corresponding to the case labels.
// See SwitchStringJumpTableEmitter.ComputeStringHash().
// We need to emit this function to compute the hash value into the compiler generated
// <PrivateImplementationDetails> class.
// If we have at least one string switch statement in a module that needs a
// hash table based jump table, we generate a single public string hash synthesized method
// that is shared across the module.
// If we have already generated the helper, possibly for another switch
// or on another thread, we don't need to regenerate it.
var privateImplClass = module.GetPrivateImplClass(syntaxNode, _localRewriter._diagnostics.DiagnosticBag);
if (privateImplClass.GetMethod(CodeAnalysis.CodeGen.PrivateImplementationDetails.SynthesizedStringHashFunctionName) != null)
{
return;
}
// cannot emit hash method if have no access to Chars.
var charsMember = _localRewriter._compilation.GetSpecialTypeMember(SpecialMember.System_String__Chars);
if ((object)charsMember == null || charsMember.HasUseSiteError)
{
return;
}
TypeSymbol returnType = _factory.SpecialType(SpecialType.System_UInt32);
TypeSymbol paramType = _factory.SpecialType(SpecialType.System_String);
var method = new SynthesizedStringSwitchHashMethod(module.SourceModule, privateImplClass, returnType, paramType);
privateImplClass.TryAddSynthesizedMethod(method.GetCciAdapter());
}
#nullable enable
private void LowerWhenClauses(ImmutableArray<BoundDecisionDagNode> sortedNodes)
{
if (!sortedNodes.Any(n => n.Kind == BoundKind.WhenDecisionDagNode)) return;
// The way the DAG is prepared, it is possible for different `BoundWhenDecisionDagNode` nodes to
// share the same `WhenExpression` (same `BoundExpression` instance).
// So we can't just lower each `BoundWhenDecisionDagNode` separately, as that would result in duplicate blocks
// for the same `WhenExpression` and such expressions might contains labels which must be emitted once only.
// For a simple `BoundWhenDecisionDagNode` (with a unique `WhenExpression`), we lower to something like:
// labelToSectionScope;
// if (... logic from WhenExpression ...)
// {
// jump to whenTrue label
// }
// jump to whenFalse label
// For a complex `BoundWhenDecisionDagNode` (where the `WhenExpression` is shared), we lower to something like:
// labelToSectionScope;
// whenNodeIdentifierLocal = whenNodeIdentifier;
// goto labelToWhenExpression;
//
// and we'll also create a section for the shared `WhenExpression` logic:
// labelToWhenExpression;
// if (... logic from WhenExpression ...)
// {
// jump to whenTrue label
// }
// switch on whenNodeIdentifierLocal with dispatches to whenFalse labels
// Prepared maps for `when` nodes and expressions
var whenExpressionMap = PooledDictionary<BoundExpression, (LabelSymbol LabelToWhenExpression, ArrayBuilder<BoundWhenDecisionDagNode> WhenNodes)>.GetInstance();
var whenNodeMap = PooledDictionary<BoundWhenDecisionDagNode, (LabelSymbol LabelToWhenExpression, int WhenNodeIdentifier)>.GetInstance();
foreach (BoundDecisionDagNode node in sortedNodes)
{
if (node is BoundWhenDecisionDagNode whenNode)
{
var whenExpression = whenNode.WhenExpression;
if (whenExpression is not null && whenExpression.ConstantValue != ConstantValue.True)
{
LabelSymbol labelToWhenExpression;
if (whenExpressionMap.TryGetValue(whenExpression, out var whenExpressionInfo))
{
labelToWhenExpression = whenExpressionInfo.LabelToWhenExpression;
whenExpressionInfo.WhenNodes.Add(whenNode);
}
else
{
labelToWhenExpression = _factory.GenerateLabel("sharedWhenExpression");
var list = ArrayBuilder<BoundWhenDecisionDagNode>.GetInstance();
list.Add(whenNode);
whenExpressionMap.Add(whenExpression, (labelToWhenExpression, list));
}
whenNodeMap.Add(whenNode, (labelToWhenExpression, _nextWhenNodeIdentifier++));
}
}
}
// Lower nodes
foreach (BoundDecisionDagNode node in sortedNodes)
{
if (node is BoundWhenDecisionDagNode whenNode)
{
if (!tryLowerAsJumpToSharedWhenExpression(whenNode))
{
lowerWhenClause(whenNode);
}
}
}
// Lower shared `when` expressions
foreach (var (whenExpression, (labelToWhenExpression, whenNodes)) in whenExpressionMap)
{
lowerWhenExpressionIfShared(whenExpression, labelToWhenExpression, whenNodes);
whenNodes.Free();
}
whenExpressionMap.Free();
whenNodeMap.Free();
return;
bool tryLowerAsJumpToSharedWhenExpression(BoundWhenDecisionDagNode whenNode)
{
var whenExpression = whenNode.WhenExpression;
if (!isSharedWhenExpression(whenExpression))
{
return false;
}
LabelSymbol labelToSectionScope = GetDagNodeLabel(whenNode);
ArrayBuilder<BoundStatement> sectionBuilder = BuilderForSection(whenNode.Syntax);
sectionBuilder.Add(_factory.Label(labelToSectionScope));
_whenNodeIdentifierLocal ??= _factory.SynthesizedLocal(_factory.SpecialType(SpecialType.System_Int32));
var found = whenNodeMap.TryGetValue(whenNode, out var whenNodeInfo);
Debug.Assert(found);
// whenNodeIdentifierLocal = whenNodeIdentifier;
sectionBuilder.Add(_factory.Assignment(_factory.Local(_whenNodeIdentifierLocal), _factory.Literal(whenNodeInfo.WhenNodeIdentifier)));
// goto labelToWhenExpression;
sectionBuilder.Add(_factory.Goto(whenNodeInfo.LabelToWhenExpression));
return true;
}
void lowerWhenExpressionIfShared(BoundExpression whenExpression, LabelSymbol labelToWhenExpression, ArrayBuilder<BoundWhenDecisionDagNode> whenNodes)
{
if (!isSharedWhenExpression(whenExpression))
{
return;
}
var whenClauseSyntax = whenNodes[0].Syntax;
var whenTrueLabel = GetDagNodeLabel(whenNodes[0].WhenTrue);
Debug.Assert(whenNodes.Count > 1);
Debug.Assert(whenNodes.All(n => n.Syntax == whenClauseSyntax));
Debug.Assert(whenNodes.All(n => n.WhenExpression == whenExpression));
Debug.Assert(whenNodes.All(n => n.Bindings == whenNodes[0].Bindings));
Debug.Assert(whenNodes.All(n => GetDagNodeLabel(n.WhenTrue) == whenTrueLabel));
ArrayBuilder<BoundStatement> sectionBuilder = BuilderForSection(whenClauseSyntax);
sectionBuilder.Add(_factory.Label(labelToWhenExpression));
lowerBindings(whenNodes[0].Bindings, sectionBuilder);
addConditionalGoto(whenExpression, whenClauseSyntax, whenTrueLabel, sectionBuilder);
var whenFalseSwitchSections = ArrayBuilder<SyntheticSwitchSection>.GetInstance();
foreach (var whenNode in whenNodes)
{
var (_, whenNodeIdentifier) = whenNodeMap[whenNode];
Debug.Assert(whenNode.WhenFalse != null);
whenFalseSwitchSections.Add(_factory.SwitchSection(whenNodeIdentifier, _factory.Goto(GetDagNodeLabel(whenNode.WhenFalse))));
}
// switch (whenNodeIdentifierLocal)
// {
// case whenNodeIdentifier: goto falseLabelForWhenNode;
// ...
// }
Debug.Assert(_whenNodeIdentifierLocal is not null);
BoundStatement jumps = _factory.Switch(_factory.Local(_whenNodeIdentifierLocal), whenFalseSwitchSections.ToImmutableAndFree());
// We hide the jump back into the decision dag, as it is not logically part of the when clause
sectionBuilder.Add(GenerateInstrumentation ? _factory.HiddenSequencePoint(jumps) : jumps);
}
// if (loweredWhenExpression)
// {
// jump to whenTrue label
// }
void addConditionalGoto(BoundExpression whenExpression, SyntaxNode whenClauseSyntax, LabelSymbol whenTrueLabel, ArrayBuilder<BoundStatement> sectionBuilder)
{
_factory.Syntax = whenClauseSyntax;
BoundStatement conditionalGoto = _factory.ConditionalGoto(_localRewriter.VisitExpression(whenExpression), whenTrueLabel, jumpIfTrue: true);
// Only add instrumentation (such as a sequence point) if the node is not compiler-generated.
if (GenerateInstrumentation && !whenExpression.WasCompilerGenerated)
{
conditionalGoto = _localRewriter._instrumenter.InstrumentSwitchWhenClauseConditionalGotoBody(whenExpression, conditionalGoto);
}
sectionBuilder.Add(conditionalGoto);
}
bool isSharedWhenExpression(BoundExpression? whenExpression)
{
return whenExpression is not null
&& whenExpressionMap.TryGetValue(whenExpression, out var whenExpressionInfo)
&& whenExpressionInfo.WhenNodes.Count > 1;
}
void lowerWhenClause(BoundWhenDecisionDagNode whenClause)
{
// This node is used even when there is no when clause, to record bindings. In the case that there
// is no when clause, whenClause.WhenExpression and whenClause.WhenFalse are null, and the syntax for this
// node is the case clause.
// We need to assign the pattern variables in the code where they are in scope, so we produce a branch
// to the section where they are in scope and evaluate the when clause there.
var whenTrue = (BoundLeafDecisionDagNode)whenClause.WhenTrue;
LabelSymbol labelToSectionScope = GetDagNodeLabel(whenClause);
ArrayBuilder<BoundStatement> sectionBuilder = BuilderForSection(whenClause.Syntax);
sectionBuilder.Add(_factory.Label(labelToSectionScope));
lowerBindings(whenClause.Bindings, sectionBuilder);
var whenFalse = whenClause.WhenFalse;
var trueLabel = GetDagNodeLabel(whenTrue);
if (whenClause.WhenExpression != null && whenClause.WhenExpression.ConstantValue != ConstantValue.True)
{
addConditionalGoto(whenClause.WhenExpression, whenClause.Syntax, trueLabel, sectionBuilder);
// We hide the jump back into the decision dag, as it is not logically part of the when clause
Debug.Assert(whenFalse != null);
BoundStatement jump = _factory.Goto(GetDagNodeLabel(whenFalse));
sectionBuilder.Add(GenerateInstrumentation ? _factory.HiddenSequencePoint(jump) : jump);
}
else
{
Debug.Assert(whenFalse == null);
sectionBuilder.Add(_factory.Goto(trueLabel));
}
}
void lowerBindings(ImmutableArray<BoundPatternBinding> bindings, ArrayBuilder<BoundStatement> sectionBuilder)
{
foreach (BoundPatternBinding binding in bindings)
{
BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess);
// Since a switch does not add variables to the enclosing scope, the pattern variables
// are locals even in a script and rewriting them should have no effect.
Debug.Assert(left.Kind == BoundKind.Local && left == binding.VariableAccess);
BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue);
if (left != right)
{
sectionBuilder.Add(_factory.Assignment(left, right));
}
}
}
}
#nullable disable
/// <summary>
/// Translate the decision dag for node, given that it will be followed by the translation for nextNode.
/// </summary>
private void LowerDecisionDagNode(BoundDecisionDagNode node, BoundDecisionDagNode nextNode)
{
_factory.Syntax = node.Syntax;
switch (node)
{
case BoundEvaluationDecisionDagNode evaluationNode:
{
BoundExpression sideEffect = LowerEvaluation(evaluationNode.Evaluation);
Debug.Assert(sideEffect != null);
_loweredDecisionDag.Add(_factory.ExpressionStatement(sideEffect));
// We add a hidden sequence point after the evaluation's side-effect, which may be a call out
// to user code such as `Deconstruct` or a property get, to permit edit-and-continue to
// synchronize on changes.
if (GenerateInstrumentation)
_loweredDecisionDag.Add(_factory.HiddenSequencePoint());
if (nextNode != evaluationNode.Next)
{
// We only need a goto if we would not otherwise fall through to the desired state
_loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(evaluationNode.Next)));
}
}
break;
case BoundTestDecisionDagNode testNode:
{
BoundExpression test = base.LowerTest(testNode.Test);
GenerateTest(test, testNode.WhenTrue, testNode.WhenFalse, nextNode);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_PatternSwitchStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
{
return SwitchStatementLocalRewriter.Rewrite(this, node);
}
private sealed class SwitchStatementLocalRewriter : BaseSwitchLocalRewriter
{
/// <summary>
/// A map from section syntax to the first label in that section.
/// </summary>
private readonly Dictionary<SyntaxNode, LabelSymbol> _sectionLabels = PooledDictionary<SyntaxNode, LabelSymbol>.GetInstance();
public static BoundStatement Rewrite(LocalRewriter localRewriter, BoundSwitchStatement node)
{
var rewriter = new SwitchStatementLocalRewriter(node, localRewriter);
BoundStatement result = rewriter.LowerSwitchStatement(node);
rewriter.Free();
return result;
}
/// <summary>
/// We revise the returned label for a leaf so that all leaves in the same switch section are given the same label.
/// This enables the switch emitter to produce better code.
/// </summary>
protected override LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag)
{
var result = base.GetDagNodeLabel(dag);
if (dag is BoundLeafDecisionDagNode d)
{
SyntaxNode? section = d.Syntax.Parent;
// It is possible that the leaf represents a compiler-generated default for a switch statement in the EE.
// In that case d.Syntax is the whole switch statement, and its parent is null. We are only interested
// in leaves that result from explicit switch case labels in a switch section.
if (section?.Kind() == SyntaxKind.SwitchSection)
{
if (_sectionLabels.TryGetValue(section, out LabelSymbol? replacementLabel))
{
return replacementLabel;
}
_sectionLabels.Add(section, result);
}
}
return result;
}
private SwitchStatementLocalRewriter(BoundSwitchStatement node, LocalRewriter localRewriter)
: base(node.Syntax, localRewriter, node.SwitchSections.SelectAsArray(section => section.Syntax),
// Only add instrumentation (such as sequence points) if the node is not compiler-generated.
generateInstrumentation: localRewriter.Instrument && !node.WasCompilerGenerated)
{
}
private BoundStatement LowerSwitchStatement(BoundSwitchStatement node)
{
_factory.Syntax = node.Syntax;
var result = ArrayBuilder<BoundStatement>.GetInstance();
var outerVariables = ArrayBuilder<LocalSymbol>.GetInstance();
var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression);
if (!node.WasCompilerGenerated && _localRewriter.Instrument)
{
// 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 expression are being executed.
var instrumentedExpression = _localRewriter._instrumenter.InstrumentSwitchStatementExpression(node, loweredSwitchGoverningExpression, _factory);
if (loweredSwitchGoverningExpression.ConstantValue == null)
{
loweredSwitchGoverningExpression = instrumentedExpression;
}
else
{
// If the expression is a constant, we leave it alone (the decision dag lowering code needs
// to see that constant). But we add an additional leading statement with the instrumented expression.
result.Add(_factory.ExpressionStatement(instrumentedExpression));
}
}
// The set of variables attached to the outer block
outerVariables.AddRange(node.InnerLocals);
// Evaluate the input and set up sharing for dag temps with user variables
BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput(node.DecisionDag, loweredSwitchGoverningExpression, result, out _);
// In a switch statement, there is a hidden sequence point after evaluating the input at the start of
// the code to handle the decision dag. This is necessary so that jumps back from a `when` clause into
// the decision dag do not appear to jump back up to the enclosing construct.
if (GenerateInstrumentation)
{
// Since there may have been no code to evaluate the input, add a no-op for any previous sequence point to bind to.
if (result.Count == 0)
result.Add(_factory.NoOp(NoOpStatementFlavor.Default));
result.Add(_factory.HiddenSequencePoint());
}
// lower the decision dag.
(ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) =
LowerDecisionDag(decisionDag);
// then add the rest of the lowered dag that references that input
result.Add(_factory.Block(loweredDag));
// A branch to the default label when no switch case matches is included in the
// decision dag, so the code in `result` is unreachable at this point.
// Lower each switch section.
foreach (BoundSwitchSection section in node.SwitchSections)
{
_factory.Syntax = section.Syntax;
var sectionBuilder = ArrayBuilder<BoundStatement>.GetInstance();
sectionBuilder.AddRange(switchSections[section.Syntax]);
foreach (BoundSwitchLabel switchLabel in section.SwitchLabels)
{
sectionBuilder.Add(_factory.Label(switchLabel.Label));
}
// Add the translated body of the switch section
sectionBuilder.AddRange(_localRewriter.VisitList(section.Statements));
// By the semantics of the switch statement, the end of each section is required to be unreachable.
// So we can just seal the block and there is no need to follow it by anything.
ImmutableArray<BoundStatement> statements = sectionBuilder.ToImmutableAndFree();
if (section.Locals.IsEmpty)
{
result.Add(_factory.StatementList(statements));
}
else
{
// Lifetime of these locals is expanded to the entire switch body, as it is possible to capture
// them in a different section by using a local function as an intermediary.
outerVariables.AddRange(section.Locals);
// Note the language scope of the locals, even though they are included for the purposes of
// lifetime analysis in the enclosing scope.
result.Add(new BoundScope(section.Syntax, section.Locals, statements));
}
}
// Dispatch temps are in scope throughout the switch statement, as they are used
// both in the dispatch section to hold temporary values from the translation of
// the decision dag, and in the branches where the temp values are assigned to the
// pattern variables of matched patterns.
outerVariables.AddRange(_tempAllocator.AllTemps());
_factory.Syntax = node.Syntax;
if (GenerateInstrumentation)
result.Add(_factory.HiddenSequencePoint());
result.Add(_factory.Label(node.BreakLabel));
BoundStatement translatedSwitch = _factory.Block(outerVariables.ToImmutableAndFree(), node.InnerLocalFunctions, result.ToImmutableAndFree());
if (GenerateInstrumentation)
translatedSwitch = _localRewriter._instrumenter.InstrumentSwitchStatement(node, translatedSwitch);
return translatedSwitch;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
{
return SwitchStatementLocalRewriter.Rewrite(this, node);
}
private sealed class SwitchStatementLocalRewriter : BaseSwitchLocalRewriter
{
/// <summary>
/// A map from section syntax to the first label in that section.
/// </summary>
private readonly Dictionary<SyntaxNode, LabelSymbol> _sectionLabels = PooledDictionary<SyntaxNode, LabelSymbol>.GetInstance();
public static BoundStatement Rewrite(LocalRewriter localRewriter, BoundSwitchStatement node)
{
var rewriter = new SwitchStatementLocalRewriter(node, localRewriter);
BoundStatement result = rewriter.LowerSwitchStatement(node);
rewriter.Free();
return result;
}
/// <summary>
/// We revise the returned label for a leaf so that all leaves in the same switch section are given the same label.
/// This enables the switch emitter to produce better code.
/// </summary>
protected override LabelSymbol GetDagNodeLabel(BoundDecisionDagNode dag)
{
var result = base.GetDagNodeLabel(dag);
if (dag is BoundLeafDecisionDagNode d)
{
SyntaxNode? section = d.Syntax.Parent;
// It is possible that the leaf represents a compiler-generated default for a switch statement in the EE.
// In that case d.Syntax is the whole switch statement, and its parent is null. We are only interested
// in leaves that result from explicit switch case labels in a switch section.
if (section?.Kind() == SyntaxKind.SwitchSection)
{
if (_sectionLabels.TryGetValue(section, out LabelSymbol? replacementLabel))
{
return replacementLabel;
}
_sectionLabels.Add(section, result);
}
}
return result;
}
private SwitchStatementLocalRewriter(BoundSwitchStatement node, LocalRewriter localRewriter)
: base(node.Syntax, localRewriter, node.SwitchSections.SelectAsArray(section => section.Syntax),
// Only add instrumentation (such as sequence points) if the node is not compiler-generated.
generateInstrumentation: localRewriter.Instrument && !node.WasCompilerGenerated)
{
}
private BoundStatement LowerSwitchStatement(BoundSwitchStatement node)
{
_factory.Syntax = node.Syntax;
var result = ArrayBuilder<BoundStatement>.GetInstance();
var outerVariables = ArrayBuilder<LocalSymbol>.GetInstance();
var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression);
if (!node.WasCompilerGenerated && _localRewriter.Instrument)
{
// 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 expression are being executed.
var instrumentedExpression = _localRewriter._instrumenter.InstrumentSwitchStatementExpression(node, loweredSwitchGoverningExpression, _factory);
if (loweredSwitchGoverningExpression.ConstantValue == null)
{
loweredSwitchGoverningExpression = instrumentedExpression;
}
else
{
// If the expression is a constant, we leave it alone (the decision dag lowering code needs
// to see that constant). But we add an additional leading statement with the instrumented expression.
result.Add(_factory.ExpressionStatement(instrumentedExpression));
}
}
// The set of variables attached to the outer block
outerVariables.AddRange(node.InnerLocals);
// Evaluate the input and set up sharing for dag temps with user variables
BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput(node.DecisionDag, loweredSwitchGoverningExpression, result, out _);
// In a switch statement, there is a hidden sequence point after evaluating the input at the start of
// the code to handle the decision dag. This is necessary so that jumps back from a `when` clause into
// the decision dag do not appear to jump back up to the enclosing construct.
if (GenerateInstrumentation)
{
// Since there may have been no code to evaluate the input, add a no-op for any previous sequence point to bind to.
if (result.Count == 0)
result.Add(_factory.NoOp(NoOpStatementFlavor.Default));
result.Add(_factory.HiddenSequencePoint());
}
// lower the decision dag.
(ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) =
LowerDecisionDag(decisionDag);
if (_whenNodeIdentifierLocal is not null)
{
outerVariables.Add(_whenNodeIdentifierLocal);
}
// then add the rest of the lowered dag that references that input
result.Add(_factory.Block(loweredDag));
// A branch to the default label when no switch case matches is included in the
// decision dag, so the code in `result` is unreachable at this point.
// Lower each switch section.
foreach (BoundSwitchSection section in node.SwitchSections)
{
_factory.Syntax = section.Syntax;
var sectionBuilder = ArrayBuilder<BoundStatement>.GetInstance();
sectionBuilder.AddRange(switchSections[section.Syntax]);
foreach (BoundSwitchLabel switchLabel in section.SwitchLabels)
{
sectionBuilder.Add(_factory.Label(switchLabel.Label));
}
// Add the translated body of the switch section
sectionBuilder.AddRange(_localRewriter.VisitList(section.Statements));
// By the semantics of the switch statement, the end of each section is required to be unreachable.
// So we can just seal the block and there is no need to follow it by anything.
ImmutableArray<BoundStatement> statements = sectionBuilder.ToImmutableAndFree();
if (section.Locals.IsEmpty)
{
result.Add(_factory.StatementList(statements));
}
else
{
// Lifetime of these locals is expanded to the entire switch body, as it is possible to capture
// them in a different section by using a local function as an intermediary.
outerVariables.AddRange(section.Locals);
// Note the language scope of the locals, even though they are included for the purposes of
// lifetime analysis in the enclosing scope.
result.Add(new BoundScope(section.Syntax, section.Locals, statements));
}
}
// Dispatch temps are in scope throughout the switch statement, as they are used
// both in the dispatch section to hold temporary values from the translation of
// the decision dag, and in the branches where the temp values are assigned to the
// pattern variables of matched patterns.
outerVariables.AddRange(_tempAllocator.AllTemps());
_factory.Syntax = node.Syntax;
if (GenerateInstrumentation)
result.Add(_factory.HiddenSequencePoint());
result.Add(_factory.Label(node.BreakLabel));
BoundStatement translatedSwitch = _factory.Block(outerVariables.ToImmutableAndFree(), node.InnerLocalFunctions, result.ToImmutableAndFree());
if (GenerateInstrumentation)
translatedSwitch = _localRewriter._instrumenter.InstrumentSwitchStatement(node, translatedSwitch);
return translatedSwitch;
}
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_SwitchExpression.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node)
{
// The switch expression is lowered to an expression that involves the use of side-effects
// such as jumps and labels, therefore it is represented by a BoundSpillSequence and
// the resulting nodes will need to be "spilled" to move such statements to the top
// level (i.e. into the enclosing statement list).
this._needsSpilling = true;
return SwitchExpressionLocalRewriter.Rewrite(this, node);
}
private sealed class SwitchExpressionLocalRewriter : BaseSwitchLocalRewriter
{
private SwitchExpressionLocalRewriter(BoundConvertedSwitchExpression node, LocalRewriter localRewriter)
: base(node.Syntax, localRewriter, node.SwitchArms.SelectAsArray(arm => arm.Syntax),
generateInstrumentation: !node.WasCompilerGenerated && localRewriter.Instrument)
{
}
public static BoundExpression Rewrite(LocalRewriter localRewriter, BoundConvertedSwitchExpression node)
{
var rewriter = new SwitchExpressionLocalRewriter(node, localRewriter);
BoundExpression result = rewriter.LowerSwitchExpression(node);
rewriter.Free();
return result;
}
private BoundExpression LowerSwitchExpression(BoundConvertedSwitchExpression node)
{
// When compiling for Debug (not Release), we produce the most detailed sequence points.
var produceDetailedSequencePoints =
GenerateInstrumentation && _localRewriter._compilation.Options.OptimizationLevel != OptimizationLevel.Release;
_factory.Syntax = node.Syntax;
var result = ArrayBuilder<BoundStatement>.GetInstance();
var outerVariables = ArrayBuilder<LocalSymbol>.GetInstance();
var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression);
BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput(
node.DecisionDag, loweredSwitchGoverningExpression, result, out BoundExpression savedInputExpression);
Debug.Assert(savedInputExpression != null);
object restorePointForEnclosingStatement = new object();
object restorePointForSwitchBody = new object();
// lower the decision dag.
(ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) =
LowerDecisionDag(decisionDag);
if (produceDetailedSequencePoints)
{
var syntax = (SwitchExpressionSyntax)node.Syntax;
result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForEnclosingStatement));
// While evaluating the state machine, we highlight the `switch {...}` part.
var spanStart = syntax.SwitchKeyword.Span.Start;
var spanEnd = syntax.Span.End;
var spanForSwitchBody = new TextSpan(spanStart, spanEnd - spanStart);
result.Add(new BoundStepThroughSequencePoint(node.Syntax, span: spanForSwitchBody));
result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForSwitchBody));
}
// add the rest of the lowered dag that references that input
result.Add(_factory.Block(loweredDag));
// A branch to the default label when no switch case matches is included in the
// decision tree, so the code in result is unreachable at this point.
// Lower each switch expression arm
LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp);
LabelSymbol afterSwitchExpression = _factory.GenerateLabel("afterSwitchExpression");
foreach (BoundSwitchExpressionArm arm in node.SwitchArms)
{
_factory.Syntax = arm.Syntax;
var sectionBuilder = ArrayBuilder<BoundStatement>.GetInstance();
sectionBuilder.AddRange(switchSections[arm.Syntax]);
sectionBuilder.Add(_factory.Label(arm.Label));
var loweredValue = _localRewriter.VisitExpression(arm.Value);
if (GenerateInstrumentation)
loweredValue = this._localRewriter._instrumenter.InstrumentSwitchExpressionArmExpression(arm.Value, loweredValue, _factory);
sectionBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), loweredValue));
sectionBuilder.Add(_factory.Goto(afterSwitchExpression));
var statements = sectionBuilder.ToImmutableAndFree();
if (arm.Locals.IsEmpty)
{
result.Add(_factory.StatementList(statements));
}
else
{
// Lifetime of these locals is expanded to the entire switch body, as it is possible to
// share them as temps in the decision dag.
outerVariables.AddRange(arm.Locals);
// Note the language scope of the locals, even though they are included for the purposes of
// lifetime analysis in the enclosing scope.
result.Add(new BoundScope(arm.Syntax, arm.Locals, statements));
}
}
_factory.Syntax = node.Syntax;
if (node.DefaultLabel != null)
{
result.Add(_factory.Label(node.DefaultLabel));
if (produceDetailedSequencePoints)
result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForSwitchBody));
var objectType = _factory.SpecialType(SpecialType.System_Object);
var thrownExpression =
(implicitConversionExists(savedInputExpression, objectType) &&
_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, isOptional: true) is MethodSymbol exception1)
? _factory.New(exception1, _factory.Convert(objectType, savedInputExpression)) :
(_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, isOptional: true) is MethodSymbol exception0)
? _factory.New(exception0) :
_factory.New(_factory.WellKnownMethod(WellKnownMember.System_InvalidOperationException__ctor));
result.Add(_factory.Throw(thrownExpression));
}
if (GenerateInstrumentation)
result.Add(_factory.HiddenSequencePoint());
result.Add(_factory.Label(afterSwitchExpression));
if (produceDetailedSequencePoints)
result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForEnclosingStatement));
outerVariables.Add(resultTemp);
outerVariables.AddRange(_tempAllocator.AllTemps());
return _factory.SpillSequence(outerVariables.ToImmutableAndFree(), result.ToImmutableAndFree(), _factory.Local(resultTemp));
bool implicitConversionExists(BoundExpression expression, TypeSymbol type)
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
Conversion c = _localRewriter._compilation.Conversions.ClassifyConversionFromExpression(expression, type, ref discardedUseSiteInfo);
return c.IsImplicit;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node)
{
// The switch expression is lowered to an expression that involves the use of side-effects
// such as jumps and labels, therefore it is represented by a BoundSpillSequence and
// the resulting nodes will need to be "spilled" to move such statements to the top
// level (i.e. into the enclosing statement list).
this._needsSpilling = true;
return SwitchExpressionLocalRewriter.Rewrite(this, node);
}
private sealed class SwitchExpressionLocalRewriter : BaseSwitchLocalRewriter
{
private SwitchExpressionLocalRewriter(BoundConvertedSwitchExpression node, LocalRewriter localRewriter)
: base(node.Syntax, localRewriter, node.SwitchArms.SelectAsArray(arm => arm.Syntax),
generateInstrumentation: !node.WasCompilerGenerated && localRewriter.Instrument)
{
}
public static BoundExpression Rewrite(LocalRewriter localRewriter, BoundConvertedSwitchExpression node)
{
var rewriter = new SwitchExpressionLocalRewriter(node, localRewriter);
BoundExpression result = rewriter.LowerSwitchExpression(node);
rewriter.Free();
return result;
}
private BoundExpression LowerSwitchExpression(BoundConvertedSwitchExpression node)
{
// When compiling for Debug (not Release), we produce the most detailed sequence points.
var produceDetailedSequencePoints =
GenerateInstrumentation && _localRewriter._compilation.Options.OptimizationLevel != OptimizationLevel.Release;
_factory.Syntax = node.Syntax;
var result = ArrayBuilder<BoundStatement>.GetInstance();
var outerVariables = ArrayBuilder<LocalSymbol>.GetInstance();
var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression);
BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput(
node.DecisionDag, loweredSwitchGoverningExpression, result, out BoundExpression savedInputExpression);
Debug.Assert(savedInputExpression != null);
object restorePointForEnclosingStatement = new object();
object restorePointForSwitchBody = new object();
// lower the decision dag.
(ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) =
LowerDecisionDag(decisionDag);
if (_whenNodeIdentifierLocal is not null)
{
outerVariables.Add(_whenNodeIdentifierLocal);
}
if (produceDetailedSequencePoints)
{
var syntax = (SwitchExpressionSyntax)node.Syntax;
result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForEnclosingStatement));
// While evaluating the state machine, we highlight the `switch {...}` part.
var spanStart = syntax.SwitchKeyword.Span.Start;
var spanEnd = syntax.Span.End;
var spanForSwitchBody = new TextSpan(spanStart, spanEnd - spanStart);
result.Add(new BoundStepThroughSequencePoint(node.Syntax, span: spanForSwitchBody));
result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForSwitchBody));
}
// add the rest of the lowered dag that references that input
result.Add(_factory.Block(loweredDag));
// A branch to the default label when no switch case matches is included in the
// decision tree, so the code in result is unreachable at this point.
// Lower each switch expression arm
LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp);
LabelSymbol afterSwitchExpression = _factory.GenerateLabel("afterSwitchExpression");
foreach (BoundSwitchExpressionArm arm in node.SwitchArms)
{
_factory.Syntax = arm.Syntax;
var sectionBuilder = ArrayBuilder<BoundStatement>.GetInstance();
sectionBuilder.AddRange(switchSections[arm.Syntax]);
sectionBuilder.Add(_factory.Label(arm.Label));
var loweredValue = _localRewriter.VisitExpression(arm.Value);
if (GenerateInstrumentation)
loweredValue = this._localRewriter._instrumenter.InstrumentSwitchExpressionArmExpression(arm.Value, loweredValue, _factory);
sectionBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), loweredValue));
sectionBuilder.Add(_factory.Goto(afterSwitchExpression));
var statements = sectionBuilder.ToImmutableAndFree();
if (arm.Locals.IsEmpty)
{
result.Add(_factory.StatementList(statements));
}
else
{
// Lifetime of these locals is expanded to the entire switch body, as it is possible to
// share them as temps in the decision dag.
outerVariables.AddRange(arm.Locals);
// Note the language scope of the locals, even though they are included for the purposes of
// lifetime analysis in the enclosing scope.
result.Add(new BoundScope(arm.Syntax, arm.Locals, statements));
}
}
_factory.Syntax = node.Syntax;
if (node.DefaultLabel != null)
{
result.Add(_factory.Label(node.DefaultLabel));
if (produceDetailedSequencePoints)
result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForSwitchBody));
var objectType = _factory.SpecialType(SpecialType.System_Object);
var thrownExpression =
(implicitConversionExists(savedInputExpression, objectType) &&
_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, isOptional: true) is MethodSymbol exception1)
? _factory.New(exception1, _factory.Convert(objectType, savedInputExpression)) :
(_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, isOptional: true) is MethodSymbol exception0)
? _factory.New(exception0) :
_factory.New(_factory.WellKnownMethod(WellKnownMember.System_InvalidOperationException__ctor));
result.Add(_factory.Throw(thrownExpression));
}
if (GenerateInstrumentation)
result.Add(_factory.HiddenSequencePoint());
result.Add(_factory.Label(afterSwitchExpression));
if (produceDetailedSequencePoints)
result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForEnclosingStatement));
outerVariables.Add(resultTemp);
outerVariables.AddRange(_tempAllocator.AllTemps());
return _factory.SpillSequence(outerVariables.ToImmutableAndFree(), result.ToImmutableAndFree(), _factory.Local(resultTemp));
bool implicitConversionExists(BoundExpression expression, TypeSymbol type)
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
Conversion c = _localRewriter._compilation.Conversions.ClassifyConversionFromExpression(expression, type, ref discardedUseSiteInfo);
return c.IsImplicit;
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Test/Emit/CodeGen/SwitchTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class SwitchTests : EmitMetadataTestBase
{
#region Functionality tests
[Fact]
public void DefaultOnlySwitch()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
switch (true) {
default:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: dup
IL_0002: call ""void System.Console.Write(int)""
IL_0007: ret
}");
}
[WorkItem(542298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542298")]
[Fact]
public void DefaultOnlySwitch_02()
{
string text = @"using System;
public class Test
{
public static void Main()
{
int status = 2;
switch (status)
{
default: status--; break;
}
string str = ""string"";
switch (str)
{
default: status--; break;
}
Console.WriteLine(status);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main",
@"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: call ""void System.Console.WriteLine(int)""
IL_000a: ret
}"
);
}
[Fact]
public void ConstantIntegerSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
switch (true) {
case true:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: dup
IL_0002: call ""void System.Console.Write(int)""
IL_0007: ret
}"
);
}
[Fact]
public void ConstantNullSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
const string s = null;
switch (s)
{
case null:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: dup
IL_0002: call ""void System.Console.Write(int)""
IL_0007: ret
}"
);
}
[Fact]
public void NonConstantSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
int value = 1;
switch (value) {
case 2:
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.2
IL_0004: bne.un.s IL_0008
IL_0006: ldc.i4.1
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: call ""void System.Console.Write(int)""
IL_000e: ldloc.0
IL_000f: ret
}"
);
}
[Fact]
public void ConstantVariableInCaseLabel()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
int value = 23;
switch (value) {
case kValue:
ret = 0;
break;
default:
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
const int kValue = 23;
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.s 23
IL_0004: ldc.i4.s 23
IL_0006: bne.un.s IL_000c
IL_0008: ldc.i4.0
IL_0009: stloc.0
IL_000a: br.s IL_000e
IL_000c: ldc.i4.1
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: call ""void System.Console.Write(int)""
IL_0014: ldloc.0
IL_0015: ret
}"
);
}
[Fact]
public void DefaultExpressionInLabel()
{
var source = @"
class C
{
static void Main()
{
switch (0)
{
case default(int): return;
}
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void SwitchWith_NoMatchingCaseLabel_And_NoDefaultLabel()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 5;
switch (i)
{
case 1:
case 2:
case 3:
return 1;
case 1001:
case 1002:
case 1003:
return 2;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.5
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: ldc.i4.2
IL_0006: ble.un.s IL_0014
IL_0008: ldloc.0
IL_0009: ldc.i4 0x3e9
IL_000e: sub
IL_000f: ldc.i4.2
IL_0010: ble.un.s IL_0016
IL_0012: br.s IL_0018
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.2
IL_0017: ret
IL_0018: ldc.i4.0
IL_0019: ret
}"
);
}
[Fact]
public void DegenerateSwitch001()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(100);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return 1;
case 100:
goto case 3;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.6
IL_0002: ble.un.s IL_0009
IL_0004: ldarg.0
IL_0005: ldc.i4.s 100
IL_0007: bne.un.s IL_000b
IL_0009: ldc.i4.1
IL_000a: ret
IL_000b: ldc.i4.0
IL_000c: ret
}"
);
}
[Fact]
public void DegenerateSwitch001_Debug()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(100);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return 1;
case 100:
goto case 3;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1", options: TestOptions.DebugExe);
compVerifier.VerifyIL("Test.M", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (int V_0,
int V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: ldc.i4.6
IL_0007: ble.un.s IL_0012
IL_0009: br.s IL_000b
IL_000b: ldloc.0
IL_000c: ldc.i4.s 100
IL_000e: beq.s IL_0016
IL_0010: br.s IL_0018
IL_0012: ldc.i4.1
IL_0013: stloc.2
IL_0014: br.s IL_001c
IL_0016: br.s IL_0012
IL_0018: ldc.i4.0
IL_0019: stloc.2
IL_001a: br.s IL_001c
IL_001c: ldloc.2
IL_001d: ret
}"
);
}
[Fact]
public void DegenerateSwitch002()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(5);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 1:
case 5:
case 6:
case 3:
case 4:
case 2:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ldc.i4.5
IL_0004: bgt.un.s IL_0008
IL_0006: ldc.i4.1
IL_0007: ret
IL_0008: ldc.i4.0
IL_0009: ret
}
"
);
}
[Fact]
public void DegenerateSwitch003()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(4);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case -2:
case -1:
case 0:
case 2:
case 1:
case 4:
case 3:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s -2
IL_0003: sub
IL_0004: ldc.i4.6
IL_0005: bgt.un.s IL_0009
IL_0007: ldc.i4.1
IL_0008: ret
IL_0009: ldc.i4.0
IL_000a: ret
}"
);
}
[Fact]
public void DegenerateSwitch004()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(int.MaxValue - 1);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case int.MinValue + 1:
case int.MinValue:
case int.MaxValue:
case int.MaxValue - 1:
case int.MaxValue - 2:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x80000000
IL_0006: sub
IL_0007: ldc.i4.1
IL_0008: ble.un.s IL_0014
IL_000a: ldarg.0
IL_000b: ldc.i4 0x7ffffffd
IL_0010: sub
IL_0011: ldc.i4.2
IL_0012: bgt.un.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}"
);
}
[Fact]
public void DegenerateSwitch005()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(int.MaxValue + 1L);
Console.Write(ret);
return(ret);
}
public static int M(long i)
{
switch (i)
{
case int.MaxValue:
case int.MaxValue + 1L:
case int.MaxValue + 2L:
case int.MaxValue + 3L:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x7fffffff
IL_0006: conv.i8
IL_0007: sub
IL_0008: ldc.i4.3
IL_0009: conv.i8
IL_000a: bgt.un.s IL_000e
IL_000c: ldc.i4.1
IL_000d: ret
IL_000e: ldc.i4.0
IL_000f: ret
}"
);
}
[Fact]
public void DegenerateSwitch006()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(35);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 1:
case 5:
case 6:
case 3:
case 4:
case 2:
return 1;
case 31:
case 35:
case 36:
case 33:
case 34:
case 32:
return 4;
case 41:
case 45:
case 46:
case 43:
case 44:
case 42:
return 5;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "4");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 30 (0x1e)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ldc.i4.5
IL_0004: ble.un.s IL_0016
IL_0006: ldarg.0
IL_0007: ldc.i4.s 31
IL_0009: sub
IL_000a: ldc.i4.5
IL_000b: ble.un.s IL_0018
IL_000d: ldarg.0
IL_000e: ldc.i4.s 41
IL_0010: sub
IL_0011: ldc.i4.5
IL_0012: ble.un.s IL_001a
IL_0014: br.s IL_001c
IL_0016: ldc.i4.1
IL_0017: ret
IL_0018: ldc.i4.4
IL_0019: ret
IL_001a: ldc.i4.5
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}"
);
}
[Fact]
public void NotDegenerateSwitch006()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(35);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 1:
case 5:
case 6:
case 3:
case 4:
case 2:
return 1;
case 11:
case 15:
case 16:
case 13:
case 14:
case 12:
return 2;
case 21:
case 25:
case 26:
case 23:
case 24:
case 22:
return 3;
case 31:
case 35:
case 36:
case 33:
case 34:
case 32:
return 4;
case 41:
case 45:
case 46:
case 43:
case 44:
case 42:
return 5;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "4");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 206 (0xce)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: switch (
IL_00c2,
IL_00c2,
IL_00c2,
IL_00c2,
IL_00c2,
IL_00c2,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00ca,
IL_00ca,
IL_00ca,
IL_00ca,
IL_00ca,
IL_00ca)
IL_00c0: br.s IL_00cc
IL_00c2: ldc.i4.1
IL_00c3: ret
IL_00c4: ldc.i4.2
IL_00c5: ret
IL_00c6: ldc.i4.3
IL_00c7: ret
IL_00c8: ldc.i4.4
IL_00c9: ret
IL_00ca: ldc.i4.5
IL_00cb: ret
IL_00cc: ldc.i4.0
IL_00cd: ret
}");
}
[Fact]
public void DegenerateSwitch007()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(5);
Console.Write(ret);
return(ret);
}
public static int M(int? i)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return 1;
default:
return 0;
case null:
return 2;
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0019
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldc.i4.6
IL_0013: bgt.un.s IL_0017
IL_0015: ldc.i4.1
IL_0016: ret
IL_0017: ldc.i4.0
IL_0018: ret
IL_0019: ldc.i4.2
IL_001a: ret
}"
);
}
[Fact]
public void DegenerateSwitch008()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M((uint)int.MaxValue + (uint)1);
Console.Write(ret);
return(ret);
}
public static int M(uint i)
{
switch (i)
{
case (uint)int.MaxValue:
case (uint)int.MaxValue + (uint)1:
case (uint)int.MaxValue + (uint)2:
case (uint)int.MaxValue + (uint)3:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x7fffffff
IL_0006: sub
IL_0007: ldc.i4.3
IL_0008: bgt.un.s IL_000c
IL_000a: ldc.i4.1
IL_000b: ret
IL_000c: ldc.i4.0
IL_000d: ret
}"
);
}
[Fact]
public void DegenerateSwitch009()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(uint.MaxValue);
Console.Write(ret);
return(ret);
}
public static int M(uint i)
{
switch (i)
{
case 0:
case 1:
case uint.MaxValue:
case uint.MaxValue - 1:
case uint.MaxValue - 2:
case uint.MaxValue - 3:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: ble.un.s IL_000b
IL_0004: ldarg.0
IL_0005: ldc.i4.s -4
IL_0007: sub
IL_0008: ldc.i4.3
IL_0009: bgt.un.s IL_000d
IL_000b: ldc.i4.1
IL_000c: ret
IL_000d: ldc.i4.0
IL_000e: ret
}"
);
}
[Fact]
public void ByteTypeSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
ret = DoByte();
return(ret);
}
private static int DoByte()
{
int ret = 2;
byte b = 2;
switch (b) {
case 1:
case 2:
ret--;
break;
case 3:
break;
default:
break;
}
switch (b) {
case 1:
case 3:
break;
default:
ret--;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.DoByte",
@"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (int V_0, //ret
byte V_1) //b
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldc.i4.1
IL_0006: sub
IL_0007: ldc.i4.1
IL_0008: ble.un.s IL_0010
IL_000a: ldloc.1
IL_000b: ldc.i4.3
IL_000c: beq.s IL_0014
IL_000e: br.s IL_0014
IL_0010: ldloc.0
IL_0011: ldc.i4.1
IL_0012: sub
IL_0013: stloc.0
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: beq.s IL_0020
IL_0018: ldloc.1
IL_0019: ldc.i4.3
IL_001a: beq.s IL_0020
IL_001c: ldloc.0
IL_001d: ldc.i4.1
IL_001e: sub
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ldloc.0
IL_0027: ret
}"
);
}
[Fact]
public void LongTypeSwitchArgumentExpression()
{
var text = @"
using System;
public class Test
{
public static void Main(string [] args)
{
int ret = 0;
ret = DoLong(2);
Console.Write(ret);
ret = DoLong(4);
Console.Write(ret);
ret = DoLong(42);
Console.Write(ret);
}
private static int DoLong(long b)
{
int ret = 2;
switch (b) {
case 1:
ret++;
break;
case 2:
ret--;
break;
case 3:
break;
case 4:
ret += 7;
break;
default:
ret+=2;
break;
}
return ret;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "194");
compVerifier.VerifyIL("Test.DoLong",
@"
{
// Code size 62 (0x3e)
.maxstack 3
.locals init (int V_0) //ret
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldc.i4.1
IL_0004: conv.i8
IL_0005: sub
IL_0006: dup
IL_0007: ldc.i4.3
IL_0008: conv.i8
IL_0009: ble.un.s IL_000e
IL_000b: pop
IL_000c: br.s IL_0038
IL_000e: conv.u4
IL_000f: switch (
IL_0026,
IL_002c,
IL_003c,
IL_0032)
IL_0024: br.s IL_0038
IL_0026: ldloc.0
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stloc.0
IL_002a: br.s IL_003c
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: sub
IL_002f: stloc.0
IL_0030: br.s IL_003c
IL_0032: ldloc.0
IL_0033: ldc.i4.7
IL_0034: add
IL_0035: stloc.0
IL_0036: br.s IL_003c
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: add
IL_003b: stloc.0
IL_003c: ldloc.0
IL_003d: ret
}"
);
}
[WorkItem(740058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740058")]
[Fact]
public void LongTypeSwitchArgumentExpressionOverflow()
{
var text = @"
using System;
public class Test
{
public static void Main(string[] args)
{
string ret;
ret = DoLong(long.MaxValue);
Console.Write(ret);
ret = DoLong(long.MinValue);
Console.Write(ret);
ret = DoLong(1L);
Console.Write(ret);
ret = DoLong(0L);
Console.Write(ret);
}
private static string DoLong(long b)
{
switch (b)
{
case long.MaxValue:
return ""max"";
case 1L:
return ""one"";
case long.MinValue:
return ""min"";
default:
return ""default"";
}
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "maxminonedefault");
compVerifier.VerifyIL("Test.DoLong",
@"
{
// Code size 53 (0x35)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i8 0x8000000000000000
IL_000a: beq.s IL_0029
IL_000c: ldarg.0
IL_000d: ldc.i4.1
IL_000e: conv.i8
IL_000f: beq.s IL_0023
IL_0011: ldarg.0
IL_0012: ldc.i8 0x7fffffffffffffff
IL_001b: bne.un.s IL_002f
IL_001d: ldstr ""max""
IL_0022: ret
IL_0023: ldstr ""one""
IL_0028: ret
IL_0029: ldstr ""min""
IL_002e: ret
IL_002f: ldstr ""default""
IL_0034: ret
}"
);
}
[Fact]
public void ULongTypeSwitchArgumentExpression()
{
var text = @"
using System;
public class Test
{
public static void Main(string[] args)
{
int ret = 0;
ret = DoULong(0x1000000000000001L);
Console.Write(ret);
}
private static int DoULong(ulong b)
{
int ret = 2;
switch (b)
{
case 0:
ret++;
break;
case 1:
ret--;
break;
case 2:
break;
case 3:
ret += 7;
break;
default:
ret += 40;
break;
}
return ret;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "42");
compVerifier.VerifyIL("Test.DoULong",
@"
{
// Code size 60 (0x3c)
.maxstack 3
.locals init (int V_0) //ret
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: dup
IL_0004: ldc.i4.3
IL_0005: conv.i8
IL_0006: ble.un.s IL_000b
IL_0008: pop
IL_0009: br.s IL_0035
IL_000b: conv.u4
IL_000c: switch (
IL_0023,
IL_0029,
IL_003a,
IL_002f)
IL_0021: br.s IL_0035
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.0
IL_0027: br.s IL_003a
IL_0029: ldloc.0
IL_002a: ldc.i4.1
IL_002b: sub
IL_002c: stloc.0
IL_002d: br.s IL_003a
IL_002f: ldloc.0
IL_0030: ldc.i4.7
IL_0031: add
IL_0032: stloc.0
IL_0033: br.s IL_003a
IL_0035: ldloc.0
IL_0036: ldc.i4.s 40
IL_0038: add
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ret
}"
);
}
[Fact]
public void EnumTypeSwitchArgumentExpressionWithCasts()
{
var text = @"using System;
public class Test
{
enum eTypes {
kFirst,
kSecond,
kThird,
};
public static int Main(string [] args)
{
int ret = 0;
ret = DoEnum();
return(ret);
}
private static int DoEnum()
{
int ret = 2;
eTypes e = eTypes.kSecond;
switch (e) {
case eTypes.kThird:
case eTypes.kSecond:
ret--;
break;
case (eTypes) (-1):
break;
default:
break;
}
switch (e) {
case (eTypes)100:
case (eTypes) (-1):
break;
default:
ret--;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.DoEnum",
@"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (int V_0, //ret
Test.eTypes V_1) //e
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldc.i4.m1
IL_0006: beq.s IL_0012
IL_0008: ldloc.1
IL_0009: ldc.i4.1
IL_000a: sub
IL_000b: ldc.i4.1
IL_000c: bgt.un.s IL_0012
IL_000e: ldloc.0
IL_000f: ldc.i4.1
IL_0010: sub
IL_0011: stloc.0
IL_0012: ldloc.1
IL_0013: ldc.i4.m1
IL_0014: beq.s IL_001f
IL_0016: ldloc.1
IL_0017: ldc.i4.s 100
IL_0019: beq.s IL_001f
IL_001b: ldloc.0
IL_001c: ldc.i4.1
IL_001d: sub
IL_001e: stloc.0
IL_001f: ldloc.0
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ldloc.0
IL_0026: ret
}"
);
}
[Fact]
public void NullableEnumTypeSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
enum eTypes {
kFirst,
kSecond,
kThird,
};
public static int Main(string [] args)
{
int ret = 0;
ret = DoEnum();
return(ret);
}
private static int DoEnum()
{
int ret = 3;
eTypes? e = eTypes.kSecond;
switch (e)
{
case eTypes.kThird:
case eTypes.kSecond:
ret--;
break;
default:
break;
}
switch (e)
{
case null:
case (eTypes) (-1):
break;
default:
ret--;
break;
}
e = null;
switch (e)
{
case null:
ret--;
break;
case (eTypes) (-1):
case eTypes.kThird:
case eTypes.kSecond:
default:
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.DoEnum", @"
{
// Code size 109 (0x6d)
.maxstack 2
.locals init (int V_0, //ret
Test.eTypes? V_1, //e
Test.eTypes V_2)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.1
IL_0005: call ""Test.eTypes?..ctor(Test.eTypes)""
IL_000a: ldloca.s V_1
IL_000c: call ""bool Test.eTypes?.HasValue.get""
IL_0011: brfalse.s IL_0025
IL_0013: ldloca.s V_1
IL_0015: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()""
IL_001a: stloc.2
IL_001b: ldloc.2
IL_001c: ldc.i4.1
IL_001d: sub
IL_001e: ldc.i4.1
IL_001f: bgt.un.s IL_0025
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: sub
IL_0024: stloc.0
IL_0025: ldloca.s V_1
IL_0027: call ""bool Test.eTypes?.HasValue.get""
IL_002c: brfalse.s IL_003c
IL_002e: ldloca.s V_1
IL_0030: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()""
IL_0035: ldc.i4.m1
IL_0036: beq.s IL_003c
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: sub
IL_003b: stloc.0
IL_003c: ldloca.s V_1
IL_003e: initobj ""Test.eTypes?""
IL_0044: ldloca.s V_1
IL_0046: call ""bool Test.eTypes?.HasValue.get""
IL_004b: brfalse.s IL_0061
IL_004d: ldloca.s V_1
IL_004f: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()""
IL_0054: stloc.2
IL_0055: ldloc.2
IL_0056: ldc.i4.m1
IL_0057: beq.s IL_0065
IL_0059: ldloc.2
IL_005a: ldc.i4.1
IL_005b: sub
IL_005c: ldc.i4.1
IL_005d: ble.un.s IL_0065
IL_005f: br.s IL_0065
IL_0061: ldloc.0
IL_0062: ldc.i4.1
IL_0063: sub
IL_0064: stloc.0
IL_0065: ldloc.0
IL_0066: call ""void System.Console.Write(int)""
IL_006b: ldloc.0
IL_006c: ret
}");
}
[Fact]
public void SwitchSectionWithGotoNonSwitchLabel()
{
var text = @"
class Test
{
public static int Main()
{
int ret = 1;
switch (10)
{
case 123: // No unreachable code warning here
mylabel:
--ret;
break;
case 9: // No unreachable code warning here
case 10:
case 11: // No unreachable code warning here
goto mylabel;
}
System.Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics();
compVerifier.VerifyIL("Test.Main",
@"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""void System.Console.Write(int)""
IL_000c: ldloc.0
IL_000d: ret
}"
);
}
[Fact]
public void SwitchSectionWithGotoNonSwitchLabel_02()
{
var text = @"class Test
{
delegate void D();
public static void Main()
{
int i = 0;
switch (10)
{
case 5:
goto mylabel;
case 10:
goto case 5;
case 15:
mylabel:
D d1 = delegate() { System.Console.Write(i); };
d1();
return;
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (Test.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Test.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.0
IL_0008: stfld ""int Test.<>c__DisplayClass1_0.i""
IL_000d: ldloc.0
IL_000e: ldftn ""void Test.<>c__DisplayClass1_0.<Main>b__0()""
IL_0014: newobj ""Test.D..ctor(object, System.IntPtr)""
IL_0019: callvirt ""void Test.D.Invoke()""
IL_001e: ret
}
"
);
}
[Fact]
public void SwitchSectionWithReturnStatement()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 3;
for (int i = 0; i < 3; i++) {
switch (i) {
case 1:
case 0:
case 2:
ret--;
break;
default:
Console.Write(1);
return(1);
}
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (int V_0, //ret
int V_1) //i
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_001c
IL_0006: ldloc.1
IL_0007: ldc.i4.2
IL_0008: bgt.un.s IL_0010
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: sub
IL_000d: stloc.0
IL_000e: br.s IL_0018
IL_0010: ldc.i4.1
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.1
IL_0017: ret
IL_0018: ldloc.1
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.3
IL_001e: blt.s IL_0006
IL_0020: ldloc.0
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ldloc.0
IL_0027: ret
}"
);
}
[Fact]
public void SwitchSectionWithReturnStatement_02()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 5;
switch (i)
{
case 1:
return 1;
}
return 0;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.5
IL_0001: ldc.i4.1
IL_0002: bne.un.s IL_0006
IL_0004: ldc.i4.1
IL_0005: ret
IL_0006: ldc.i4.0
IL_0007: ret
}"
);
}
[Fact]
public void CaseLabelWithTypeCastToGoverningType()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 5;
switch (i)
{
case (int) 5.0f:
return 0;
default:
return 1;
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: bne.un.s IL_0006
IL_0004: ldc.i4.0
IL_0005: ret
IL_0006: ldc.i4.1
IL_0007: ret
}"
);
}
[Fact]
public void SwitchSectionWithTryFinally()
{
var text = @"using System;
class Class1
{
static int Main()
{
int j = 0;
int i = 3;
switch (j)
{
case 0:
try
{
i = 0;
}
catch
{
i = 1;
}
finally
{
j = 2;
}
break;
default:
i = 2;
break;
}
Console.Write(i);
return i;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Class1.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.0
IL_0001: ldc.i4.3
IL_0002: stloc.0
IL_0003: brtrue.s IL_0010
IL_0005: nop
.try
{
.try
{
IL_0006: ldc.i4.0
IL_0007: stloc.0
IL_0008: leave.s IL_0012
}
catch object
{
IL_000a: pop
IL_000b: ldc.i4.1
IL_000c: stloc.0
IL_000d: leave.s IL_0012
}
}
finally
{
IL_000f: endfinally
}
IL_0010: ldc.i4.2
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: call ""void System.Console.Write(int)""
IL_0018: ldloc.0
IL_0019: ret
}"
);
}
[Fact]
public void MultipleSwitchSectionsWithGotoCase()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int ret = 6;
switch (ret) {
case 0:
ret--; // 2
Console.Write(""case 0: "");
Console.WriteLine(ret);
goto case 9999;
case 2:
ret--; // 4
Console.Write(""case 2: "");
Console.WriteLine(ret);
goto case 255;
case 6: // start here
ret--; // 5
Console.Write(""case 5: "");
Console.WriteLine(ret);
goto case 2;
case 9999:
ret--; // 1
Console.Write(""case 9999: "");
Console.WriteLine(ret);
goto default;
case 0xff:
ret--; // 3
Console.Write(""case 0xff: "");
Console.WriteLine(ret);
goto case 0;
default:
ret--;
Console.Write(""Default: "");
Console.WriteLine(ret);
if (ret > 0) {
goto case -1;
}
break;
case -1:
ret = 999;
Console.WriteLine(""case -1: "");
Console.Write(ret);
break;
}
return(ret);
}
}";
string expectedOutput = @"case 5: 5
case 2: 4
case 0xff: 3
case 0: 2
case 9999: 1
Default: 0
0";
var compVerifier = CompileAndVerify(text, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Test.M",
@"
{
// Code size 215 (0xd7)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.6
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.6
IL_0004: bgt.s IL_0027
IL_0006: ldloc.0
IL_0007: ldc.i4.m1
IL_0008: sub
IL_0009: switch (
IL_00bf,
IL_0039,
IL_00a7,
IL_004f)
IL_001e: ldloc.0
IL_001f: ldc.i4.6
IL_0020: beq.s IL_0065
IL_0022: br IL_00a7
IL_0027: ldloc.0
IL_0028: ldc.i4 0xff
IL_002d: beq.s IL_0091
IL_002f: ldloc.0
IL_0030: ldc.i4 0x270f
IL_0035: beq.s IL_007b
IL_0037: br.s IL_00a7
IL_0039: ldloc.0
IL_003a: ldc.i4.1
IL_003b: sub
IL_003c: stloc.0
IL_003d: ldstr ""case 0: ""
IL_0042: call ""void System.Console.Write(string)""
IL_0047: ldloc.0
IL_0048: call ""void System.Console.WriteLine(int)""
IL_004d: br.s IL_007b
IL_004f: ldloc.0
IL_0050: ldc.i4.1
IL_0051: sub
IL_0052: stloc.0
IL_0053: ldstr ""case 2: ""
IL_0058: call ""void System.Console.Write(string)""
IL_005d: ldloc.0
IL_005e: call ""void System.Console.WriteLine(int)""
IL_0063: br.s IL_0091
IL_0065: ldloc.0
IL_0066: ldc.i4.1
IL_0067: sub
IL_0068: stloc.0
IL_0069: ldstr ""case 5: ""
IL_006e: call ""void System.Console.Write(string)""
IL_0073: ldloc.0
IL_0074: call ""void System.Console.WriteLine(int)""
IL_0079: br.s IL_004f
IL_007b: ldloc.0
IL_007c: ldc.i4.1
IL_007d: sub
IL_007e: stloc.0
IL_007f: ldstr ""case 9999: ""
IL_0084: call ""void System.Console.Write(string)""
IL_0089: ldloc.0
IL_008a: call ""void System.Console.WriteLine(int)""
IL_008f: br.s IL_00a7
IL_0091: ldloc.0
IL_0092: ldc.i4.1
IL_0093: sub
IL_0094: stloc.0
IL_0095: ldstr ""case 0xff: ""
IL_009a: call ""void System.Console.Write(string)""
IL_009f: ldloc.0
IL_00a0: call ""void System.Console.WriteLine(int)""
IL_00a5: br.s IL_0039
IL_00a7: ldloc.0
IL_00a8: ldc.i4.1
IL_00a9: sub
IL_00aa: stloc.0
IL_00ab: ldstr ""Default: ""
IL_00b0: call ""void System.Console.Write(string)""
IL_00b5: ldloc.0
IL_00b6: call ""void System.Console.WriteLine(int)""
IL_00bb: ldloc.0
IL_00bc: ldc.i4.0
IL_00bd: ble.s IL_00d5
IL_00bf: ldc.i4 0x3e7
IL_00c4: stloc.0
IL_00c5: ldstr ""case -1: ""
IL_00ca: call ""void System.Console.WriteLine(string)""
IL_00cf: ldloc.0
IL_00d0: call ""void System.Console.Write(int)""
IL_00d5: ldloc.0
IL_00d6: ret
}"
);
}
[Fact]
public void Switch_TestSwitchBuckets_01()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 0;
// Expected switch buckets: (10, 12, 14) (1000) (2000, 2001, 2005, 2008, 2009, 2010)
switch (i)
{
case 10:
case 2000:
case 12:
return 1;
case 2001:
case 14:
return 2;
case 1000:
case 2010:
case 2008:
return 3;
case 2005:
case 2009:
return 2;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 107 (0x6b)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.s 10
IL_0005: sub
IL_0006: switch (
IL_0061,
IL_0069,
IL_0061,
IL_0069,
IL_0063)
IL_001f: ldloc.0
IL_0020: ldc.i4 0x3e8
IL_0025: beq.s IL_0065
IL_0027: ldloc.0
IL_0028: ldc.i4 0x7d0
IL_002d: sub
IL_002e: switch (
IL_0061,
IL_0063,
IL_0069,
IL_0069,
IL_0069,
IL_0067,
IL_0069,
IL_0069,
IL_0065,
IL_0067,
IL_0065)
IL_005f: br.s IL_0069
IL_0061: ldc.i4.1
IL_0062: ret
IL_0063: ldc.i4.2
IL_0064: ret
IL_0065: ldc.i4.3
IL_0066: ret
IL_0067: ldc.i4.2
IL_0068: ret
IL_0069: ldc.i4.0
IL_006a: ret
}"
);
}
[Fact]
public void Switch_TestSwitchBuckets_02()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 0;
// Expected switch buckets: (10, 12, 14) (1000) (2000, 2001) (2008, 2009, 2010)
switch (i)
{
case 10:
case 2000:
case 12:
return 1;
case 2001:
case 14:
return 2;
case 1000:
case 2010:
case 2008:
return 3;
case 2009:
return 2;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 101 (0x65)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4 0x3e8
IL_0008: bgt.s IL_0031
IL_000a: ldloc.0
IL_000b: ldc.i4.s 10
IL_000d: sub
IL_000e: switch (
IL_005b,
IL_0063,
IL_005b,
IL_0063,
IL_005d)
IL_0027: ldloc.0
IL_0028: ldc.i4 0x3e8
IL_002d: beq.s IL_005f
IL_002f: br.s IL_0063
IL_0031: ldloc.0
IL_0032: ldc.i4 0x7d0
IL_0037: beq.s IL_005b
IL_0039: ldloc.0
IL_003a: ldc.i4 0x7d1
IL_003f: beq.s IL_005d
IL_0041: ldloc.0
IL_0042: ldc.i4 0x7d8
IL_0047: sub
IL_0048: switch (
IL_005f,
IL_0061,
IL_005f)
IL_0059: br.s IL_0063
IL_005b: ldc.i4.1
IL_005c: ret
IL_005d: ldc.i4.2
IL_005e: ret
IL_005f: ldc.i4.3
IL_0060: ret
IL_0061: ldc.i4.2
IL_0062: ret
IL_0063: ldc.i4.0
IL_0064: ret
}"
);
}
[WorkItem(542398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542398")]
[Fact]
public void MaxValueGotoCaseExpression()
{
var text = @"
class Program
{
static void Main(string[] args)
{
ulong a = 0;
switch (a)
{
case long.MaxValue:
goto case ulong.MaxValue;
case ulong.MaxValue:
break;
}
}
}
";
CompileAndVerify(text, expectedOutput: "");
}
[WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")]
[Fact()]
public void NullableAsSwitchExpression()
{
var text = @"using System;
class Program
{
static void Main()
{
sbyte? local = null;
switch (local)
{
case null:
Console.Write(""null "");
break;
case 1:
Console.Write(""1 "");
break;
}
Goo(1);
}
static void Goo(sbyte? p)
{
switch (p)
{
case 1:
Console.Write(""1 "");
break;
case null:
Console.Write(""null "");
break;
}
}
}
";
var verifier = CompileAndVerify(text, expectedOutput: "null 1");
verifier.VerifyIL("Program.Main", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (sbyte? V_0) //local
IL_0000: ldloca.s V_0
IL_0002: initobj ""sbyte?""
IL_0008: ldloca.s V_0
IL_000a: call ""bool sbyte?.HasValue.get""
IL_000f: brfalse.s IL_001d
IL_0011: ldloca.s V_0
IL_0013: call ""sbyte sbyte?.GetValueOrDefault()""
IL_0018: ldc.i4.1
IL_0019: beq.s IL_0029
IL_001b: br.s IL_0033
IL_001d: ldstr ""null ""
IL_0022: call ""void System.Console.Write(string)""
IL_0027: br.s IL_0033
IL_0029: ldstr ""1 ""
IL_002e: call ""void System.Console.Write(string)""
IL_0033: ldc.i4.1
IL_0034: conv.i1
IL_0035: newobj ""sbyte?..ctor(sbyte)""
IL_003a: call ""void Program.Goo(sbyte?)""
IL_003f: ret
}");
}
[WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")]
[Fact()]
public void NullableAsSwitchExpression_02()
{
var text = @"using System;
class Program
{
static void Main()
{
Goo(null);
Goo(100);
}
static void Goo(short? p)
{
switch (p)
{
case null:
Console.Write(""null "");
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 100:
Console.Write(""100 "");
break;
case 101:
break;
case 103:
break;
case 1001:
break;
case 1002:
break;
case 1003:
break;
}
switch (p)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 101:
break;
case 103:
break;
case 1001:
break;
case 1002:
break;
case 1003:
break;
default:
Console.Write(""default "");
break;
}
switch (p)
{
case 1:
Console.Write(""FAIL"");
break;
case 2:
Console.Write(""FAIL"");
break;
case 3:
Console.Write(""FAIL"");
break;
case 101:
Console.Write(""FAIL"");
break;
case 103:
Console.Write(""FAIL"");
break;
case 1001:
Console.Write(""FAIL"");
break;
case 1002:
Console.Write(""FAIL"");
break;
case 1003:
Console.Write(""FAIL"");
break;
}
}
}
";
var verifier = CompileAndVerify(text, expectedOutput: "null default 100 default ");
verifier.VerifyIL("Program.Goo", @"
{
// Code size 367 (0x16f)
.maxstack 2
.locals init (short V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool short?.HasValue.get""
IL_0007: brfalse.s IL_0058
IL_0009: ldarga.s V_0
IL_000b: call ""short short?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldc.i4.1
IL_0013: sub
IL_0014: switch (
IL_006e,
IL_006e,
IL_006e)
IL_0025: ldloc.0
IL_0026: ldc.i4.s 100
IL_0028: sub
IL_0029: switch (
IL_0064,
IL_006e,
IL_006e,
IL_006e)
IL_003e: ldloc.0
IL_003f: ldc.i4 0x3e9
IL_0044: sub
IL_0045: switch (
IL_006e,
IL_006e,
IL_006e)
IL_0056: br.s IL_006e
IL_0058: ldstr ""null ""
IL_005d: call ""void System.Console.Write(string)""
IL_0062: br.s IL_006e
IL_0064: ldstr ""100 ""
IL_0069: call ""void System.Console.Write(string)""
IL_006e: ldarga.s V_0
IL_0070: call ""bool short?.HasValue.get""
IL_0075: brfalse.s IL_00bc
IL_0077: ldarga.s V_0
IL_0079: call ""short short?.GetValueOrDefault()""
IL_007e: stloc.0
IL_007f: ldloc.0
IL_0080: ldc.i4.s 101
IL_0082: bgt.s IL_009f
IL_0084: ldloc.0
IL_0085: ldc.i4.1
IL_0086: sub
IL_0087: switch (
IL_00c6,
IL_00c6,
IL_00c6)
IL_0098: ldloc.0
IL_0099: ldc.i4.s 101
IL_009b: beq.s IL_00c6
IL_009d: br.s IL_00bc
IL_009f: ldloc.0
IL_00a0: ldc.i4.s 103
IL_00a2: beq.s IL_00c6
IL_00a4: ldloc.0
IL_00a5: ldc.i4 0x3e9
IL_00aa: sub
IL_00ab: switch (
IL_00c6,
IL_00c6,
IL_00c6)
IL_00bc: ldstr ""default ""
IL_00c1: call ""void System.Console.Write(string)""
IL_00c6: ldarga.s V_0
IL_00c8: call ""bool short?.HasValue.get""
IL_00cd: brfalse IL_016e
IL_00d2: ldarga.s V_0
IL_00d4: call ""short short?.GetValueOrDefault()""
IL_00d9: stloc.0
IL_00da: ldloc.0
IL_00db: ldc.i4.s 101
IL_00dd: bgt.s IL_00f9
IL_00df: ldloc.0
IL_00e0: ldc.i4.1
IL_00e1: sub
IL_00e2: switch (
IL_0117,
IL_0122,
IL_012d)
IL_00f3: ldloc.0
IL_00f4: ldc.i4.s 101
IL_00f6: beq.s IL_0138
IL_00f8: ret
IL_00f9: ldloc.0
IL_00fa: ldc.i4.s 103
IL_00fc: beq.s IL_0143
IL_00fe: ldloc.0
IL_00ff: ldc.i4 0x3e9
IL_0104: sub
IL_0105: switch (
IL_014e,
IL_0159,
IL_0164)
IL_0116: ret
IL_0117: ldstr ""FAIL""
IL_011c: call ""void System.Console.Write(string)""
IL_0121: ret
IL_0122: ldstr ""FAIL""
IL_0127: call ""void System.Console.Write(string)""
IL_012c: ret
IL_012d: ldstr ""FAIL""
IL_0132: call ""void System.Console.Write(string)""
IL_0137: ret
IL_0138: ldstr ""FAIL""
IL_013d: call ""void System.Console.Write(string)""
IL_0142: ret
IL_0143: ldstr ""FAIL""
IL_0148: call ""void System.Console.Write(string)""
IL_014d: ret
IL_014e: ldstr ""FAIL""
IL_0153: call ""void System.Console.Write(string)""
IL_0158: ret
IL_0159: ldstr ""FAIL""
IL_015e: call ""void System.Console.Write(string)""
IL_0163: ret
IL_0164: ldstr ""FAIL""
IL_0169: call ""void System.Console.Write(string)""
IL_016e: ret
}");
}
[Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")]
public void SwitchOnNullableInt64WithInt32Label()
{
var text = @"public static class C
{
public static bool F(long? x)
{
switch (x)
{
case 1:
return true;
default:
return false;
}
}
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "True");
compVerifier.VerifyIL("C.F(long?)",
@"{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool long?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""long long?.GetValueOrDefault()""
IL_0010: ldc.i4.1
IL_0011: conv.i8
IL_0012: bne.un.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}"
);
}
[Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")]
public void SwitchOnNullableWithNonConstant()
{
var text = @"public static class C
{
public static bool F(int? x)
{
int i = 4;
switch (x)
{
case i:
return true;
default:
return false;
}
}
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compilation = base.CreateCSharpCompilation(text);
compilation.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case i:
Diagnostic(ErrorCode.ERR_ConstantExpected, "i").WithLocation(8, 18)
);
}
[Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")]
public void SwitchOnNullableWithNonCompatibleType()
{
var text = @"public static class C
{
public static bool F(int? x)
{
switch (x)
{
case default(System.DateTime):
return true;
default:
return false;
}
}
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compilation = base.CreateCSharpCompilation(text);
// (7,18): error CS0029: Cannot implicitly convert type 'System.DateTime' to 'int?'
// case default(System.DateTime):
var expected = Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(System.DateTime)").WithArguments("System.DateTime", "int?");
compilation.VerifyDiagnostics(expected);
}
[Fact]
public void SwitchOnNullableInt64WithInt32LabelWithEnum()
{
var text = @"public static class C
{
public static bool F(long? x)
{
switch (x)
{
case (int)Goo.X:
return true;
default:
return false;
}
}
public enum Goo : int { X = 1 }
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "True");
compVerifier.VerifyIL("C.F(long?)",
@"{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool long?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""long long?.GetValueOrDefault()""
IL_0010: ldc.i4.1
IL_0011: conv.i8
IL_0012: bne.un.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}"
);
}
// TODO: Add more targeted tests for verifying switch bucketing
#region "String tests"
[Fact]
public void StringTypeSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
string s = ""hello"";
switch (s)
{
default:
return 1;
case null:
return 1;
case ""hello"":
return 0;
}
return 1;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (25,5): warning CS0162: Unreachable code detected
// return 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "return"));
compVerifier.VerifyIL("Test.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //s
IL_0000: ldstr ""hello""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brfalse.s IL_0018
IL_0009: ldloc.0
IL_000a: ldstr ""hello""
IL_000f: call ""bool string.op_Equality(string, string)""
IL_0014: brtrue.s IL_001a
IL_0016: ldc.i4.1
IL_0017: ret
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldc.i4.0
IL_001b: ret
}"
);
// We shouldn't generate a string hash synthesized method if we are generating non hash string switch
VerifySynthesizedStringHashMethod(compVerifier, expected: false);
}
[Fact]
public void StringSwitch_SwitchOnNull()
{
var text = @"using System;
public class Test
{
public static int Main(string[] args)
{
string s = null;
int ret = 0;
switch (s)
{
case null + ""abc"":
ret = 1;
break;
case null + ""def"":
ret = 1;
break;
}
Console.Write(ret);
return ret;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (string V_0, //s
int V_1) //ret
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: ldstr ""abc""
IL_000a: call ""bool string.op_Equality(string, string)""
IL_000f: brtrue.s IL_0020
IL_0011: ldloc.0
IL_0012: ldstr ""def""
IL_0017: call ""bool string.op_Equality(string, string)""
IL_001c: brtrue.s IL_0024
IL_001e: br.s IL_0026
IL_0020: ldc.i4.1
IL_0021: stloc.1
IL_0022: br.s IL_0026
IL_0024: ldc.i4.1
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: call ""void System.Console.Write(int)""
IL_002c: ldloc.1
IL_002d: ret
}"
);
// We shouldn't generate a string hash synthesized method if we are generating non hash string switch
VerifySynthesizedStringHashMethod(compVerifier, expected: false);
}
[Fact]
[WorkItem(546632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546632")]
public void StringSwitch_HashTableSwitch_01()
{
var text = @"using System;
class Test
{
public static bool M(string test)
{
string value = """";
if (test != null && test.IndexOf(""C#"") != -1)
test = test.Remove(0, 2);
switch (test)
{
case null:
value = null;
break;
case """":
break;
case ""_"":
value = ""_"";
break;
case ""W"":
value = ""W"";
break;
case ""B"":
value = ""B"";
break;
case ""C"":
value = ""C"";
break;
case ""<"":
value = ""<"";
break;
case ""T"":
value = ""T"";
break;
case ""M"":
value = ""M"";
break;
}
return (value == test);
}
public static void Main()
{
bool success = Test.M(""C#"");
success &= Test.M(""C#_"");
success &= Test.M(""C#W"");
success &= Test.M(""C#B"");
success &= Test.M(""C#C"");
success &= Test.M(""C#<"");
success &= Test.M(""C#T"");
success &= Test.M(""C#M"");
success &= Test.M(null);
Console.WriteLine(success);
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "True");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 365 (0x16d)
.maxstack 3
.locals init (string V_0, //value
uint V_1)
IL_0000: ldstr """"
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: brfalse.s IL_0021
IL_0009: ldarg.0
IL_000a: ldstr ""C#""
IL_000f: callvirt ""int string.IndexOf(string)""
IL_0014: ldc.i4.m1
IL_0015: beq.s IL_0021
IL_0017: ldarg.0
IL_0018: ldc.i4.0
IL_0019: ldc.i4.2
IL_001a: callvirt ""string string.Remove(int, int)""
IL_001f: starg.s V_0
IL_0021: ldarg.0
IL_0022: brfalse IL_012b
IL_0027: ldarg.0
IL_0028: call ""ComputeStringHash""
IL_002d: stloc.1
IL_002e: ldloc.1
IL_002f: ldc.i4 0xc70bfb85
IL_0034: bgt.un.s IL_006e
IL_0036: ldloc.1
IL_0037: ldc.i4 0x811c9dc5
IL_003c: bgt.un.s IL_0056
IL_003e: ldloc.1
IL_003f: ldc.i4 0x390caefb
IL_0044: beq IL_00fe
IL_0049: ldloc.1
IL_004a: ldc.i4 0x811c9dc5
IL_004f: beq.s IL_00a6
IL_0051: br IL_0165
IL_0056: ldloc.1
IL_0057: ldc.i4 0xc60bf9f2
IL_005c: beq IL_00ef
IL_0061: ldloc.1
IL_0062: ldc.i4 0xc70bfb85
IL_0067: beq.s IL_00e0
IL_0069: br IL_0165
IL_006e: ldloc.1
IL_006f: ldc.i4 0xd10c0b43
IL_0074: bgt.un.s IL_0091
IL_0076: ldloc.1
IL_0077: ldc.i4 0xc80bfd18
IL_007c: beq IL_011c
IL_0081: ldloc.1
IL_0082: ldc.i4 0xd10c0b43
IL_0087: beq IL_010d
IL_008c: br IL_0165
IL_0091: ldloc.1
IL_0092: ldc.i4 0xd20c0cd6
IL_0097: beq.s IL_00ce
IL_0099: ldloc.1
IL_009a: ldc.i4 0xda0c196e
IL_009f: beq.s IL_00bc
IL_00a1: br IL_0165
IL_00a6: ldarg.0
IL_00a7: brfalse IL_0165
IL_00ac: ldarg.0
IL_00ad: call ""int string.Length.get""
IL_00b2: brfalse IL_0165
IL_00b7: br IL_0165
IL_00bc: ldarg.0
IL_00bd: ldstr ""_""
IL_00c2: call ""bool string.op_Equality(string, string)""
IL_00c7: brtrue.s IL_012f
IL_00c9: br IL_0165
IL_00ce: ldarg.0
IL_00cf: ldstr ""W""
IL_00d4: call ""bool string.op_Equality(string, string)""
IL_00d9: brtrue.s IL_0137
IL_00db: br IL_0165
IL_00e0: ldarg.0
IL_00e1: ldstr ""B""
IL_00e6: call ""bool string.op_Equality(string, string)""
IL_00eb: brtrue.s IL_013f
IL_00ed: br.s IL_0165
IL_00ef: ldarg.0
IL_00f0: ldstr ""C""
IL_00f5: call ""bool string.op_Equality(string, string)""
IL_00fa: brtrue.s IL_0147
IL_00fc: br.s IL_0165
IL_00fe: ldarg.0
IL_00ff: ldstr ""<""
IL_0104: call ""bool string.op_Equality(string, string)""
IL_0109: brtrue.s IL_014f
IL_010b: br.s IL_0165
IL_010d: ldarg.0
IL_010e: ldstr ""T""
IL_0113: call ""bool string.op_Equality(string, string)""
IL_0118: brtrue.s IL_0157
IL_011a: br.s IL_0165
IL_011c: ldarg.0
IL_011d: ldstr ""M""
IL_0122: call ""bool string.op_Equality(string, string)""
IL_0127: brtrue.s IL_015f
IL_0129: br.s IL_0165
IL_012b: ldnull
IL_012c: stloc.0
IL_012d: br.s IL_0165
IL_012f: ldstr ""_""
IL_0134: stloc.0
IL_0135: br.s IL_0165
IL_0137: ldstr ""W""
IL_013c: stloc.0
IL_013d: br.s IL_0165
IL_013f: ldstr ""B""
IL_0144: stloc.0
IL_0145: br.s IL_0165
IL_0147: ldstr ""C""
IL_014c: stloc.0
IL_014d: br.s IL_0165
IL_014f: ldstr ""<""
IL_0154: stloc.0
IL_0155: br.s IL_0165
IL_0157: ldstr ""T""
IL_015c: stloc.0
IL_015d: br.s IL_0165
IL_015f: ldstr ""M""
IL_0164: stloc.0
IL_0165: ldloc.0
IL_0166: ldarg.0
IL_0167: call ""bool string.op_Equality(string, string)""
IL_016c: ret
}"
);
// Verify string hash synthesized method for hash table switch
VerifySynthesizedStringHashMethod(compVerifier, expected: true);
// verify that hash method is internal:
var reference = compVerifier.Compilation.EmitToImageReference();
var comp = CSharpCompilation.Create("Name", references: new[] { reference }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
var pid = ((NamedTypeSymbol)comp.GlobalNamespace.GetMembers().Single(s => s.Name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
var member = pid.GetMembers(PrivateImplementationDetails.SynthesizedStringHashFunctionName).Single();
Assert.Equal(Accessibility.Internal, member.DeclaredAccessibility);
}
[Fact]
public void StringSwitch_HashTableSwitch_02()
{
var text = @"
using System;
using System.Text;
class Test
{
public static bool Switcheroo(string test)
{
string value = """";
if (test.IndexOf(""C#"") != -1)
test = test.Remove(0, 2);
switch (test)
{
case ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"":
value = ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"";
break;
case ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"":
value = ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"";
break;
case ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"":
value = ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"";
break;
case ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"":
value = ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"";
break;
case ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"":
value = ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"";
break;
case ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"":
value = ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"";
break;
case ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"":
value = ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"";
break;
case ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"":
value = ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"";
break;
case ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"":
value = ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"";
break;
case ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"":
value = ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"";
break;
case "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"":
value = "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"";
break;
case ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"":
value = ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"";
break;
case ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"":
value = ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"";
break;
case ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"":
value = ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"";
break;
case ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"":
value = ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"";
break;
case ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"":
value = ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"";
break;
case ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"":
value = ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"";
break;
case ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"":
value = ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"";
break;
case ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"":
value = ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"";
break;
case ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"":
value = ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"";
break;
case ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"":
value = ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"";
break;
case ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"":
value = ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"";
break;
case ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"":
value = ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"";
break;
case ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"":
value = ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"";
break;
}
return (value == test);
}
public static void Main()
{
string status = ""PASS"";
bool retval;
retval = Test.Switcheroo(""C#N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#>AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#a@=FkgImdk5<Wn0DRYa?m0<F0JT4kha;H:HIZ;6C"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Zbk^]59O<<GHe8MjRMOh4]c3@RQ?hU>^G81cOMW:"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#hP<l25H@W60UF4bYYDU]0AjIE6oCQ^k66F9gNJ`Q"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#XS9dCIb;9T`;JJ1Jmimba@@0[l[B=BgDhKZ05DO2"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#JbMbko?;e@1XLU>:=c_Vg>0YTJ7Qd]6KLh26miBV"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#IW3:>L<H<kf:AS2ZYDGaE`?^HZY_D]cRO[lNjd4;"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#NC>J^E3;VJ`nKSjVbJ_Il^^@0Xof9CFA2I1I^9c>"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#TfjQOCnAhM8[T3JUbLlQMS=`F=?:FPT3=X0Q]aj:"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#H_6fHA8OKO><TYDXiIg[Qed<=71KC>^6cTMOjT]d"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#jN>cSCF0?I<1RSQ^g^HnBABPhUc>5Y`ahlY9HS]5"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#V;`Q_kEGIX=Mh9=UVF[Q@Q=QTT@oC]IRF]<bA1R9"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#7DKT?2VIk2^XUJ>C]G_IDe?299DJTD>1RO18Ql>F"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#U`^]IeJC;o^90V=5<ToV<Gj26hnZLolffohc8iZX"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#9S?>A?E>gBl_dC[iCiiNnW7<BP;eGHf>8ceTGZ6C"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#ALLhjN7]XVBBA=VcYM8iWg^FGiG[QG03dlKYnIAe"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#6<]i]EllPZf6mnAM0D1;0eP6_G1HmRSi?`1o[a_a"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#]5Tb^6:NB]>ahEoWI5U9N5beS<?da]A]fL08AelQ"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#KhPBV8=H?G^Hmaaf^n<GcoI8eC1O_0]579;MY=81"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#A8iN_OFUPIcWac0^LU1;^HaEX[_E]<8h3N:Hm_XX"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Y811aKWEJYcX6Y1aj_I]O7TXP5j_lo;71kAiB:;:"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#P@ok2DgbUDeLVA:POd`B_S@2Ocg99VQBZ<LI<gd1"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#9V84FSRoD9453VdERM86a6B12VeN]hNNU:]XE`W9"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Tegah0mKcWmFhaH0K0oSjKGkmH8gDEF3SBVd2H1P"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#=II;VADkVKf7JV55ca5oUjkPaWSY7`LXTlgTV4^W"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#k7XPoXNhd8P0V7@Sd5ohO>h7io3Pl[J[8g:[_da^"");
if (retval) status = ""FAIL"";
Console.Write(status);
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "PASS");
compVerifier.VerifyIL("Test.Switcheroo", @"
{
// Code size 1115 (0x45b)
.maxstack 3
.locals init (string V_0, //value
uint V_1)
IL_0000: ldstr """"
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldstr ""C#""
IL_000c: callvirt ""int string.IndexOf(string)""
IL_0011: ldc.i4.m1
IL_0012: beq.s IL_001e
IL_0014: ldarg.0
IL_0015: ldc.i4.0
IL_0016: ldc.i4.2
IL_0017: callvirt ""string string.Remove(int, int)""
IL_001c: starg.s V_0
IL_001e: ldarg.0
IL_001f: call ""ComputeStringHash""
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: ldc.i4 0xb2f29419
IL_002b: bgt.un IL_00e0
IL_0030: ldloc.1
IL_0031: ldc.i4 0x619348d8
IL_0036: bgt.un.s IL_008c
IL_0038: ldloc.1
IL_0039: ldc.i4 0x36758e37
IL_003e: bgt.un.s IL_0066
IL_0040: ldloc.1
IL_0041: ldc.i4 0x144fd20d
IL_0046: beq IL_02ae
IL_004b: ldloc.1
IL_004c: ldc.i4 0x14ca99e2
IL_0051: beq IL_025a
IL_0056: ldloc.1
IL_0057: ldc.i4 0x36758e37
IL_005c: beq IL_0206
IL_0061: br IL_0453
IL_0066: ldloc.1
IL_0067: ldc.i4 0x5398a778
IL_006c: beq IL_021b
IL_0071: ldloc.1
IL_0072: ldc.i4 0x616477cf
IL_0077: beq IL_01b2
IL_007c: ldloc.1
IL_007d: ldc.i4 0x619348d8
IL_0082: beq IL_02ed
IL_0087: br IL_0453
IL_008c: ldloc.1
IL_008d: ldc.i4 0x78a826a8
IL_0092: bgt.un.s IL_00ba
IL_0094: ldloc.1
IL_0095: ldc.i4 0x65b3e3e5
IL_009a: beq IL_02c3
IL_009f: ldloc.1
IL_00a0: ldc.i4 0x7822b5bc
IL_00a5: beq IL_0284
IL_00aa: ldloc.1
IL_00ab: ldc.i4 0x78a826a8
IL_00b0: beq IL_01dc
IL_00b5: br IL_0453
IL_00ba: ldloc.1
IL_00bb: ldc.i4 0x7f66da4e
IL_00c0: beq IL_0356
IL_00c5: ldloc.1
IL_00c6: ldc.i4 0xb13d374d
IL_00cb: beq IL_032c
IL_00d0: ldloc.1
IL_00d1: ldc.i4 0xb2f29419
IL_00d6: beq IL_0302
IL_00db: br IL_0453
IL_00e0: ldloc.1
IL_00e1: ldc.i4 0xd59864f4
IL_00e6: bgt.un.s IL_013c
IL_00e8: ldloc.1
IL_00e9: ldc.i4 0xbf4a9f8e
IL_00ee: bgt.un.s IL_0116
IL_00f0: ldloc.1
IL_00f1: ldc.i4 0xb6e02d3a
IL_00f6: beq IL_0299
IL_00fb: ldloc.1
IL_00fc: ldc.i4 0xbaed3db3
IL_0101: beq IL_0317
IL_0106: ldloc.1
IL_0107: ldc.i4 0xbf4a9f8e
IL_010c: beq IL_0230
IL_0111: br IL_0453
IL_0116: ldloc.1
IL_0117: ldc.i4 0xc6284d42
IL_011c: beq IL_01f1
IL_0121: ldloc.1
IL_0122: ldc.i4 0xd1761402
IL_0127: beq IL_01c7
IL_012c: ldloc.1
IL_012d: ldc.i4 0xd59864f4
IL_0132: beq IL_026f
IL_0137: br IL_0453
IL_013c: ldloc.1
IL_013d: ldc.i4 0xeb323c73
IL_0142: bgt.un.s IL_016a
IL_0144: ldloc.1
IL_0145: ldc.i4 0xdca4b248
IL_014a: beq IL_0245
IL_014f: ldloc.1
IL_0150: ldc.i4 0xe926f470
IL_0155: beq IL_036b
IL_015a: ldloc.1
IL_015b: ldc.i4 0xeb323c73
IL_0160: beq IL_02d8
IL_0165: br IL_0453
IL_016a: ldloc.1
IL_016b: ldc.i4 0xf1ea0ad5
IL_0170: beq IL_0341
IL_0175: ldloc.1
IL_0176: ldc.i4 0xfa67b44d
IL_017b: beq.s IL_019d
IL_017d: ldloc.1
IL_017e: ldc.i4 0xfea21584
IL_0183: bne.un IL_0453
IL_0188: ldarg.0
IL_0189: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""
IL_018e: call ""bool string.op_Equality(string, string)""
IL_0193: brtrue IL_0380
IL_0198: br IL_0453
IL_019d: ldarg.0
IL_019e: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""
IL_01a3: call ""bool string.op_Equality(string, string)""
IL_01a8: brtrue IL_038b
IL_01ad: br IL_0453
IL_01b2: ldarg.0
IL_01b3: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""
IL_01b8: call ""bool string.op_Equality(string, string)""
IL_01bd: brtrue IL_0396
IL_01c2: br IL_0453
IL_01c7: ldarg.0
IL_01c8: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""
IL_01cd: call ""bool string.op_Equality(string, string)""
IL_01d2: brtrue IL_03a1
IL_01d7: br IL_0453
IL_01dc: ldarg.0
IL_01dd: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""
IL_01e2: call ""bool string.op_Equality(string, string)""
IL_01e7: brtrue IL_03ac
IL_01ec: br IL_0453
IL_01f1: ldarg.0
IL_01f2: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""
IL_01f7: call ""bool string.op_Equality(string, string)""
IL_01fc: brtrue IL_03b7
IL_0201: br IL_0453
IL_0206: ldarg.0
IL_0207: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""
IL_020c: call ""bool string.op_Equality(string, string)""
IL_0211: brtrue IL_03c2
IL_0216: br IL_0453
IL_021b: ldarg.0
IL_021c: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""
IL_0221: call ""bool string.op_Equality(string, string)""
IL_0226: brtrue IL_03cd
IL_022b: br IL_0453
IL_0230: ldarg.0
IL_0231: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""
IL_0236: call ""bool string.op_Equality(string, string)""
IL_023b: brtrue IL_03d5
IL_0240: br IL_0453
IL_0245: ldarg.0
IL_0246: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""
IL_024b: call ""bool string.op_Equality(string, string)""
IL_0250: brtrue IL_03dd
IL_0255: br IL_0453
IL_025a: ldarg.0
IL_025b: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""
IL_0260: call ""bool string.op_Equality(string, string)""
IL_0265: brtrue IL_03e5
IL_026a: br IL_0453
IL_026f: ldarg.0
IL_0270: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""
IL_0275: call ""bool string.op_Equality(string, string)""
IL_027a: brtrue IL_03ed
IL_027f: br IL_0453
IL_0284: ldarg.0
IL_0285: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""
IL_028a: call ""bool string.op_Equality(string, string)""
IL_028f: brtrue IL_03f5
IL_0294: br IL_0453
IL_0299: ldarg.0
IL_029a: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""
IL_029f: call ""bool string.op_Equality(string, string)""
IL_02a4: brtrue IL_03fd
IL_02a9: br IL_0453
IL_02ae: ldarg.0
IL_02af: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""
IL_02b4: call ""bool string.op_Equality(string, string)""
IL_02b9: brtrue IL_0405
IL_02be: br IL_0453
IL_02c3: ldarg.0
IL_02c4: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""
IL_02c9: call ""bool string.op_Equality(string, string)""
IL_02ce: brtrue IL_040d
IL_02d3: br IL_0453
IL_02d8: ldarg.0
IL_02d9: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""
IL_02de: call ""bool string.op_Equality(string, string)""
IL_02e3: brtrue IL_0415
IL_02e8: br IL_0453
IL_02ed: ldarg.0
IL_02ee: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""
IL_02f3: call ""bool string.op_Equality(string, string)""
IL_02f8: brtrue IL_041d
IL_02fd: br IL_0453
IL_0302: ldarg.0
IL_0303: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""
IL_0308: call ""bool string.op_Equality(string, string)""
IL_030d: brtrue IL_0425
IL_0312: br IL_0453
IL_0317: ldarg.0
IL_0318: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""
IL_031d: call ""bool string.op_Equality(string, string)""
IL_0322: brtrue IL_042d
IL_0327: br IL_0453
IL_032c: ldarg.0
IL_032d: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""
IL_0332: call ""bool string.op_Equality(string, string)""
IL_0337: brtrue IL_0435
IL_033c: br IL_0453
IL_0341: ldarg.0
IL_0342: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""
IL_0347: call ""bool string.op_Equality(string, string)""
IL_034c: brtrue IL_043d
IL_0351: br IL_0453
IL_0356: ldarg.0
IL_0357: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""
IL_035c: call ""bool string.op_Equality(string, string)""
IL_0361: brtrue IL_0445
IL_0366: br IL_0453
IL_036b: ldarg.0
IL_036c: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""
IL_0371: call ""bool string.op_Equality(string, string)""
IL_0376: brtrue IL_044d
IL_037b: br IL_0453
IL_0380: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""
IL_0385: stloc.0
IL_0386: br IL_0453
IL_038b: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""
IL_0390: stloc.0
IL_0391: br IL_0453
IL_0396: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""
IL_039b: stloc.0
IL_039c: br IL_0453
IL_03a1: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""
IL_03a6: stloc.0
IL_03a7: br IL_0453
IL_03ac: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""
IL_03b1: stloc.0
IL_03b2: br IL_0453
IL_03b7: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""
IL_03bc: stloc.0
IL_03bd: br IL_0453
IL_03c2: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""
IL_03c7: stloc.0
IL_03c8: br IL_0453
IL_03cd: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""
IL_03d2: stloc.0
IL_03d3: br.s IL_0453
IL_03d5: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""
IL_03da: stloc.0
IL_03db: br.s IL_0453
IL_03dd: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""
IL_03e2: stloc.0
IL_03e3: br.s IL_0453
IL_03e5: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""
IL_03ea: stloc.0
IL_03eb: br.s IL_0453
IL_03ed: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""
IL_03f2: stloc.0
IL_03f3: br.s IL_0453
IL_03f5: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""
IL_03fa: stloc.0
IL_03fb: br.s IL_0453
IL_03fd: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""
IL_0402: stloc.0
IL_0403: br.s IL_0453
IL_0405: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""
IL_040a: stloc.0
IL_040b: br.s IL_0453
IL_040d: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""
IL_0412: stloc.0
IL_0413: br.s IL_0453
IL_0415: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""
IL_041a: stloc.0
IL_041b: br.s IL_0453
IL_041d: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""
IL_0422: stloc.0
IL_0423: br.s IL_0453
IL_0425: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""
IL_042a: stloc.0
IL_042b: br.s IL_0453
IL_042d: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""
IL_0432: stloc.0
IL_0433: br.s IL_0453
IL_0435: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""
IL_043a: stloc.0
IL_043b: br.s IL_0453
IL_043d: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""
IL_0442: stloc.0
IL_0443: br.s IL_0453
IL_0445: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""
IL_044a: stloc.0
IL_044b: br.s IL_0453
IL_044d: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""
IL_0452: stloc.0
IL_0453: ldloc.0
IL_0454: ldarg.0
IL_0455: call ""bool string.op_Equality(string, string)""
IL_045a: ret
}"
);
// Verify string hash synthesized method for hash table switch
VerifySynthesizedStringHashMethod(compVerifier, expected: true);
}
[WorkItem(544322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544322")]
[Fact]
public void StringSwitch_HashTableSwitch_03()
{
var text = @"
using System;
class Goo
{
public static void Main()
{
Console.WriteLine(M(""blah""));
}
static int M(string s)
{
byte[] bytes = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
switch (s)
{
case ""blah"":
return 1;
case ""help"":
return 2;
case ""ooof"":
return 3;
case ""walk"":
return 4;
case ""bark"":
return 5;
case ""xblah"":
return 1;
case ""xhelp"":
return 2;
case ""xooof"":
return 3;
case ""xwalk"":
return 4;
case ""xbark"":
return 5;
case ""rblah"":
return 1;
case ""rhelp"":
return 2;
case ""rooof"":
return 3;
case ""rwalk"":
return 4;
case ""rbark"":
return 5;
}
return bytes.Length;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
// Verify string hash synthesized method for hash table switch
VerifySynthesizedStringHashMethod(compVerifier, expected: true);
}
private static void VerifySynthesizedStringHashMethod(CompilationVerifier compVerifier, bool expected)
{
compVerifier.VerifyMemberInIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName, expected);
if (expected)
{
compVerifier.VerifyIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName,
@"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (uint V_0,
int V_1)
IL_0000: ldarg.0
IL_0001: brfalse.s IL_002a
IL_0003: ldc.i4 0x811c9dc5
IL_0008: stloc.0
IL_0009: ldc.i4.0
IL_000a: stloc.1
IL_000b: br.s IL_0021
IL_000d: ldarg.0
IL_000e: ldloc.1
IL_000f: callvirt ""char string.this[int].get""
IL_0014: ldloc.0
IL_0015: xor
IL_0016: ldc.i4 0x1000193
IL_001b: mul
IL_001c: stloc.0
IL_001d: ldloc.1
IL_001e: ldc.i4.1
IL_001f: add
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.0
IL_0023: callvirt ""int string.Length.get""
IL_0028: blt.s IL_000d
IL_002a: ldloc.0
IL_002b: ret
}
");
}
}
#endregion
#region "Implicit user defined conversion tests"
[WorkItem(543602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543602")]
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_01()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var source = @"using System;
public class Test
{
public static implicit operator int(Test val)
{
return 1;
}
public static implicit operator float(Test val2)
{
return 2.1f;
}
public static int Main()
{
Test t = new Test();
switch (t)
{
case 1:
Console.WriteLine(0);
return 0;
default:
Console.WriteLine(1);
return 1;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_02()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
class X {}
class Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator X (Conv C2)
{
return new X();
}
public static int Main()
{
Conv C = new Conv();
switch(C)
{
case 1:
System.Console.WriteLine(""Pass"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 1;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_03()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
enum X { F = 0 }
class Conv
{
// only valid operator
public static implicit operator int (Conv C)
{
return 1;
}
// bool type is not valid
public static implicit operator bool (Conv C2)
{
return false;
}
// enum type is not valid
public static implicit operator X (Conv C3)
{
return X.F;
}
public static int Main()
{
Conv C = new Conv();
switch(C)
{
case 1:
System.Console.WriteLine(""Pass"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 1;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_04()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator int? (Conv? C2)
{
return null;
}
public static int Main()
{
Conv? D = new Conv();
switch(D)
{
case 1:
System.Console.WriteLine(""Fail"");
return 1;
case null:
System.Console.WriteLine(""Pass"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 1;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_06()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator int? (Conv? C)
{
return null;
}
public static int Main()
{
Conv? C = new Conv();
switch(C)
{
case null:
System.Console.WriteLine(""Pass"");
return 0;
case 1:
System.Console.WriteLine(""Fail"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 0;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_3()
{
var text =
@"using System;
struct A
{
public static implicit operator int?(A? a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int(A a)
{
Console.WriteLine(""1"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "0");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_4()
{
var text =
@"using System;
struct A
{
public static implicit operator int?(A a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int(A? a)
{
Console.WriteLine(""1"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "1");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_1()
{
var text =
@"using System;
struct A
{
public static implicit operator int(A a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int(A? a)
{
Console.WriteLine(""1"");
return 0;
}
public static implicit operator int?(A a)
{
Console.WriteLine(""2"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "1");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_3()
{
var text =
@"using System;
struct A
{
public static implicit operator int?(A a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int?(A? a)
{
Console.WriteLine(""1"");
return 0;
}
public static implicit operator int(A a)
{
Console.WriteLine(""2"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "1");
}
#endregion
[WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")]
[Fact()]
public void MissingCharsProperty()
{
var text = @"
using System;
class Program
{
static string d = null;
static void Main()
{
string s = ""hello"";
switch (s)
{
case ""Hi"":
d = "" Hi "";
break;
case ""Bye"":
d = "" Bye "";
break;
case ""qwe"":
d = "" qwe "";
break;
case ""ert"":
d = "" ert "";
break;
case ""asd"":
d = "" asd "";
break;
case ""hello"":
d = "" hello "";
break;
case ""qrs"":
d = "" qrs "";
break;
case ""tuv"":
d = "" tuv "";
break;
case ""wxy"":
d = "" wxy "";
break;
}
}
}
";
var comp = CreateEmptyCompilation(
source: new[] { Parse(text) },
references: new[] { AacorlibRef });
var verifier = CompileAndVerify(comp, verify: Verification.Fails);
verifier.VerifyIL("Program.Main", @"
{
// Code size 223 (0xdf)
.maxstack 2
.locals init (string V_0) //s
IL_0000: ldstr ""hello""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""Hi""
IL_000c: call ""bool string.op_Equality(string, string)""
IL_0011: brtrue.s IL_007c
IL_0013: ldloc.0
IL_0014: ldstr ""Bye""
IL_0019: call ""bool string.op_Equality(string, string)""
IL_001e: brtrue.s IL_0087
IL_0020: ldloc.0
IL_0021: ldstr ""qwe""
IL_0026: call ""bool string.op_Equality(string, string)""
IL_002b: brtrue.s IL_0092
IL_002d: ldloc.0
IL_002e: ldstr ""ert""
IL_0033: call ""bool string.op_Equality(string, string)""
IL_0038: brtrue.s IL_009d
IL_003a: ldloc.0
IL_003b: ldstr ""asd""
IL_0040: call ""bool string.op_Equality(string, string)""
IL_0045: brtrue.s IL_00a8
IL_0047: ldloc.0
IL_0048: ldstr ""hello""
IL_004d: call ""bool string.op_Equality(string, string)""
IL_0052: brtrue.s IL_00b3
IL_0054: ldloc.0
IL_0055: ldstr ""qrs""
IL_005a: call ""bool string.op_Equality(string, string)""
IL_005f: brtrue.s IL_00be
IL_0061: ldloc.0
IL_0062: ldstr ""tuv""
IL_0067: call ""bool string.op_Equality(string, string)""
IL_006c: brtrue.s IL_00c9
IL_006e: ldloc.0
IL_006f: ldstr ""wxy""
IL_0074: call ""bool string.op_Equality(string, string)""
IL_0079: brtrue.s IL_00d4
IL_007b: ret
IL_007c: ldstr "" Hi ""
IL_0081: stsfld ""string Program.d""
IL_0086: ret
IL_0087: ldstr "" Bye ""
IL_008c: stsfld ""string Program.d""
IL_0091: ret
IL_0092: ldstr "" qwe ""
IL_0097: stsfld ""string Program.d""
IL_009c: ret
IL_009d: ldstr "" ert ""
IL_00a2: stsfld ""string Program.d""
IL_00a7: ret
IL_00a8: ldstr "" asd ""
IL_00ad: stsfld ""string Program.d""
IL_00b2: ret
IL_00b3: ldstr "" hello ""
IL_00b8: stsfld ""string Program.d""
IL_00bd: ret
IL_00be: ldstr "" qrs ""
IL_00c3: stsfld ""string Program.d""
IL_00c8: ret
IL_00c9: ldstr "" tuv ""
IL_00ce: stsfld ""string Program.d""
IL_00d3: ret
IL_00d4: ldstr "" wxy ""
IL_00d9: stsfld ""string Program.d""
IL_00de: ret
}");
}
[WorkItem(642186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642186")]
[Fact()]
public void IsWarningSwitchEmit()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication24
{
class Program
{
static void Main(string[] args)
{
TimeIt();
TimeIt();
TimeIt();
TimeIt();
TimeIt();
TimeIt();
TimeIt();
}
private static void TimeIt()
{
// var sw = System.Diagnostics.Stopwatch.StartNew();
//
// for (int i = 0; i < 100000000; i++)
// {
// IsWarning((ErrorCode)(i % 10002));
// }
//
// sw.Stop();
// System.Console.WriteLine(sw.ElapsedMilliseconds);
}
public static bool IsWarning(ErrorCode code)
{
switch (code)
{
case ErrorCode.WRN_InvalidMainSig:
case ErrorCode.WRN_UnreferencedEvent:
case ErrorCode.WRN_LowercaseEllSuffix:
case ErrorCode.WRN_DuplicateUsing:
case ErrorCode.WRN_NewRequired:
case ErrorCode.WRN_NewNotRequired:
case ErrorCode.WRN_NewOrOverrideExpected:
case ErrorCode.WRN_UnreachableCode:
case ErrorCode.WRN_UnreferencedLabel:
case ErrorCode.WRN_UnreferencedVar:
case ErrorCode.WRN_UnreferencedField:
case ErrorCode.WRN_IsAlwaysTrue:
case ErrorCode.WRN_IsAlwaysFalse:
case ErrorCode.WRN_ByRefNonAgileField:
case ErrorCode.WRN_OldWarning_UnsafeProp:
case ErrorCode.WRN_UnreferencedVarAssg:
case ErrorCode.WRN_NegativeArrayIndex:
case ErrorCode.WRN_BadRefCompareLeft:
case ErrorCode.WRN_BadRefCompareRight:
case ErrorCode.WRN_PatternIsAmbiguous:
case ErrorCode.WRN_PatternStaticOrInaccessible:
case ErrorCode.WRN_PatternBadSignature:
case ErrorCode.WRN_SequentialOnPartialClass:
case ErrorCode.WRN_MainCantBeGeneric:
case ErrorCode.WRN_UnreferencedFieldAssg:
case ErrorCode.WRN_AmbiguousXMLReference:
case ErrorCode.WRN_VolatileByRef:
case ErrorCode.WRN_IncrSwitchObsolete:
case ErrorCode.WRN_UnreachableExpr:
case ErrorCode.WRN_SameFullNameThisNsAgg:
case ErrorCode.WRN_SameFullNameThisAggAgg:
case ErrorCode.WRN_SameFullNameThisAggNs:
case ErrorCode.WRN_GlobalAliasDefn:
case ErrorCode.WRN_UnexpectedPredefTypeLoc:
case ErrorCode.WRN_AlwaysNull:
case ErrorCode.WRN_CmpAlwaysFalse:
case ErrorCode.WRN_FinalizeMethod:
case ErrorCode.WRN_AmbigLookupMeth:
case ErrorCode.WRN_GotoCaseShouldConvert:
case ErrorCode.WRN_NubExprIsConstBool:
case ErrorCode.WRN_ExplicitImplCollision:
case ErrorCode.WRN_FeatureDeprecated:
case ErrorCode.WRN_DeprecatedSymbol:
case ErrorCode.WRN_DeprecatedSymbolStr:
case ErrorCode.WRN_ExternMethodNoImplementation:
case ErrorCode.WRN_ProtectedInSealed:
case ErrorCode.WRN_PossibleMistakenNullStatement:
case ErrorCode.WRN_UnassignedInternalField:
case ErrorCode.WRN_VacuousIntegralComp:
case ErrorCode.WRN_AttributeLocationOnBadDeclaration:
case ErrorCode.WRN_InvalidAttributeLocation:
case ErrorCode.WRN_EqualsWithoutGetHashCode:
case ErrorCode.WRN_EqualityOpWithoutEquals:
case ErrorCode.WRN_EqualityOpWithoutGetHashCode:
case ErrorCode.WRN_IncorrectBooleanAssg:
case ErrorCode.WRN_NonObsoleteOverridingObsolete:
case ErrorCode.WRN_BitwiseOrSignExtend:
case ErrorCode.WRN_OldWarning_ProtectedInternal:
case ErrorCode.WRN_OldWarning_AccessibleReadonly:
case ErrorCode.WRN_CoClassWithoutComImport:
case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter:
case ErrorCode.WRN_AssignmentToLockOrDispose:
case ErrorCode.WRN_ObsoleteOverridingNonObsolete:
case ErrorCode.WRN_DebugFullNameTooLong:
case ErrorCode.WRN_ExternCtorNoImplementation:
case ErrorCode.WRN_WarningDirective:
case ErrorCode.WRN_UnreachableGeneralCatch:
case ErrorCode.WRN_UninitializedField:
case ErrorCode.WRN_DeprecatedCollectionInitAddStr:
case ErrorCode.WRN_DeprecatedCollectionInitAdd:
case ErrorCode.WRN_DefaultValueForUnconsumedLocation:
case ErrorCode.WRN_FeatureDeprecated2:
case ErrorCode.WRN_FeatureDeprecated3:
case ErrorCode.WRN_FeatureDeprecated4:
case ErrorCode.WRN_FeatureDeprecated5:
case ErrorCode.WRN_OldWarning_FeatureDefaultDeprecated:
case ErrorCode.WRN_EmptySwitch:
case ErrorCode.WRN_XMLParseError:
case ErrorCode.WRN_DuplicateParamTag:
case ErrorCode.WRN_UnmatchedParamTag:
case ErrorCode.WRN_MissingParamTag:
case ErrorCode.WRN_BadXMLRef:
case ErrorCode.WRN_BadXMLRefParamType:
case ErrorCode.WRN_BadXMLRefReturnType:
case ErrorCode.WRN_BadXMLRefSyntax:
case ErrorCode.WRN_UnprocessedXMLComment:
case ErrorCode.WRN_FailedInclude:
case ErrorCode.WRN_InvalidInclude:
case ErrorCode.WRN_MissingXMLComment:
case ErrorCode.WRN_XMLParseIncludeError:
case ErrorCode.WRN_OldWarning_MultipleTypeDefs:
case ErrorCode.WRN_OldWarning_DocFileGenAndIncr:
case ErrorCode.WRN_XMLParserNotFound:
case ErrorCode.WRN_ALinkWarn:
case ErrorCode.WRN_DeleteAutoResFailed:
case ErrorCode.WRN_CmdOptionConflictsSource:
case ErrorCode.WRN_IllegalPragma:
case ErrorCode.WRN_IllegalPPWarning:
case ErrorCode.WRN_BadRestoreNumber:
case ErrorCode.WRN_NonECMAFeature:
case ErrorCode.WRN_ErrorOverride:
case ErrorCode.WRN_OldWarning_ReservedIdentifier:
case ErrorCode.WRN_InvalidSearchPathDir:
case ErrorCode.WRN_MissingTypeNested:
case ErrorCode.WRN_MissingTypeInSource:
case ErrorCode.WRN_MissingTypeInAssembly:
case ErrorCode.WRN_MultiplePredefTypes:
case ErrorCode.WRN_TooManyLinesForDebugger:
case ErrorCode.WRN_CallOnNonAgileField:
case ErrorCode.WRN_BadWarningNumber:
case ErrorCode.WRN_InvalidNumber:
case ErrorCode.WRN_FileNameTooLong:
case ErrorCode.WRN_IllegalPPChecksum:
case ErrorCode.WRN_EndOfPPLineExpected:
case ErrorCode.WRN_ConflictingChecksum:
case ErrorCode.WRN_AssumedMatchThis:
case ErrorCode.WRN_UseSwitchInsteadOfAttribute:
case ErrorCode.WRN_InvalidAssemblyName:
case ErrorCode.WRN_UnifyReferenceMajMin:
case ErrorCode.WRN_UnifyReferenceBldRev:
case ErrorCode.WRN_DelegateNewMethBind:
case ErrorCode.WRN_EmptyFileName:
case ErrorCode.WRN_DuplicateTypeParamTag:
case ErrorCode.WRN_UnmatchedTypeParamTag:
case ErrorCode.WRN_MissingTypeParamTag:
case ErrorCode.WRN_AssignmentToSelf:
case ErrorCode.WRN_ComparisonToSelf:
case ErrorCode.WRN_DotOnDefault:
case ErrorCode.WRN_BadXMLRefTypeVar:
case ErrorCode.WRN_UnmatchedParamRefTag:
case ErrorCode.WRN_UnmatchedTypeParamRefTag:
case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA:
case ErrorCode.WRN_TypeNotFoundForNoPIAWarning:
case ErrorCode.WRN_CantHaveManifestForModule:
case ErrorCode.WRN_MultipleRuntimeImplementationMatches:
case ErrorCode.WRN_MultipleRuntimeOverrideMatches:
case ErrorCode.WRN_DynamicDispatchToConditionalMethod:
case ErrorCode.WRN_IsDynamicIsConfusing:
case ErrorCode.WRN_AsyncLacksAwaits:
case ErrorCode.WRN_FileAlreadyIncluded:
case ErrorCode.WRN_NoSources:
case ErrorCode.WRN_UseNewSwitch:
case ErrorCode.WRN_NoConfigNotOnCommandLine:
case ErrorCode.WRN_DefineIdentifierRequired:
case ErrorCode.WRN_BadUILang:
case ErrorCode.WRN_CLS_NoVarArgs:
case ErrorCode.WRN_CLS_BadArgType:
case ErrorCode.WRN_CLS_BadReturnType:
case ErrorCode.WRN_CLS_BadFieldPropType:
case ErrorCode.WRN_CLS_BadUnicode:
case ErrorCode.WRN_CLS_BadIdentifierCase:
case ErrorCode.WRN_CLS_OverloadRefOut:
case ErrorCode.WRN_CLS_OverloadUnnamed:
case ErrorCode.WRN_CLS_BadIdentifier:
case ErrorCode.WRN_CLS_BadBase:
case ErrorCode.WRN_CLS_BadInterfaceMember:
case ErrorCode.WRN_CLS_NoAbstractMembers:
case ErrorCode.WRN_CLS_NotOnModules:
case ErrorCode.WRN_CLS_ModuleMissingCLS:
case ErrorCode.WRN_CLS_AssemblyNotCLS:
case ErrorCode.WRN_CLS_BadAttributeType:
case ErrorCode.WRN_CLS_ArrayArgumentToAttribute:
case ErrorCode.WRN_CLS_NotOnModules2:
case ErrorCode.WRN_CLS_IllegalTrueInFalse:
case ErrorCode.WRN_CLS_MeaninglessOnPrivateType:
case ErrorCode.WRN_CLS_AssemblyNotCLS2:
case ErrorCode.WRN_CLS_MeaninglessOnParam:
case ErrorCode.WRN_CLS_MeaninglessOnReturn:
case ErrorCode.WRN_CLS_BadTypeVar:
case ErrorCode.WRN_CLS_VolatileField:
case ErrorCode.WRN_CLS_BadInterface:
case ErrorCode.WRN_UnobservedAwaitableExpression:
case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation:
case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation:
case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation:
case ErrorCode.WRN_UnknownOption:
case ErrorCode.WRN_MetadataNameTooLong:
case ErrorCode.WRN_MainIgnored:
case ErrorCode.WRN_DelaySignButNoKey:
case ErrorCode.WRN_InvalidVersionFormat:
case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath:
case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden:
case ErrorCode.WRN_UnimplementedCommandLineSwitch:
case ErrorCode.WRN_RefCultureMismatch:
case ErrorCode.WRN_ConflictingMachineAssembly:
case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope1:
case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope2:
case ErrorCode.WRN_CA2202_DoNotDisposeObjectsMultipleTimes:
return true;
default:
return false;
}
}
internal enum ErrorCode
{
Void = InternalErrorCode.Void,
Unknown = InternalErrorCode.Unknown,
FTL_InternalError = 1,
//FTL_FailedToLoadResource = 2,
//FTL_NoMemory = 3,
//ERR_WarningAsError = 4,
//ERR_MissingOptionArg = 5,
ERR_NoMetadataFile = 6,
//FTL_ComPlusInit = 7,
FTL_MetadataImportFailure = 8,
FTL_MetadataCantOpenFile = 9,
//ERR_FatalError = 10,
//ERR_CantImportBase = 11,
ERR_NoTypeDef = 12,
FTL_MetadataEmitFailure = 13,
//FTL_RequiredFileNotFound = 14,
ERR_ClassNameTooLong = 15,
ERR_OutputWriteFailed = 16,
ERR_MultipleEntryPoints = 17,
//ERR_UnimplementedOp = 18,
ERR_BadBinaryOps = 19,
ERR_IntDivByZero = 20,
ERR_BadIndexLHS = 21,
ERR_BadIndexCount = 22,
ERR_BadUnaryOp = 23,
//ERR_NoStdLib = 25, not used in Roslyn
ERR_ThisInStaticMeth = 26,
ERR_ThisInBadContext = 27,
WRN_InvalidMainSig = 28,
ERR_NoImplicitConv = 29,
ERR_NoExplicitConv = 30,
ERR_ConstOutOfRange = 31,
ERR_AmbigBinaryOps = 34,
ERR_AmbigUnaryOp = 35,
ERR_InAttrOnOutParam = 36,
ERR_ValueCantBeNull = 37,
//ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired ""An object reference is required for the non-static...""
ERR_NoExplicitBuiltinConv = 39,
//FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
FTL_DebugEmitFailure = 41,
//FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info.
//FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
ERR_BadVisReturnType = 50,
ERR_BadVisParamType = 51,
ERR_BadVisFieldType = 52,
ERR_BadVisPropertyType = 53,
ERR_BadVisIndexerReturn = 54,
ERR_BadVisIndexerParam = 55,
ERR_BadVisOpReturn = 56,
ERR_BadVisOpParam = 57,
ERR_BadVisDelegateReturn = 58,
ERR_BadVisDelegateParam = 59,
ERR_BadVisBaseClass = 60,
ERR_BadVisBaseInterface = 61,
ERR_EventNeedsBothAccessors = 65,
ERR_EventNotDelegate = 66,
WRN_UnreferencedEvent = 67,
ERR_InterfaceEventInitializer = 68,
ERR_EventPropertyInInterface = 69,
ERR_BadEventUsage = 70,
ERR_ExplicitEventFieldImpl = 71,
ERR_CantOverrideNonEvent = 72,
ERR_AddRemoveMustHaveBody = 73,
ERR_AbstractEventInitializer = 74,
ERR_PossibleBadNegCast = 75,
ERR_ReservedEnumerator = 76,
ERR_AsMustHaveReferenceType = 77,
WRN_LowercaseEllSuffix = 78,
ERR_BadEventUsageNoField = 79,
ERR_ConstraintOnlyAllowedOnGenericDecl = 80,
ERR_TypeParamMustBeIdentifier = 81,
ERR_MemberReserved = 82,
ERR_DuplicateParamName = 100,
ERR_DuplicateNameInNS = 101,
ERR_DuplicateNameInClass = 102,
ERR_NameNotInContext = 103,
ERR_AmbigContext = 104,
WRN_DuplicateUsing = 105,
ERR_BadMemberFlag = 106,
ERR_BadMemberProtection = 107,
WRN_NewRequired = 108,
WRN_NewNotRequired = 109,
ERR_CircConstValue = 110,
ERR_MemberAlreadyExists = 111,
ERR_StaticNotVirtual = 112,
ERR_OverrideNotNew = 113,
WRN_NewOrOverrideExpected = 114,
ERR_OverrideNotExpected = 115,
ERR_NamespaceUnexpected = 116,
ERR_NoSuchMember = 117,
ERR_BadSKknown = 118,
ERR_BadSKunknown = 119,
ERR_ObjectRequired = 120,
ERR_AmbigCall = 121,
ERR_BadAccess = 122,
ERR_MethDelegateMismatch = 123,
ERR_RetObjectRequired = 126,
ERR_RetNoObjectRequired = 127,
ERR_LocalDuplicate = 128,
ERR_AssgLvalueExpected = 131,
ERR_StaticConstParam = 132,
ERR_NotConstantExpression = 133,
ERR_NotNullConstRefField = 134,
ERR_NameIllegallyOverrides = 135,
ERR_LocalIllegallyOverrides = 136,
ERR_BadUsingNamespace = 138,
ERR_NoBreakOrCont = 139,
ERR_DuplicateLabel = 140,
ERR_NoConstructors = 143,
ERR_NoNewAbstract = 144,
ERR_ConstValueRequired = 145,
ERR_CircularBase = 146,
ERR_BadDelegateConstructor = 148,
ERR_MethodNameExpected = 149,
ERR_ConstantExpected = 150,
// ERR_SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler.
// However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future
// we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used.
ERR_SwitchGoverningTypeValueExpected = 151,
ERR_DuplicateCaseLabel = 152,
ERR_InvalidGotoCase = 153,
ERR_PropertyLacksGet = 154,
ERR_BadExceptionType = 155,
ERR_BadEmptyThrow = 156,
ERR_BadFinallyLeave = 157,
ERR_LabelShadow = 158,
ERR_LabelNotFound = 159,
ERR_UnreachableCatch = 160,
ERR_ReturnExpected = 161,
WRN_UnreachableCode = 162,
ERR_SwitchFallThrough = 163,
WRN_UnreferencedLabel = 164,
ERR_UseDefViolation = 165,
//ERR_NoInvoke = 167,
WRN_UnreferencedVar = 168,
WRN_UnreferencedField = 169,
ERR_UseDefViolationField = 170,
ERR_UnassignedThis = 171,
ERR_AmbigQM = 172,
ERR_InvalidQM = 173,
ERR_NoBaseClass = 174,
ERR_BaseIllegal = 175,
ERR_ObjectProhibited = 176,
ERR_ParamUnassigned = 177,
ERR_InvalidArray = 178,
ERR_ExternHasBody = 179,
ERR_AbstractAndExtern = 180,
ERR_BadAttributeParamType = 181,
ERR_BadAttributeArgument = 182,
WRN_IsAlwaysTrue = 183,
WRN_IsAlwaysFalse = 184,
ERR_LockNeedsReference = 185,
ERR_NullNotValid = 186,
ERR_UseDefViolationThis = 188,
ERR_ArgsInvalid = 190,
ERR_AssgReadonly = 191,
ERR_RefReadonly = 192,
ERR_PtrExpected = 193,
ERR_PtrIndexSingle = 196,
WRN_ByRefNonAgileField = 197,
ERR_AssgReadonlyStatic = 198,
ERR_RefReadonlyStatic = 199,
ERR_AssgReadonlyProp = 200,
ERR_IllegalStatement = 201,
ERR_BadGetEnumerator = 202,
ERR_TooManyLocals = 204,
ERR_AbstractBaseCall = 205,
ERR_RefProperty = 206,
WRN_OldWarning_UnsafeProp = 207, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:207"" is specified on the command line.
ERR_ManagedAddr = 208,
ERR_BadFixedInitType = 209,
ERR_FixedMustInit = 210,
ERR_InvalidAddrOp = 211,
ERR_FixedNeeded = 212,
ERR_FixedNotNeeded = 213,
ERR_UnsafeNeeded = 214,
ERR_OpTFRetType = 215,
ERR_OperatorNeedsMatch = 216,
ERR_BadBoolOp = 217,
ERR_MustHaveOpTF = 218,
WRN_UnreferencedVarAssg = 219,
ERR_CheckedOverflow = 220,
ERR_ConstOutOfRangeChecked = 221,
ERR_BadVarargs = 224,
ERR_ParamsMustBeArray = 225,
ERR_IllegalArglist = 226,
ERR_IllegalUnsafe = 227,
//ERR_NoAccessibleMember = 228,
ERR_AmbigMember = 229,
ERR_BadForeachDecl = 230,
ERR_ParamsLast = 231,
ERR_SizeofUnsafe = 233,
ERR_DottedTypeNameNotFoundInNS = 234,
ERR_FieldInitRefNonstatic = 236,
ERR_SealedNonOverride = 238,
ERR_CantOverrideSealed = 239,
//ERR_NoDefaultArgs = 241,
ERR_VoidError = 242,
ERR_ConditionalOnOverride = 243,
ERR_PointerInAsOrIs = 244,
ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated
ERR_SingleTypeNameNotFound = 246,
ERR_NegativeStackAllocSize = 247,
ERR_NegativeArraySize = 248,
ERR_OverrideFinalizeDeprecated = 249,
ERR_CallingBaseFinalizeDeprecated = 250,
WRN_NegativeArrayIndex = 251,
WRN_BadRefCompareLeft = 252,
WRN_BadRefCompareRight = 253,
ERR_BadCastInFixed = 254,
ERR_StackallocInCatchFinally = 255,
ERR_VarargsLast = 257,
ERR_MissingPartial = 260,
ERR_PartialTypeKindConflict = 261,
ERR_PartialModifierConflict = 262,
ERR_PartialMultipleBases = 263,
ERR_PartialWrongTypeParams = 264,
ERR_PartialWrongConstraints = 265,
ERR_NoImplicitConvCast = 266,
ERR_PartialMisplaced = 267,
ERR_ImportedCircularBase = 268,
ERR_UseDefViolationOut = 269,
ERR_ArraySizeInDeclaration = 270,
ERR_InaccessibleGetter = 271,
ERR_InaccessibleSetter = 272,
ERR_InvalidPropertyAccessMod = 273,
ERR_DuplicatePropertyAccessMods = 274,
ERR_PropertyAccessModInInterface = 275,
ERR_AccessModMissingAccessor = 276,
ERR_UnimplementedInterfaceAccessor = 277,
WRN_PatternIsAmbiguous = 278,
WRN_PatternStaticOrInaccessible = 279,
WRN_PatternBadSignature = 280,
ERR_FriendRefNotEqualToThis = 281,
WRN_SequentialOnPartialClass = 282,
ERR_BadConstType = 283,
ERR_NoNewTyvar = 304,
ERR_BadArity = 305,
ERR_BadTypeArgument = 306,
ERR_TypeArgsNotAllowed = 307,
ERR_HasNoTypeVars = 308,
ERR_NewConstraintNotSatisfied = 310,
ERR_GenericConstraintNotSatisfiedRefType = 311,
ERR_GenericConstraintNotSatisfiedNullableEnum = 312,
ERR_GenericConstraintNotSatisfiedNullableInterface = 313,
ERR_GenericConstraintNotSatisfiedTyVar = 314,
ERR_GenericConstraintNotSatisfiedValType = 315,
ERR_DuplicateGeneratedName = 316,
ERR_GlobalSingleTypeNameNotFound = 400,
ERR_NewBoundMustBeLast = 401,
WRN_MainCantBeGeneric = 402,
ERR_TypeVarCantBeNull = 403,
ERR_AttributeCantBeGeneric = 404,
ERR_DuplicateBound = 405,
ERR_ClassBoundNotFirst = 406,
ERR_BadRetType = 407,
ERR_DuplicateConstraintClause = 409,
//ERR_WrongSignature = 410, unused in Roslyn
ERR_CantInferMethTypeArgs = 411,
ERR_LocalSameNameAsTypeParam = 412,
ERR_AsWithTypeVar = 413,
WRN_UnreferencedFieldAssg = 414,
ERR_BadIndexerNameAttr = 415,
ERR_AttrArgWithTypeVars = 416,
ERR_NewTyvarWithArgs = 417,
ERR_AbstractSealedStatic = 418,
WRN_AmbiguousXMLReference = 419,
WRN_VolatileByRef = 420,
WRN_IncrSwitchObsolete = 422, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line.
ERR_ComImportWithImpl = 423,
ERR_ComImportWithBase = 424,
ERR_ImplBadConstraints = 425,
ERR_DottedTypeNameNotFoundInAgg = 426,
ERR_MethGrpToNonDel = 428,
WRN_UnreachableExpr = 429, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line.
ERR_BadExternAlias = 430,
ERR_ColColWithTypeAlias = 431,
ERR_AliasNotFound = 432,
ERR_SameFullNameAggAgg = 433,
ERR_SameFullNameNsAgg = 434,
WRN_SameFullNameThisNsAgg = 435,
WRN_SameFullNameThisAggAgg = 436,
WRN_SameFullNameThisAggNs = 437,
ERR_SameFullNameThisAggThisNs = 438,
ERR_ExternAfterElements = 439,
WRN_GlobalAliasDefn = 440,
ERR_SealedStaticClass = 441,
ERR_PrivateAbstractAccessor = 442,
ERR_ValueExpected = 443,
WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line.
ERR_UnboxNotLValue = 445,
ERR_AnonMethGrpInForEach = 446,
//ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error.
ERR_BadIncDecRetType = 448,
ERR_TypeConstraintsMustBeUniqueAndFirst = 449,
ERR_RefValBoundWithClass = 450,
ERR_NewBoundWithVal = 451,
ERR_RefConstraintNotSatisfied = 452,
ERR_ValConstraintNotSatisfied = 453,
ERR_CircularConstraint = 454,
ERR_BaseConstraintConflict = 455,
ERR_ConWithValCon = 456,
ERR_AmbigUDConv = 457,
WRN_AlwaysNull = 458,
ERR_AddrOnReadOnlyLocal = 459,
ERR_OverrideWithConstraints = 460,
ERR_AmbigOverride = 462,
ERR_DecConstError = 463,
WRN_CmpAlwaysFalse = 464,
WRN_FinalizeMethod = 465,
ERR_ExplicitImplParams = 466,
WRN_AmbigLookupMeth = 467,
ERR_SameFullNameThisAggThisAgg = 468,
WRN_GotoCaseShouldConvert = 469,
ERR_MethodImplementingAccessor = 470,
//ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn
WRN_NubExprIsConstBool = 472,
WRN_ExplicitImplCollision = 473,
ERR_AbstractHasBody = 500,
ERR_ConcreteMissingBody = 501,
ERR_AbstractAndSealed = 502,
ERR_AbstractNotVirtual = 503,
ERR_StaticConstant = 504,
ERR_CantOverrideNonFunction = 505,
ERR_CantOverrideNonVirtual = 506,
ERR_CantChangeAccessOnOverride = 507,
ERR_CantChangeReturnTypeOnOverride = 508,
ERR_CantDeriveFromSealedType = 509,
ERR_AbstractInConcreteClass = 513,
ERR_StaticConstructorWithExplicitConstructorCall = 514,
ERR_StaticConstructorWithAccessModifiers = 515,
ERR_RecursiveConstructorCall = 516,
ERR_ObjectCallingBaseConstructor = 517,
ERR_PredefinedTypeNotFound = 518,
//ERR_PredefinedTypeBadType = 520,
ERR_StructWithBaseConstructorCall = 522,
ERR_StructLayoutCycle = 523,
ERR_InterfacesCannotContainTypes = 524,
ERR_InterfacesCantContainFields = 525,
ERR_InterfacesCantContainConstructors = 526,
ERR_NonInterfaceInInterfaceList = 527,
ERR_DuplicateInterfaceInBaseList = 528,
ERR_CycleInInterfaceInheritance = 529,
ERR_InterfaceMemberHasBody = 531,
ERR_HidingAbstractMethod = 533,
ERR_UnimplementedAbstractMethod = 534,
ERR_UnimplementedInterfaceMember = 535,
ERR_ObjectCantHaveBases = 537,
ERR_ExplicitInterfaceImplementationNotInterface = 538,
ERR_InterfaceMemberNotFound = 539,
ERR_ClassDoesntImplementInterface = 540,
ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541,
ERR_MemberNameSameAsType = 542,
ERR_EnumeratorOverflow = 543,
ERR_CantOverrideNonProperty = 544,
ERR_NoGetToOverride = 545,
ERR_NoSetToOverride = 546,
ERR_PropertyCantHaveVoidType = 547,
ERR_PropertyWithNoAccessors = 548,
ERR_NewVirtualInSealed = 549,
ERR_ExplicitPropertyAddingAccessor = 550,
ERR_ExplicitPropertyMissingAccessor = 551,
ERR_ConversionWithInterface = 552,
ERR_ConversionWithBase = 553,
ERR_ConversionWithDerived = 554,
ERR_IdentityConversion = 555,
ERR_ConversionNotInvolvingContainedType = 556,
ERR_DuplicateConversionInClass = 557,
ERR_OperatorsMustBeStatic = 558,
ERR_BadIncDecSignature = 559,
ERR_BadUnaryOperatorSignature = 562,
ERR_BadBinaryOperatorSignature = 563,
ERR_BadShiftOperatorSignature = 564,
ERR_InterfacesCantContainOperators = 567,
ERR_StructsCantContainDefaultConstructor = 568,
ERR_CantOverrideBogusMethod = 569,
ERR_BindToBogus = 570,
ERR_CantCallSpecialMethod = 571,
ERR_BadTypeReference = 572,
ERR_FieldInitializerInStruct = 573,
ERR_BadDestructorName = 574,
ERR_OnlyClassesCanContainDestructors = 575,
ERR_ConflictAliasAndMember = 576,
ERR_ConditionalOnSpecialMethod = 577,
ERR_ConditionalMustReturnVoid = 578,
ERR_DuplicateAttribute = 579,
ERR_ConditionalOnInterfaceMethod = 582,
//ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused
//ERR_ICE_Symbol = 584,
//ERR_ICE_Node = 585,
//ERR_ICE_File = 586,
//ERR_ICE_Stage = 587,
//ERR_ICE_Lexer = 588,
//ERR_ICE_Parser = 589,
ERR_OperatorCantReturnVoid = 590,
ERR_InvalidAttributeArgument = 591,
ERR_AttributeOnBadSymbolType = 592,
ERR_FloatOverflow = 594,
ERR_ComImportWithoutUuidAttribute = 596,
ERR_InvalidNamedArgument = 599,
ERR_DllImportOnInvalidMethod = 601,
WRN_FeatureDeprecated = 602, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:602"" is specified on the command line.
// ERR_NameAttributeOnOverride = 609, // removed in Roslyn
ERR_FieldCantBeRefAny = 610,
ERR_ArrayElementCantBeRefAny = 611,
WRN_DeprecatedSymbol = 612,
ERR_NotAnAttributeClass = 616,
ERR_BadNamedAttributeArgument = 617,
WRN_DeprecatedSymbolStr = 618,
ERR_DeprecatedSymbolStr = 619,
ERR_IndexerCantHaveVoidType = 620,
ERR_VirtualPrivate = 621,
ERR_ArrayInitToNonArrayType = 622,
ERR_ArrayInitInBadPlace = 623,
ERR_MissingStructOffset = 625,
WRN_ExternMethodNoImplementation = 626,
WRN_ProtectedInSealed = 628,
ERR_InterfaceImplementedByConditional = 629,
ERR_IllegalRefParam = 631,
ERR_BadArgumentToAttribute = 633,
//ERR_MissingComTypeOrMarshaller = 635,
ERR_StructOffsetOnBadStruct = 636,
ERR_StructOffsetOnBadField = 637,
ERR_AttributeUsageOnNonAttributeClass = 641,
WRN_PossibleMistakenNullStatement = 642,
ERR_DuplicateNamedAttributeArgument = 643,
ERR_DeriveFromEnumOrValueType = 644,
ERR_DefaultMemberOnIndexedType = 646,
//ERR_CustomAttributeError = 647,
ERR_BogusType = 648,
WRN_UnassignedInternalField = 649,
ERR_CStyleArray = 650,
WRN_VacuousIntegralComp = 652,
ERR_AbstractAttributeClass = 653,
ERR_BadNamedAttributeArgumentType = 655,
ERR_MissingPredefinedMember = 656,
WRN_AttributeLocationOnBadDeclaration = 657,
WRN_InvalidAttributeLocation = 658,
WRN_EqualsWithoutGetHashCode = 659,
WRN_EqualityOpWithoutEquals = 660,
WRN_EqualityOpWithoutGetHashCode = 661,
ERR_OutAttrOnRefParam = 662,
ERR_OverloadRefKind = 663,
ERR_LiteralDoubleCast = 664,
WRN_IncorrectBooleanAssg = 665,
ERR_ProtectedInStruct = 666,
//ERR_FeatureDeprecated = 667,
ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler
ERR_ComImportWithUserCtor = 669,
ERR_FieldCantHaveVoidType = 670,
WRN_NonObsoleteOverridingObsolete = 672,
ERR_SystemVoid = 673,
ERR_ExplicitParamArray = 674,
WRN_BitwiseOrSignExtend = 675,
ERR_VolatileStruct = 677,
ERR_VolatileAndReadonly = 678,
WRN_OldWarning_ProtectedInternal = 679, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:679"" is specified on the command line.
WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:680"" is specified on the command line.
ERR_AbstractField = 681,
ERR_BogusExplicitImpl = 682,
ERR_ExplicitMethodImplAccessor = 683,
WRN_CoClassWithoutComImport = 684,
ERR_ConditionalWithOutParam = 685,
ERR_AccessorImplementingMethod = 686,
ERR_AliasQualAsExpression = 687,
ERR_DerivingFromATyVar = 689,
//FTL_MalformedMetadata = 690,
ERR_DuplicateTypeParameter = 692,
WRN_TypeParameterSameAsOuterTypeParameter = 693,
ERR_TypeVariableSameAsParent = 694,
ERR_UnifyingInterfaceInstantiations = 695,
ERR_GenericDerivingFromAttribute = 698,
ERR_TyVarNotFoundInConstraint = 699,
ERR_BadBoundType = 701,
ERR_SpecialTypeAsBound = 702,
ERR_BadVisBound = 703,
ERR_LookupInTypeVariable = 704,
ERR_BadConstraintType = 706,
ERR_InstanceMemberInStaticClass = 708,
ERR_StaticBaseClass = 709,
ERR_ConstructorInStaticClass = 710,
ERR_DestructorInStaticClass = 711,
ERR_InstantiatingStaticClass = 712,
ERR_StaticDerivedFromNonObject = 713,
ERR_StaticClassInterfaceImpl = 714,
ERR_OperatorInStaticClass = 715,
ERR_ConvertToStaticClass = 716,
ERR_ConstraintIsStaticClass = 717,
ERR_GenericArgIsStaticClass = 718,
ERR_ArrayOfStaticClass = 719,
ERR_IndexerInStaticClass = 720,
ERR_ParameterIsStaticClass = 721,
ERR_ReturnTypeIsStaticClass = 722,
ERR_VarDeclIsStaticClass = 723,
ERR_BadEmptyThrowInFinally = 724,
//ERR_InvalidDecl = 725,
//ERR_InvalidSpecifier = 726,
//ERR_InvalidSpecifierUnk = 727,
WRN_AssignmentToLockOrDispose = 728,
ERR_ForwardedTypeInThisAssembly = 729,
ERR_ForwardedTypeIsNested = 730,
ERR_CycleInTypeForwarder = 731,
//ERR_FwdedGeneric = 733,
ERR_AssemblyNameOnNonModule = 734,
ERR_InvalidFwdType = 735,
ERR_CloseUnimplementedInterfaceMemberStatic = 736,
ERR_CloseUnimplementedInterfaceMemberNotPublic = 737,
ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738,
ERR_DuplicateTypeForwarder = 739,
ERR_ExpectedSelectOrGroup = 742,
ERR_ExpectedContextualKeywordOn = 743,
ERR_ExpectedContextualKeywordEquals = 744,
ERR_ExpectedContextualKeywordBy = 745,
ERR_InvalidAnonymousTypeMemberDeclarator = 746,
ERR_InvalidInitializerElementInitializer = 747,
ERR_InconsistentLambdaParameterUsage = 748,
ERR_PartialMethodInvalidModifier = 750,
ERR_PartialMethodOnlyInPartialClass = 751,
ERR_PartialMethodCannotHaveOutParameters = 752,
ERR_PartialMethodOnlyMethods = 753,
ERR_PartialMethodNotExplicit = 754,
ERR_PartialMethodExtensionDifference = 755,
ERR_PartialMethodOnlyOneLatent = 756,
ERR_PartialMethodOnlyOneActual = 757,
ERR_PartialMethodParamsDifference = 758,
ERR_PartialMethodMustHaveLatent = 759,
ERR_PartialMethodInconsistentConstraints = 761,
ERR_PartialMethodToDelegate = 762,
ERR_PartialMethodStaticDifference = 763,
ERR_PartialMethodUnsafeDifference = 764,
ERR_PartialMethodInExpressionTree = 765,
ERR_PartialMethodMustReturnVoid = 766,
ERR_ExplicitImplCollisionOnRefOut = 767,
//ERR_NoEmptyArrayRanges = 800,
//ERR_IntegerSpecifierOnOneDimArrays = 801,
//ERR_IntegerSpecifierMustBePositive = 802,
//ERR_ArrayRangeDimensionsMustMatch = 803,
//ERR_ArrayRangeDimensionsWrong = 804,
//ERR_IntegerSpecifierValidOnlyOnArrays = 805,
//ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806,
//ERR_UseAdditionalSquareBrackets = 807,
//ERR_DotDotNotAssociative = 808,
WRN_ObsoleteOverridingNonObsolete = 809,
WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong
ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue
ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer
ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator
ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer
ERR_ImplicitlyTypedLocalCannotBeFixed = 821,
ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst
WRN_ExternCtorNoImplementation = 824,
ERR_TypeVarNotFound = 825,
ERR_ImplicitlyTypedArrayNoBestType = 826,
ERR_AnonymousTypePropertyAssignedBadValue = 828,
ERR_ExpressionTreeContainsBaseAccess = 831,
ERR_ExpressionTreeContainsAssignment = 832,
ERR_AnonymousTypeDuplicatePropertyName = 833,
ERR_StatementLambdaToExpressionTree = 834,
ERR_ExpressionTreeMustHaveDelegate = 835,
ERR_AnonymousTypeNotAvailable = 836,
ERR_LambdaInIsAs = 837,
ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838,
ERR_MissingArgument = 839,
ERR_AutoPropertiesMustHaveBothAccessors = 840,
ERR_VariableUsedBeforeDeclaration = 841,
ERR_ExplicitLayoutAndAutoImplementedProperty = 842,
ERR_UnassignedThisAutoProperty = 843,
ERR_VariableUsedBeforeDeclarationAndHidesField = 844,
ERR_ExpressionTreeContainsBadCoalesce = 845,
ERR_ArrayInitializerExpected = 846,
ERR_ArrayInitializerIncorrectLength = 847,
// ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind
ERR_ExpressionTreeContainsNamedArgument = 853,
ERR_ExpressionTreeContainsOptionalArgument = 854,
ERR_ExpressionTreeContainsIndexedProperty = 855,
ERR_IndexedPropertyRequiresParams = 856,
ERR_IndexedPropertyMustHaveAllOptionalParams = 857,
ERR_FusionConfigFileNameTooLong = 858,
ERR_IdentifierExpected = 1001,
ERR_SemicolonExpected = 1002,
ERR_SyntaxError = 1003,
ERR_DuplicateModifier = 1004,
ERR_DuplicateAccessor = 1007,
ERR_IntegralTypeExpected = 1008,
ERR_IllegalEscape = 1009,
ERR_NewlineInConst = 1010,
ERR_EmptyCharConst = 1011,
ERR_TooManyCharsInConst = 1012,
ERR_InvalidNumber = 1013,
ERR_GetOrSetExpected = 1014,
ERR_ClassTypeExpected = 1015,
ERR_NamedArgumentExpected = 1016,
ERR_TooManyCatches = 1017,
ERR_ThisOrBaseExpected = 1018,
ERR_OvlUnaryOperatorExpected = 1019,
ERR_OvlBinaryOperatorExpected = 1020,
ERR_IntOverflow = 1021,
ERR_EOFExpected = 1022,
ERR_BadEmbeddedStmt = 1023,
ERR_PPDirectiveExpected = 1024,
ERR_EndOfPPLineExpected = 1025,
ERR_CloseParenExpected = 1026,
ERR_EndifDirectiveExpected = 1027,
ERR_UnexpectedDirective = 1028,
ERR_ErrorDirective = 1029,
WRN_WarningDirective = 1030,
ERR_TypeExpected = 1031,
ERR_PPDefFollowsToken = 1032,
//ERR_TooManyLines = 1033, unused in Roslyn.
//ERR_LineTooLong = 1034, unused in Roslyn.
ERR_OpenEndedComment = 1035,
ERR_OvlOperatorExpected = 1037,
ERR_EndRegionDirectiveExpected = 1038,
ERR_UnterminatedStringLit = 1039,
ERR_BadDirectivePlacement = 1040,
ERR_IdentifierExpectedKW = 1041,
ERR_SemiOrLBraceExpected = 1043,
ERR_MultiTypeInDeclaration = 1044,
ERR_AddOrRemoveExpected = 1055,
ERR_UnexpectedCharacter = 1056,
ERR_ProtectedInStatic = 1057,
WRN_UnreachableGeneralCatch = 1058,
ERR_IncrementLvalueExpected = 1059,
WRN_UninitializedField = 1060, //unused in Roslyn but preserving for the purposes of not breaking users' /nowarn settings
ERR_NoSuchMemberOrExtension = 1061,
WRN_DeprecatedCollectionInitAddStr = 1062,
ERR_DeprecatedCollectionInitAddStr = 1063,
WRN_DeprecatedCollectionInitAdd = 1064,
ERR_DefaultValueNotAllowed = 1065,
WRN_DefaultValueForUnconsumedLocation = 1066,
ERR_PartialWrongTypeParamsVariance = 1067,
ERR_GlobalSingleTypeNameNotFoundFwd = 1068,
ERR_DottedTypeNameNotFoundInNSFwd = 1069,
ERR_SingleTypeNameNotFoundFwd = 1070,
//ERR_NoSuchMemberOnNoPIAType = 1071, //EE
// ERR_EOLExpected = 1099, // EE
// ERR_NotSupportedinEE = 1100, // EE
ERR_BadThisParam = 1100,
ERR_BadRefWithThis = 1101,
ERR_BadOutWithThis = 1102,
ERR_BadTypeforThis = 1103,
ERR_BadParamModThis = 1104,
ERR_BadExtensionMeth = 1105,
ERR_BadExtensionAgg = 1106,
ERR_DupParamMod = 1107,
ERR_MultiParamMod = 1108,
ERR_ExtensionMethodsDecl = 1109,
ERR_ExtensionAttrNotFound = 1110,
//ERR_ExtensionTypeParam = 1111,
ERR_ExplicitExtension = 1112,
ERR_ValueTypeExtDelegate = 1113,
// Below five error codes are unused, but we still need to retain them to suppress CS1691 when ""/nowarn:1200,1201,1202,1203,1204"" is specified on the command line.
WRN_FeatureDeprecated2 = 1200,
WRN_FeatureDeprecated3 = 1201,
WRN_FeatureDeprecated4 = 1202,
WRN_FeatureDeprecated5 = 1203,
WRN_OldWarning_FeatureDefaultDeprecated = 1204,
ERR_BadArgCount = 1501,
//ERR_BadArgTypes = 1502,
ERR_BadArgType = 1503,
ERR_NoSourceFile = 1504,
ERR_CantRefResource = 1507,
ERR_ResourceNotUnique = 1508,
ERR_ImportNonAssembly = 1509,
ERR_RefLvalueExpected = 1510,
ERR_BaseInStaticMeth = 1511,
ERR_BaseInBadContext = 1512,
ERR_RbraceExpected = 1513,
ERR_LbraceExpected = 1514,
ERR_InExpected = 1515,
ERR_InvalidPreprocExpr = 1517,
//ERR_BadTokenInType = 1518, unused in Roslyn
ERR_InvalidMemberDecl = 1519,
ERR_MemberNeedsType = 1520,
ERR_BadBaseType = 1521,
WRN_EmptySwitch = 1522,
ERR_ExpectedEndTry = 1524,
ERR_InvalidExprTerm = 1525,
ERR_BadNewExpr = 1526,
ERR_NoNamespacePrivate = 1527,
ERR_BadVarDecl = 1528,
ERR_UsingAfterElements = 1529,
//ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this.
//ERR_DontUseInvoke = 1533,
ERR_BadBinOpArgs = 1534,
ERR_BadUnOpArgs = 1535,
ERR_NoVoidParameter = 1536,
ERR_DuplicateAlias = 1537,
ERR_BadProtectedAccess = 1540,
//ERR_CantIncludeDirectory = 1541,
ERR_AddModuleAssembly = 1542,
ERR_BindToBogusProp2 = 1545,
ERR_BindToBogusProp1 = 1546,
ERR_NoVoidHere = 1547,
//ERR_CryptoFailed = 1548,
//ERR_CryptoNotFound = 1549,
ERR_IndexerNeedsParam = 1551,
ERR_BadArraySyntax = 1552,
ERR_BadOperatorSyntax = 1553,
ERR_BadOperatorSyntax2 = 1554,
ERR_MainClassNotFound = 1555,
ERR_MainClassNotClass = 1556,
ERR_MainClassWrongFile = 1557,
ERR_NoMainInClass = 1558,
ERR_MainClassIsImport = 1559,
//ERR_FileNameTooLong = 1560,
ERR_OutputFileNameTooLong = 1561,
ERR_OutputNeedsName = 1562,
//ERR_OutputNeedsInput = 1563,
ERR_CantHaveWin32ResAndManifest = 1564,
ERR_CantHaveWin32ResAndIcon = 1565,
ERR_CantReadResource = 1566,
//ERR_AutoResGen = 1567,
//ERR_DocFileGen = 1569,
WRN_XMLParseError = 1570,
WRN_DuplicateParamTag = 1571,
WRN_UnmatchedParamTag = 1572,
WRN_MissingParamTag = 1573,
WRN_BadXMLRef = 1574,
ERR_BadStackAllocExpr = 1575,
ERR_InvalidLineNumber = 1576,
//ERR_ALinkFailed = 1577, No alink usage in Roslyn
ERR_MissingPPFile = 1578,
ERR_ForEachMissingMember = 1579,
WRN_BadXMLRefParamType = 1580,
WRN_BadXMLRefReturnType = 1581,
ERR_BadWin32Res = 1583,
WRN_BadXMLRefSyntax = 1584,
ERR_BadModifierLocation = 1585,
ERR_MissingArraySize = 1586,
WRN_UnprocessedXMLComment = 1587,
//ERR_CantGetCORSystemDir = 1588,
WRN_FailedInclude = 1589,
WRN_InvalidInclude = 1590,
WRN_MissingXMLComment = 1591,
WRN_XMLParseIncludeError = 1592,
ERR_BadDelArgCount = 1593,
//ERR_BadDelArgTypes = 1594,
WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1595"" is specified on the command line.
WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1596"" is specified on the command line.
ERR_UnexpectedSemicolon = 1597,
WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time).
ERR_MethodReturnCantBeRefAny = 1599,
ERR_CompileCancelled = 1600,
ERR_MethodArgCantBeRefAny = 1601,
ERR_AssgReadonlyLocal = 1604,
ERR_RefReadonlyLocal = 1605,
//ERR_ALinkCloseFailed = 1606,
WRN_ALinkWarn = 1607, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1607"" is specified on the command line.
ERR_CantUseRequiredAttribute = 1608,
ERR_NoModifiersOnAccessor = 1609,
WRN_DeleteAutoResFailed = 1610, // Unused but preserving for /nowarn
ERR_ParamsCantBeRefOut = 1611,
ERR_ReturnNotLValue = 1612,
ERR_MissingCoClass = 1613,
ERR_AmbiguousAttribute = 1614,
ERR_BadArgExtraRef = 1615,
WRN_CmdOptionConflictsSource = 1616,
ERR_BadCompatMode = 1617,
ERR_DelegateOnConditional = 1618,
//ERR_CantMakeTempFile = 1619,
ERR_BadArgRef = 1620,
ERR_YieldInAnonMeth = 1621,
ERR_ReturnInIterator = 1622,
ERR_BadIteratorArgType = 1623,
ERR_BadIteratorReturn = 1624,
ERR_BadYieldInFinally = 1625,
ERR_BadYieldInTryOfCatch = 1626,
ERR_EmptyYield = 1627,
ERR_AnonDelegateCantUse = 1628,
ERR_IllegalInnerUnsafe = 1629,
//ERR_BadWatsonMode = 1630,
ERR_BadYieldInCatch = 1631,
ERR_BadDelegateLeave = 1632,
WRN_IllegalPragma = 1633,
WRN_IllegalPPWarning = 1634,
WRN_BadRestoreNumber = 1635,
ERR_VarargsIterator = 1636,
ERR_UnsafeIteratorArgType = 1637,
//ERR_ReservedIdentifier = 1638,
ERR_BadCoClassSig = 1639,
ERR_MultipleIEnumOfT = 1640,
ERR_FixedDimsRequired = 1641,
ERR_FixedNotInStruct = 1642,
ERR_AnonymousReturnExpected = 1643,
ERR_NonECMAFeature = 1644,
WRN_NonECMAFeature = 1645,
ERR_ExpectedVerbatimLiteral = 1646,
//FTL_StackOverflow = 1647,
ERR_AssgReadonly2 = 1648,
ERR_RefReadonly2 = 1649,
ERR_AssgReadonlyStatic2 = 1650,
ERR_RefReadonlyStatic2 = 1651,
ERR_AssgReadonlyLocal2Cause = 1654,
ERR_RefReadonlyLocal2Cause = 1655,
ERR_AssgReadonlyLocalCause = 1656,
ERR_RefReadonlyLocalCause = 1657,
WRN_ErrorOverride = 1658,
WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1659"" is specified on the command line.
ERR_AnonMethToNonDel = 1660,
ERR_CantConvAnonMethParams = 1661,
ERR_CantConvAnonMethReturns = 1662,
ERR_IllegalFixedType = 1663,
ERR_FixedOverflow = 1664,
ERR_InvalidFixedArraySize = 1665,
ERR_FixedBufferNotFixed = 1666,
ERR_AttributeNotOnAccessor = 1667,
WRN_InvalidSearchPathDir = 1668,
ERR_IllegalVarArgs = 1669,
ERR_IllegalParams = 1670,
ERR_BadModifiersOnNamespace = 1671,
ERR_BadPlatformType = 1672,
ERR_ThisStructNotInAnonMeth = 1673,
ERR_NoConvToIDisp = 1674,
// ERR_InvalidGenericEnum = 1675, replaced with 7002
ERR_BadParamRef = 1676,
ERR_BadParamExtraRef = 1677,
ERR_BadParamType = 1678,
ERR_BadExternIdentifier = 1679,
ERR_AliasMissingFile = 1680,
ERR_GlobalExternAlias = 1681,
WRN_MissingTypeNested = 1682, //unused in Roslyn.
// 1683 and 1684 are unused warning codes, but we still need to retain them to suppress CS1691 when ""/nowarn:1683"" is specified on the command line.
// In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively.
WRN_MissingTypeInSource = 1683,
WRN_MissingTypeInAssembly = 1684,
WRN_MultiplePredefTypes = 1685,
ERR_LocalCantBeFixedAndHoisted = 1686,
WRN_TooManyLinesForDebugger = 1687,
ERR_CantConvAnonMethNoParams = 1688,
ERR_ConditionalOnNonAttributeClass = 1689,
WRN_CallOnNonAgileField = 1690,
WRN_BadWarningNumber = 1691,
WRN_InvalidNumber = 1692,
WRN_FileNameTooLong = 1694, //unused but preserving for the sake of existing code using /nowarn:1694
WRN_IllegalPPChecksum = 1695,
WRN_EndOfPPLineExpected = 1696,
WRN_ConflictingChecksum = 1697,
WRN_AssumedMatchThis = 1698,
WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1699"" is specified.
WRN_InvalidAssemblyName = 1700, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1700"" is specified.
WRN_UnifyReferenceMajMin = 1701,
WRN_UnifyReferenceBldRev = 1702,
ERR_DuplicateImport = 1703,
ERR_DuplicateImportSimple = 1704,
ERR_AssemblyMatchBadVersion = 1705,
ERR_AnonMethNotAllowed = 1706,
WRN_DelegateNewMethBind = 1707, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1707"" is specified.
ERR_FixedNeedsLvalue = 1708,
WRN_EmptyFileName = 1709,
WRN_DuplicateTypeParamTag = 1710,
WRN_UnmatchedTypeParamTag = 1711,
WRN_MissingTypeParamTag = 1712,
//FTL_TypeNameBuilderError = 1713,
ERR_ImportBadBase = 1714,
ERR_CantChangeTypeOnOverride = 1715,
ERR_DoNotUseFixedBufferAttr = 1716,
WRN_AssignmentToSelf = 1717,
WRN_ComparisonToSelf = 1718,
ERR_CantOpenWin32Res = 1719,
WRN_DotOnDefault = 1720,
ERR_NoMultipleInheritance = 1721,
ERR_BaseClassMustBeFirst = 1722,
WRN_BadXMLRefTypeVar = 1723,
//ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn.
ERR_FriendAssemblyBadArgs = 1725,
ERR_FriendAssemblySNReq = 1726,
//ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings.
ERR_DelegateOnNullable = 1728,
ERR_BadCtorArgCount = 1729,
ERR_GlobalAttributesNotFirst = 1730,
ERR_CantConvAnonMethReturnsNoDelegate = 1731,
//ERR_ParameterExpected = 1732, Not used in Roslyn.
ERR_ExpressionExpected = 1733,
WRN_UnmatchedParamRefTag = 1734,
WRN_UnmatchedTypeParamRefTag = 1735,
ERR_DefaultValueMustBeConstant = 1736,
ERR_DefaultValueBeforeRequiredValue = 1737,
ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738,
ERR_BadNamedArgument = 1739,
ERR_DuplicateNamedArgument = 1740,
ERR_RefOutDefaultValue = 1741,
ERR_NamedArgumentForArray = 1742,
ERR_DefaultValueForExtensionParameter = 1743,
ERR_NamedArgumentUsedInPositional = 1744,
ERR_DefaultValueUsedWithAttributes = 1745,
ERR_BadNamedArgumentForDelegateInvoke = 1746,
ERR_NoPIAAssemblyMissingAttribute = 1747,
ERR_NoCanonicalView = 1748,
//ERR_TypeNotFoundForNoPIA = 1749,
ERR_NoConversionForDefaultParam = 1750,
ERR_DefaultValueForParamsParameter = 1751,
ERR_NewCoClassOnLink = 1752,
ERR_NoPIANestedType = 1754,
//ERR_InvalidTypeIdentifierConstructor = 1755,
ERR_InteropTypeMissingAttribute = 1756,
ERR_InteropStructContainsMethods = 1757,
ERR_InteropTypesWithSameNameAndGuid = 1758,
ERR_NoPIAAssemblyMissingAttributes = 1759,
ERR_AssemblySpecifiedForLinkAndRef = 1760,
ERR_LocalTypeNameClash = 1761,
WRN_ReferencedAssemblyReferencesLinkedPIA = 1762,
ERR_NotNullRefDefaultParameter = 1763,
ERR_FixedLocalInLambda = 1764,
WRN_TypeNotFoundForNoPIAWarning = 1765,
ERR_MissingMethodOnSourceInterface = 1766,
ERR_MissingSourceInterface = 1767,
ERR_GenericsUsedInNoPIAType = 1768,
ERR_GenericsUsedAcrossAssemblies = 1769,
ERR_NoConversionForNubDefaultParam = 1770,
//ERR_MemberWithGenericsUsedAcrossAssemblies = 1771,
//ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772,
ERR_BadSubsystemVersion = 1773,
ERR_InteropMethodWithBody = 1774,
ERR_BadWarningLevel = 1900,
ERR_BadDebugType = 1902,
//ERR_UnknownTestSwitch = 1903,
ERR_BadResourceVis = 1906,
ERR_DefaultValueTypeMustMatch = 1908,
//ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn.
ERR_DefaultValueBadValueType = 1910,
ERR_MemberAlreadyInitialized = 1912,
ERR_MemberCannotBeInitialized = 1913,
ERR_StaticMemberInObjectInitializer = 1914,
ERR_ReadonlyValueTypeInObjectInitializer = 1917,
ERR_ValueTypePropertyInObjectInitializer = 1918,
ERR_UnsafeTypeInObjectCreation = 1919,
ERR_EmptyElementInitializer = 1920,
ERR_InitializerAddHasWrongSignature = 1921,
ERR_CollectionInitRequiresIEnumerable = 1922,
ERR_InvalidCollectionInitializerType = 1925,
ERR_CantOpenWin32Manifest = 1926,
WRN_CantHaveManifestForModule = 1927,
ERR_BadExtensionArgTypes = 1928,
ERR_BadInstanceArgType = 1929,
ERR_QueryDuplicateRangeVariable = 1930,
ERR_QueryRangeVariableOverrides = 1931,
ERR_QueryRangeVariableAssignedBadValue = 1932,
ERR_QueryNotAllowed = 1933,
ERR_QueryNoProviderCastable = 1934,
ERR_QueryNoProviderStandard = 1935,
ERR_QueryNoProvider = 1936,
ERR_QueryOuterKey = 1937,
ERR_QueryInnerKey = 1938,
ERR_QueryOutRefRangeVariable = 1939,
ERR_QueryMultipleProviders = 1940,
ERR_QueryTypeInferenceFailedMulti = 1941,
ERR_QueryTypeInferenceFailed = 1942,
ERR_QueryTypeInferenceFailedSelectMany = 1943,
ERR_ExpressionTreeContainsPointerOp = 1944,
ERR_ExpressionTreeContainsAnonymousMethod = 1945,
ERR_AnonymousMethodToExpressionTree = 1946,
ERR_QueryRangeVariableReadOnly = 1947,
ERR_QueryRangeVariableSameAsTypeParam = 1948,
ERR_TypeVarNotFoundRangeVariable = 1949,
ERR_BadArgTypesForCollectionAdd = 1950,
ERR_ByRefParameterInExpressionTree = 1951,
ERR_VarArgsInExpressionTree = 1952,
ERR_MemGroupInExpressionTree = 1953,
ERR_InitializerAddHasParamModifiers = 1954,
ERR_NonInvocableMemberCalled = 1955,
WRN_MultipleRuntimeImplementationMatches = 1956,
WRN_MultipleRuntimeOverrideMatches = 1957,
ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958,
ERR_InvalidConstantDeclarationType = 1959,
ERR_IllegalVarianceSyntax = 1960,
ERR_UnexpectedVariance = 1961,
ERR_BadDynamicTypeof = 1962,
ERR_ExpressionTreeContainsDynamicOperation = 1963,
ERR_BadDynamicConversion = 1964,
ERR_DeriveFromDynamic = 1965,
ERR_DeriveFromConstructedDynamic = 1966,
ERR_DynamicTypeAsBound = 1967,
ERR_ConstructedDynamicTypeAsBound = 1968,
ERR_DynamicRequiredTypesMissing = 1969,
ERR_ExplicitDynamicAttr = 1970,
ERR_NoDynamicPhantomOnBase = 1971,
ERR_NoDynamicPhantomOnBaseIndexer = 1972,
ERR_BadArgTypeDynamicExtension = 1973,
WRN_DynamicDispatchToConditionalMethod = 1974,
ERR_NoDynamicPhantomOnBaseCtor = 1975,
ERR_BadDynamicMethodArgMemgrp = 1976,
ERR_BadDynamicMethodArgLambda = 1977,
ERR_BadDynamicMethodArg = 1978,
ERR_BadDynamicQuery = 1979,
ERR_DynamicAttributeMissing = 1980,
WRN_IsDynamicIsConfusing = 1981,
ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn.
ERR_BadAsyncReturn = 1983,
ERR_BadAwaitInFinally = 1984,
ERR_BadAwaitInCatch = 1985,
ERR_BadAwaitArg = 1986,
ERR_BadAsyncArgType = 1988,
ERR_BadAsyncExpressionTree = 1989,
ERR_WindowsRuntimeTypesMissing = 1990,
ERR_MixingWinRTEventWithRegular = 1991,
ERR_BadAwaitWithoutAsync = 1992,
ERR_MissingAsyncTypes = 1993,
ERR_BadAsyncLacksBody = 1994,
ERR_BadAwaitInQuery = 1995,
ERR_BadAwaitInLock = 1996,
ERR_TaskRetNoObjectRequired = 1997,
WRN_AsyncLacksAwaits = 1998,
ERR_FileNotFound = 2001,
WRN_FileAlreadyIncluded = 2002,
ERR_DuplicateResponseFile = 2003,
ERR_NoFileSpec = 2005,
ERR_SwitchNeedsString = 2006,
ERR_BadSwitch = 2007,
WRN_NoSources = 2008,
ERR_OpenResponseFile = 2011,
ERR_CantOpenFileWrite = 2012,
ERR_BadBaseNumber = 2013,
WRN_UseNewSwitch = 2014, //unused but preserved to keep compat with /nowarn:2014
ERR_BinaryFile = 2015,
FTL_BadCodepage = 2016,
ERR_NoMainOnDLL = 2017,
//FTL_NoMessagesDLL = 2018,
FTL_InvalidTarget = 2019,
//ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once!
FTL_InvalidInputFileName = 2021,
//ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once!
WRN_NoConfigNotOnCommandLine = 2023,
ERR_BadFileAlignment = 2024,
//ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn.
//ERR_SourceMapFileBinary = 2027,
WRN_DefineIdentifierRequired = 2029,
//ERR_InvalidSourceMap = 2030,
//ERR_NoSourceMapFile = 2031,
ERR_IllegalOptionChar = 2032,
FTL_OutputFileExists = 2033,
ERR_OneAliasPerReference = 2034,
ERR_SwitchNeedsNumber = 2035,
ERR_MissingDebugSwitch = 2036,
ERR_ComRefCallInExpressionTree = 2037,
WRN_BadUILang = 2038,
WRN_CLS_NoVarArgs = 3000,
WRN_CLS_BadArgType = 3001,
WRN_CLS_BadReturnType = 3002,
WRN_CLS_BadFieldPropType = 3003,
WRN_CLS_BadUnicode = 3004, //unused but preserved to keep compat with /nowarn:3004
WRN_CLS_BadIdentifierCase = 3005,
WRN_CLS_OverloadRefOut = 3006,
WRN_CLS_OverloadUnnamed = 3007,
WRN_CLS_BadIdentifier = 3008,
WRN_CLS_BadBase = 3009,
WRN_CLS_BadInterfaceMember = 3010,
WRN_CLS_NoAbstractMembers = 3011,
WRN_CLS_NotOnModules = 3012,
WRN_CLS_ModuleMissingCLS = 3013,
WRN_CLS_AssemblyNotCLS = 3014,
WRN_CLS_BadAttributeType = 3015,
WRN_CLS_ArrayArgumentToAttribute = 3016,
WRN_CLS_NotOnModules2 = 3017,
WRN_CLS_IllegalTrueInFalse = 3018,
WRN_CLS_MeaninglessOnPrivateType = 3019,
WRN_CLS_AssemblyNotCLS2 = 3021,
WRN_CLS_MeaninglessOnParam = 3022,
WRN_CLS_MeaninglessOnReturn = 3023,
WRN_CLS_BadTypeVar = 3024,
WRN_CLS_VolatileField = 3026,
WRN_CLS_BadInterface = 3027,
// Errors introduced in C# 5 are in the range 4000-4999
// 4000 unused
ERR_BadAwaitArgIntrinsic = 4001,
// 4002 unused
ERR_BadAwaitAsIdentifier = 4003,
ERR_AwaitInUnsafeContext = 4004,
ERR_UnsafeAsyncArgType = 4005,
ERR_VarargsAsync = 4006,
ERR_ByRefTypeAndAwait = 4007,
ERR_BadAwaitArgVoidCall = 4008,
ERR_MainCantBeAsync = 4009,
ERR_CantConvAsyncAnonFuncReturns = 4010,
ERR_BadAwaiterPattern = 4011,
ERR_BadSpecialByRefLocal = 4012,
ERR_SpecialByRefInLambda = 4013,
WRN_UnobservedAwaitableExpression = 4014,
ERR_SynchronizedAsyncMethod = 4015,
ERR_BadAsyncReturnExpression = 4016,
ERR_NoConversionForCallerLineNumberParam = 4017,
ERR_NoConversionForCallerFilePathParam = 4018,
ERR_NoConversionForCallerMemberNameParam = 4019,
ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020,
ERR_BadCallerFilePathParamWithoutDefaultValue = 4021,
ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022,
ERR_BadPrefer32OnLib = 4023,
WRN_CallerLineNumberParamForUnconsumedLocation = 4024,
WRN_CallerFilePathParamForUnconsumedLocation = 4025,
WRN_CallerMemberNameParamForUnconsumedLocation = 4026,
ERR_DoesntImplementAwaitInterface = 4027,
ERR_BadAwaitArg_NeedSystem = 4028,
ERR_CantReturnVoid = 4029,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031,
ERR_BadAwaitWithoutAsyncMethod = 4032,
ERR_BadAwaitWithoutVoidAsyncMethod = 4033,
ERR_BadAwaitWithoutAsyncLambda = 4034,
// ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn
ERR_NoSuchMemberOrExtensionNeedUsing = 4036,
WRN_UnknownOption = 5000, //unused in Roslyn
ERR_NoEntryPoint = 5001,
// There is space in the range of error codes from 7000-8999 that
// we can use for new errors in post-Dev10.
ERR_UnexpectedAliasedName = 7000,
ERR_UnexpectedGenericName = 7002,
ERR_UnexpectedUnboundGenericName = 7003,
ERR_GlobalStatement = 7006,
ERR_BadUsingType = 7007,
ERR_ReservedAssemblyName = 7008,
ERR_PPReferenceFollowsToken = 7009,
ERR_ExpectedPPFile = 7010,
ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011,
ERR_NameNotInContextPossibleMissingReference = 7012,
WRN_MetadataNameTooLong = 7013,
ERR_AttributesNotAllowed = 7014,
ERR_ExternAliasNotAllowed = 7015,
ERR_ConflictingAliasAndDefinition = 7016,
ERR_GlobalDefinitionOrStatementExpected = 7017,
ERR_ExpectedSingleScript = 7018,
ERR_RecursivelyTypedVariable = 7019,
ERR_ReturnNotAllowedInScript = 7020,
ERR_NamespaceNotAllowedInScript = 7021,
WRN_MainIgnored = 7022,
ERR_StaticInAsOrIs = 7023,
ERR_InvalidDelegateType = 7024,
ERR_BadVisEventType = 7025,
ERR_GlobalAttributesNotAllowed = 7026,
ERR_PublicKeyFileFailure = 7027,
ERR_PublicKeyContainerFailure = 7028,
ERR_FriendRefSigningMismatch = 7029,
ERR_CannotPassNullForFriendAssembly = 7030,
ERR_SignButNoPrivateKey = 7032,
WRN_DelaySignButNoKey = 7033,
ERR_InvalidVersionFormat = 7034,
WRN_InvalidVersionFormat = 7035,
ERR_NoCorrespondingArgument = 7036,
// Moot: WRN_DestructorIsNotFinalizer = 7037,
ERR_ModuleEmitFailure = 7038,
ERR_NameIllegallyOverrides2 = 7039,
ERR_NameIllegallyOverrides3 = 7040,
ERR_ResourceFileNameNotUnique = 7041,
ERR_DllImportOnGenericMethod = 7042,
ERR_LibraryMethodNotFound = 7043,
ERR_LibraryMethodNotUnique = 7044,
ERR_ParameterNotValidForType = 7045,
ERR_AttributeParameterRequired1 = 7046,
ERR_AttributeParameterRequired2 = 7047,
ERR_SecurityAttributeMissingAction = 7048,
ERR_SecurityAttributeInvalidAction = 7049,
ERR_SecurityAttributeInvalidActionAssembly = 7050,
ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051,
ERR_PrincipalPermissionInvalidAction = 7052,
ERR_FeatureNotValidInExpressionTree = 7053,
ERR_MarshalUnmanagedTypeNotValidForFields = 7054,
ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055,
ERR_PermissionSetAttributeInvalidFile = 7056,
ERR_PermissionSetAttributeFileReadError = 7057,
ERR_InvalidVersionFormat2 = 7058,
ERR_InvalidAssemblyCultureForExe = 7059,
ERR_AsyncBeforeVersionFive = 7060,
ERR_DuplicateAttributeInNetModule = 7061,
//WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning
ERR_CantOpenIcon = 7064,
ERR_ErrorBuildingWin32Resources = 7065,
ERR_IteratorInInteractive = 7066,
ERR_BadAttributeParamDefaultArgument = 7067,
ERR_MissingTypeInSource = 7068,
ERR_MissingTypeInAssembly = 7069,
ERR_SecurityAttributeInvalidTarget = 7070,
ERR_InvalidAssemblyName = 7071,
ERR_PartialTypesBeforeVersionTwo = 7072,
ERR_PartialMethodsBeforeVersionThree = 7073,
ERR_QueryBeforeVersionThree = 7074,
ERR_AnonymousTypeBeforeVersionThree = 7075,
ERR_ImplicitArrayBeforeVersionThree = 7076,
ERR_ObjectInitializerBeforeVersionThree = 7077,
ERR_LambdaBeforeVersionThree = 7078,
ERR_NoTypeDefFromModule = 7079,
WRN_CallerFilePathPreferredOverCallerMemberName = 7080,
WRN_CallerLineNumberPreferredOverCallerMemberName = 7081,
WRN_CallerLineNumberPreferredOverCallerFilePath = 7082,
ERR_InvalidDynamicCondition = 7083,
ERR_WinRtEventPassedByRef = 7084,
ERR_ByRefReturnUnsupported = 7085,
ERR_NetModuleNameMismatch = 7086,
ERR_BadCompilationOption = 7087,
ERR_BadCompilationOptionValue = 7088,
ERR_BadAppConfigPath = 7089,
WRN_AssemblyAttributeFromModuleIsOverridden = 7090,
ERR_CmdOptionConflictsSource = 7091,
ERR_FixedBufferTooManyDimensions = 7092,
ERR_CantReadConfigFile = 7093,
ERR_NotYetImplementedInRoslyn = 8000,
WRN_UnimplementedCommandLineSwitch = 8001,
ERR_ReferencedAssemblyDoesNotHaveStrongName = 8002,
ERR_InvalidSignaturePublicKey = 8003,
ERR_ExportedTypeConflictsWithDeclaration = 8004,
ERR_ExportedTypesConflict = 8005,
ERR_ForwardedTypeConflictsWithDeclaration = 8006,
ERR_ForwardedTypesConflict = 8007,
ERR_ForwardedTypeConflictsWithExportedType = 8008,
WRN_RefCultureMismatch = 8009,
ERR_AgnosticToMachineModule = 8010,
ERR_ConflictingMachineModule = 8011,
WRN_ConflictingMachineAssembly = 8012,
ERR_CryptoHashFailed = 8013,
ERR_MissingNetModuleReference = 8014,
// Values in the range 10000-14000 are used for ""Code Analysis"" issues previously reported by FXCop
WRN_CA2000_DisposeObjectsBeforeLosingScope1 = 10000,
WRN_CA2000_DisposeObjectsBeforeLosingScope2 = 10001,
WRN_CA2202_DoNotDisposeObjectsMultipleTimes = 10002
}
/// <summary>
/// Values for ErrorCode/ERRID that are used internally by the compiler but are not exposed.
/// </summary>
internal static class InternalErrorCode
{
/// <summary>
/// The code has yet to be determined.
/// </summary>
public const int Unknown = -1;
/// <summary>
/// The code was lazily determined and does not need to be reported.
/// </summary>
public const int Void = -2;
}
}
}
";
var compVerifier = CompileAndVerify(text);
compVerifier.VerifyIL("ConsoleApplication24.Program.IsWarning", @"
{
// Code size 1889 (0x761)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x32b
IL_0006: bgt IL_0300
IL_000b: ldarg.0
IL_000c: ldc.i4 0x1ad
IL_0011: bgt IL_0154
IL_0016: ldarg.0
IL_0017: ldc.i4 0xb8
IL_001c: bgt IL_00a9
IL_0021: ldarg.0
IL_0022: ldc.i4.s 109
IL_0024: bgt.s IL_005f
IL_0026: ldarg.0
IL_0027: ldc.i4.s 67
IL_0029: bgt.s IL_0040
IL_002b: ldarg.0
IL_002c: ldc.i4.s 28
IL_002e: beq IL_075d
IL_0033: ldarg.0
IL_0034: ldc.i4.s 67
IL_0036: beq IL_075d
IL_003b: br IL_075f
IL_0040: ldarg.0
IL_0041: ldc.i4.s 78
IL_0043: beq IL_075d
IL_0048: ldarg.0
IL_0049: ldc.i4.s 105
IL_004b: beq IL_075d
IL_0050: ldarg.0
IL_0051: ldc.i4.s 108
IL_0053: sub
IL_0054: ldc.i4.1
IL_0055: ble.un IL_075d
IL_005a: br IL_075f
IL_005f: ldarg.0
IL_0060: ldc.i4 0xa2
IL_0065: bgt.s IL_007f
IL_0067: ldarg.0
IL_0068: ldc.i4.s 114
IL_006a: beq IL_075d
IL_006f: ldarg.0
IL_0070: ldc.i4 0xa2
IL_0075: beq IL_075d
IL_007a: br IL_075f
IL_007f: ldarg.0
IL_0080: ldc.i4 0xa4
IL_0085: beq IL_075d
IL_008a: ldarg.0
IL_008b: ldc.i4 0xa8
IL_0090: sub
IL_0091: ldc.i4.1
IL_0092: ble.un IL_075d
IL_0097: ldarg.0
IL_0098: ldc.i4 0xb7
IL_009d: sub
IL_009e: ldc.i4.1
IL_009f: ble.un IL_075d
IL_00a4: br IL_075f
IL_00a9: ldarg.0
IL_00aa: ldc.i4 0x118
IL_00af: bgt.s IL_00fe
IL_00b1: ldarg.0
IL_00b2: ldc.i4 0xcf
IL_00b7: bgt.s IL_00d4
IL_00b9: ldarg.0
IL_00ba: ldc.i4 0xc5
IL_00bf: beq IL_075d
IL_00c4: ldarg.0
IL_00c5: ldc.i4 0xcf
IL_00ca: beq IL_075d
IL_00cf: br IL_075f
IL_00d4: ldarg.0
IL_00d5: ldc.i4 0xdb
IL_00da: beq IL_075d
IL_00df: ldarg.0
IL_00e0: ldc.i4 0xfb
IL_00e5: sub
IL_00e6: ldc.i4.2
IL_00e7: ble.un IL_075d
IL_00ec: ldarg.0
IL_00ed: ldc.i4 0x116
IL_00f2: sub
IL_00f3: ldc.i4.2
IL_00f4: ble.un IL_075d
IL_00f9: br IL_075f
IL_00fe: ldarg.0
IL_00ff: ldc.i4 0x19e
IL_0104: bgt.s IL_012c
IL_0106: ldarg.0
IL_0107: ldc.i4 0x11a
IL_010c: beq IL_075d
IL_0111: ldarg.0
IL_0112: ldc.i4 0x192
IL_0117: beq IL_075d
IL_011c: ldarg.0
IL_011d: ldc.i4 0x19e
IL_0122: beq IL_075d
IL_0127: br IL_075f
IL_012c: ldarg.0
IL_012d: ldc.i4 0x1a3
IL_0132: sub
IL_0133: ldc.i4.1
IL_0134: ble.un IL_075d
IL_0139: ldarg.0
IL_013a: ldc.i4 0x1a6
IL_013f: beq IL_075d
IL_0144: ldarg.0
IL_0145: ldc.i4 0x1ad
IL_014a: beq IL_075d
IL_014f: br IL_075f
IL_0154: ldarg.0
IL_0155: ldc.i4 0x274
IL_015a: bgt IL_0224
IL_015f: ldarg.0
IL_0160: ldc.i4 0x1d9
IL_0165: bgt.s IL_01db
IL_0167: ldarg.0
IL_0168: ldc.i4 0x1b8
IL_016d: bgt.s IL_018c
IL_016f: ldarg.0
IL_0170: ldc.i4 0x1b3
IL_0175: sub
IL_0176: ldc.i4.2
IL_0177: ble.un IL_075d
IL_017c: ldarg.0
IL_017d: ldc.i4 0x1b8
IL_0182: beq IL_075d
IL_0187: br IL_075f
IL_018c: ldarg.0
IL_018d: ldc.i4 0x1bc
IL_0192: beq IL_075d
IL_0197: ldarg.0
IL_0198: ldc.i4 0x1ca
IL_019d: beq IL_075d
IL_01a2: ldarg.0
IL_01a3: ldc.i4 0x1d0
IL_01a8: sub
IL_01a9: switch (
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075d)
IL_01d6: br IL_075f
IL_01db: ldarg.0
IL_01dc: ldc.i4 0x264
IL_01e1: bgt.s IL_01fe
IL_01e3: ldarg.0
IL_01e4: ldc.i4 0x25a
IL_01e9: beq IL_075d
IL_01ee: ldarg.0
IL_01ef: ldc.i4 0x264
IL_01f4: beq IL_075d
IL_01f9: br IL_075f
IL_01fe: ldarg.0
IL_01ff: ldc.i4 0x26a
IL_0204: beq IL_075d
IL_0209: ldarg.0
IL_020a: ldc.i4 0x272
IL_020f: beq IL_075d
IL_0214: ldarg.0
IL_0215: ldc.i4 0x274
IL_021a: beq IL_075d
IL_021f: br IL_075f
IL_0224: ldarg.0
IL_0225: ldc.i4 0x2a3
IL_022a: bgt.s IL_02aa
IL_022c: ldarg.0
IL_022d: ldc.i4 0x295
IL_0232: bgt.s IL_0284
IL_0234: ldarg.0
IL_0235: ldc.i4 0x282
IL_023a: beq IL_075d
IL_023f: ldarg.0
IL_0240: ldc.i4 0x289
IL_0245: sub
IL_0246: switch (
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d)
IL_027f: br IL_075f
IL_0284: ldarg.0
IL_0285: ldc.i4 0x299
IL_028a: beq IL_075d
IL_028f: ldarg.0
IL_0290: ldc.i4 0x2a0
IL_0295: beq IL_075d
IL_029a: ldarg.0
IL_029b: ldc.i4 0x2a3
IL_02a0: beq IL_075d
IL_02a5: br IL_075f
IL_02aa: ldarg.0
IL_02ab: ldc.i4 0x2b5
IL_02b0: bgt.s IL_02da
IL_02b2: ldarg.0
IL_02b3: ldc.i4 0x2a7
IL_02b8: sub
IL_02b9: ldc.i4.1
IL_02ba: ble.un IL_075d
IL_02bf: ldarg.0
IL_02c0: ldc.i4 0x2ac
IL_02c5: beq IL_075d
IL_02ca: ldarg.0
IL_02cb: ldc.i4 0x2b5
IL_02d0: beq IL_075d
IL_02d5: br IL_075f
IL_02da: ldarg.0
IL_02db: ldc.i4 0x2d8
IL_02e0: beq IL_075d
IL_02e5: ldarg.0
IL_02e6: ldc.i4 0x329
IL_02eb: beq IL_075d
IL_02f0: ldarg.0
IL_02f1: ldc.i4 0x32b
IL_02f6: beq IL_075d
IL_02fb: br IL_075f
IL_0300: ldarg.0
IL_0301: ldc.i4 0x7bd
IL_0306: bgt IL_05d1
IL_030b: ldarg.0
IL_030c: ldc.i4 0x663
IL_0311: bgt IL_0451
IL_0316: ldarg.0
IL_0317: ldc.i4 0x5f2
IL_031c: bgt.s IL_038e
IL_031e: ldarg.0
IL_031f: ldc.i4 0x406
IL_0324: bgt.s IL_0341
IL_0326: ldarg.0
IL_0327: ldc.i4 0x338
IL_032c: beq IL_075d
IL_0331: ldarg.0
IL_0332: ldc.i4 0x406
IL_0337: beq IL_075d
IL_033c: br IL_075f
IL_0341: ldarg.0
IL_0342: ldc.i4 0x422
IL_0347: sub
IL_0348: switch (
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d)
IL_0371: ldarg.0
IL_0372: ldc.i4 0x4b0
IL_0377: sub
IL_0378: ldc.i4.4
IL_0379: ble.un IL_075d
IL_037e: ldarg.0
IL_037f: ldc.i4 0x5f2
IL_0384: beq IL_075d
IL_0389: br IL_075f
IL_038e: ldarg.0
IL_038f: ldc.i4 0x647
IL_0394: bgt IL_0429
IL_0399: ldarg.0
IL_039a: ldc.i4 0x622
IL_039f: sub
IL_03a0: switch (
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075f,
IL_075d)
IL_0419: ldarg.0
IL_041a: ldc.i4 0x647
IL_041f: beq IL_075d
IL_0424: br IL_075f
IL_0429: ldarg.0
IL_042a: ldc.i4 0x64a
IL_042f: beq IL_075d
IL_0434: ldarg.0
IL_0435: ldc.i4 0x650
IL_043a: beq IL_075d
IL_043f: ldarg.0
IL_0440: ldc.i4 0x661
IL_0445: sub
IL_0446: ldc.i4.2
IL_0447: ble.un IL_075d
IL_044c: br IL_075f
IL_0451: ldarg.0
IL_0452: ldc.i4 0x6c7
IL_0457: bgt IL_057b
IL_045c: ldarg.0
IL_045d: ldc.i4 0x67b
IL_0462: bgt.s IL_0481
IL_0464: ldarg.0
IL_0465: ldc.i4 0x66d
IL_046a: beq IL_075d
IL_046f: ldarg.0
IL_0470: ldc.i4 0x67a
IL_0475: sub
IL_0476: ldc.i4.1
IL_0477: ble.un IL_075d
IL_047c: br IL_075f
IL_0481: ldarg.0
IL_0482: ldc.i4 0x684
IL_0487: sub
IL_0488: switch (
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d)
IL_0541: ldarg.0
IL_0542: ldc.i4 0x6b5
IL_0547: sub
IL_0548: switch (
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d)
IL_0569: ldarg.0
IL_056a: ldc.i4 0x6c6
IL_056f: sub
IL_0570: ldc.i4.1
IL_0571: ble.un IL_075d
IL_0576: br IL_075f
IL_057b: ldarg.0
IL_057c: ldc.i4 0x787
IL_0581: bgt.s IL_05a9
IL_0583: ldarg.0
IL_0584: ldc.i4 0x6e2
IL_0589: beq IL_075d
IL_058e: ldarg.0
IL_058f: ldc.i4 0x6e5
IL_0594: beq IL_075d
IL_0599: ldarg.0
IL_059a: ldc.i4 0x787
IL_059f: beq IL_075d
IL_05a4: br IL_075f
IL_05a9: ldarg.0
IL_05aa: ldc.i4 0x7a4
IL_05af: sub
IL_05b0: ldc.i4.1
IL_05b1: ble.un IL_075d
IL_05b6: ldarg.0
IL_05b7: ldc.i4 0x7b6
IL_05bc: beq IL_075d
IL_05c1: ldarg.0
IL_05c2: ldc.i4 0x7bd
IL_05c7: beq IL_075d
IL_05cc: br IL_075f
IL_05d1: ldarg.0
IL_05d2: ldc.i4 0xfba
IL_05d7: bgt IL_06e3
IL_05dc: ldarg.0
IL_05dd: ldc.i4 0x7e7
IL_05e2: bgt.s IL_062d
IL_05e4: ldarg.0
IL_05e5: ldc.i4 0x7d2
IL_05ea: bgt.s IL_0607
IL_05ec: ldarg.0
IL_05ed: ldc.i4 0x7ce
IL_05f2: beq IL_075d
IL_05f7: ldarg.0
IL_05f8: ldc.i4 0x7d2
IL_05fd: beq IL_075d
IL_0602: br IL_075f
IL_0607: ldarg.0
IL_0608: ldc.i4 0x7d8
IL_060d: beq IL_075d
IL_0612: ldarg.0
IL_0613: ldc.i4 0x7de
IL_0618: beq IL_075d
IL_061d: ldarg.0
IL_061e: ldc.i4 0x7e7
IL_0623: beq IL_075d
IL_0628: br IL_075f
IL_062d: ldarg.0
IL_062e: ldc.i4 0x7f6
IL_0633: bgt.s IL_0650
IL_0635: ldarg.0
IL_0636: ldc.i4 0x7ed
IL_063b: beq IL_075d
IL_0640: ldarg.0
IL_0641: ldc.i4 0x7f6
IL_0646: beq IL_075d
IL_064b: br IL_075f
IL_0650: ldarg.0
IL_0651: ldc.i4 0xbb8
IL_0656: sub
IL_0657: switch (
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075d)
IL_06cc: ldarg.0
IL_06cd: ldc.i4 0xfae
IL_06d2: beq IL_075d
IL_06d7: ldarg.0
IL_06d8: ldc.i4 0xfb8
IL_06dd: sub
IL_06de: ldc.i4.2
IL_06df: ble.un.s IL_075d
IL_06e1: br.s IL_075f
IL_06e3: ldarg.0
IL_06e4: ldc.i4 0x1b7b
IL_06e9: bgt.s IL_071f
IL_06eb: ldarg.0
IL_06ec: ldc.i4 0x1b65
IL_06f1: bgt.s IL_0705
IL_06f3: ldarg.0
IL_06f4: ldc.i4 0x1388
IL_06f9: beq.s IL_075d
IL_06fb: ldarg.0
IL_06fc: ldc.i4 0x1b65
IL_0701: beq.s IL_075d
IL_0703: br.s IL_075f
IL_0705: ldarg.0
IL_0706: ldc.i4 0x1b6e
IL_070b: beq.s IL_075d
IL_070d: ldarg.0
IL_070e: ldc.i4 0x1b79
IL_0713: beq.s IL_075d
IL_0715: ldarg.0
IL_0716: ldc.i4 0x1b7b
IL_071b: beq.s IL_075d
IL_071d: br.s IL_075f
IL_071f: ldarg.0
IL_0720: ldc.i4 0x1f41
IL_0725: bgt.s IL_0743
IL_0727: ldarg.0
IL_0728: ldc.i4 0x1ba8
IL_072d: sub
IL_072e: ldc.i4.2
IL_072f: ble.un.s IL_075d
IL_0731: ldarg.0
IL_0732: ldc.i4 0x1bb2
IL_0737: beq.s IL_075d
IL_0739: ldarg.0
IL_073a: ldc.i4 0x1f41
IL_073f: beq.s IL_075d
IL_0741: br.s IL_075f
IL_0743: ldarg.0
IL_0744: ldc.i4 0x1f49
IL_0749: beq.s IL_075d
IL_074b: ldarg.0
IL_074c: ldc.i4 0x1f4c
IL_0751: beq.s IL_075d
IL_0753: ldarg.0
IL_0754: ldc.i4 0x2710
IL_0759: sub
IL_075a: ldc.i4.2
IL_075b: bgt.un.s IL_075f
IL_075d: ldc.i4.1
IL_075e: ret
IL_075f: ldc.i4.0
IL_0760: ret
}");
}
[Fact]
public void StringSwitch()
{
var text = @"using System;
public class Test
{
public static void Main()
{
Console.WriteLine(M(""Orange""));
}
public static int M(string s)
{
switch (s)
{
case ""Black"": return 0;
case ""Brown"": return 1;
case ""Red"": return 2;
case ""Orange"": return 3;
case ""Yellow"": return 4;
case ""Green"": return 5;
case ""Blue"": return 6;
case ""Violet"": return 7;
case ""Grey"": case ""Gray"": return 8;
case ""White"": return 9;
default: throw new ArgumentException(s);
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "3");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 368 (0x170)
.maxstack 2
.locals init (uint V_0)
IL_0000: ldarg.0
IL_0001: call ""ComputeStringHash""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x6ceb2d06
IL_000d: bgt.un.s IL_0055
IL_000f: ldloc.0
IL_0010: ldc.i4 0x2b043744
IL_0015: bgt.un.s IL_002f
IL_0017: ldloc.0
IL_0018: ldc.i4 0x2b8b9cf
IL_001d: beq IL_00b2
IL_0022: ldloc.0
IL_0023: ldc.i4 0x2b043744
IL_0028: beq.s IL_009d
IL_002a: br IL_0169
IL_002f: ldloc.0
IL_0030: ldc.i4 0x32bdf8c6
IL_0035: beq IL_0127
IL_003a: ldloc.0
IL_003b: ldc.i4 0x3ac6ffba
IL_0040: beq IL_0136
IL_0045: ldloc.0
IL_0046: ldc.i4 0x6ceb2d06
IL_004b: beq IL_0145
IL_0050: br IL_0169
IL_0055: ldloc.0
IL_0056: ldc.i4 0xa953c75c
IL_005b: bgt.un.s IL_007d
IL_005d: ldloc.0
IL_005e: ldc.i4 0x727b390b
IL_0063: beq.s IL_00dc
IL_0065: ldloc.0
IL_0066: ldc.i4 0xa37f187c
IL_006b: beq.s IL_00c7
IL_006d: ldloc.0
IL_006e: ldc.i4 0xa953c75c
IL_0073: beq IL_00fa
IL_0078: br IL_0169
IL_007d: ldloc.0
IL_007e: ldc.i4 0xd9cdec69
IL_0083: beq.s IL_00eb
IL_0085: ldloc.0
IL_0086: ldc.i4 0xe9dd1fed
IL_008b: beq.s IL_0109
IL_008d: ldloc.0
IL_008e: ldc.i4 0xf03bdf12
IL_0093: beq IL_0118
IL_0098: br IL_0169
IL_009d: ldarg.0
IL_009e: ldstr ""Black""
IL_00a3: call ""bool string.op_Equality(string, string)""
IL_00a8: brtrue IL_0154
IL_00ad: br IL_0169
IL_00b2: ldarg.0
IL_00b3: ldstr ""Brown""
IL_00b8: call ""bool string.op_Equality(string, string)""
IL_00bd: brtrue IL_0156
IL_00c2: br IL_0169
IL_00c7: ldarg.0
IL_00c8: ldstr ""Red""
IL_00cd: call ""bool string.op_Equality(string, string)""
IL_00d2: brtrue IL_0158
IL_00d7: br IL_0169
IL_00dc: ldarg.0
IL_00dd: ldstr ""Orange""
IL_00e2: call ""bool string.op_Equality(string, string)""
IL_00e7: brtrue.s IL_015a
IL_00e9: br.s IL_0169
IL_00eb: ldarg.0
IL_00ec: ldstr ""Yellow""
IL_00f1: call ""bool string.op_Equality(string, string)""
IL_00f6: brtrue.s IL_015c
IL_00f8: br.s IL_0169
IL_00fa: ldarg.0
IL_00fb: ldstr ""Green""
IL_0100: call ""bool string.op_Equality(string, string)""
IL_0105: brtrue.s IL_015e
IL_0107: br.s IL_0169
IL_0109: ldarg.0
IL_010a: ldstr ""Blue""
IL_010f: call ""bool string.op_Equality(string, string)""
IL_0114: brtrue.s IL_0160
IL_0116: br.s IL_0169
IL_0118: ldarg.0
IL_0119: ldstr ""Violet""
IL_011e: call ""bool string.op_Equality(string, string)""
IL_0123: brtrue.s IL_0162
IL_0125: br.s IL_0169
IL_0127: ldarg.0
IL_0128: ldstr ""Grey""
IL_012d: call ""bool string.op_Equality(string, string)""
IL_0132: brtrue.s IL_0164
IL_0134: br.s IL_0169
IL_0136: ldarg.0
IL_0137: ldstr ""Gray""
IL_013c: call ""bool string.op_Equality(string, string)""
IL_0141: brtrue.s IL_0164
IL_0143: br.s IL_0169
IL_0145: ldarg.0
IL_0146: ldstr ""White""
IL_014b: call ""bool string.op_Equality(string, string)""
IL_0150: brtrue.s IL_0166
IL_0152: br.s IL_0169
IL_0154: ldc.i4.0
IL_0155: ret
IL_0156: ldc.i4.1
IL_0157: ret
IL_0158: ldc.i4.2
IL_0159: ret
IL_015a: ldc.i4.3
IL_015b: ret
IL_015c: ldc.i4.4
IL_015d: ret
IL_015e: ldc.i4.5
IL_015f: ret
IL_0160: ldc.i4.6
IL_0161: ret
IL_0162: ldc.i4.7
IL_0163: ret
IL_0164: ldc.i4.8
IL_0165: ret
IL_0166: ldc.i4.s 9
IL_0168: ret
IL_0169: ldarg.0
IL_016a: newobj ""System.ArgumentException..ctor(string)""
IL_016f: throw
}");
}
#endregion
# region "Data flow analysis tests"
[Fact]
public void DefiniteAssignmentOnAllControlPaths()
{
var text = @"using System;
class SwitchTest
{
public static int Main()
{
int n = 3;
int goo; // unassigned goo
switch (n)
{
case 1:
case 2:
goo = n;
break;
case 3:
default:
goo = 0;
break;
}
Console.Write(goo); // goo must be definitely assigned here
return goo;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("SwitchTest.Main", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (int V_0, //n
int V_1) //goo
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: ldc.i4.1
IL_0006: ble.un.s IL_000e
IL_0008: ldloc.0
IL_0009: ldc.i4.3
IL_000a: beq.s IL_0012
IL_000c: br.s IL_0012
IL_000e: ldloc.0
IL_000f: stloc.1
IL_0010: br.s IL_0014
IL_0012: ldc.i4.0
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: call ""void System.Console.Write(int)""
IL_001a: ldloc.1
IL_001b: ret
}"
);
}
[Fact]
public void ComplexControlFlow_DefiniteAssignmentOnAllControlPaths()
{
var text = @"using System;
class SwitchTest
{
public static int Main()
{
int n = 3;
int cost = 0;
int goo; // unassigned goo
switch (n)
{
case 1:
cost = 1;
goo = n;
break;
case 2:
cost = 2;
goto case 1;
case 3:
cost = 3;
if(cost > n)
{
goo = n - 1;
}
else
{
goto case 2;
}
break;
default:
cost = 4;
goo = n - 1;
break;
}
if (goo != n) // goo must be reported as definitely assigned
{
Console.Write(goo);
}
else
{
--cost;
}
Console.Write(cost); // should output 0
return cost;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("SwitchTest.Main",
@"{
// Code size 78 (0x4e)
.maxstack 2
.locals init (int V_0, //n
int V_1, //cost
int V_2) //goo
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: ldc.i4.1
IL_0006: sub
IL_0007: switch (
IL_001a,
IL_0020,
IL_0024)
IL_0018: br.s IL_0030
IL_001a: ldc.i4.1
IL_001b: stloc.1
IL_001c: ldloc.0
IL_001d: stloc.2
IL_001e: br.s IL_0036
IL_0020: ldc.i4.2
IL_0021: stloc.1
IL_0022: br.s IL_001a
IL_0024: ldc.i4.3
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldloc.0
IL_0028: ble.s IL_0020
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: sub
IL_002d: stloc.2
IL_002e: br.s IL_0036
IL_0030: ldc.i4.4
IL_0031: stloc.1
IL_0032: ldloc.0
IL_0033: ldc.i4.1
IL_0034: sub
IL_0035: stloc.2
IL_0036: ldloc.2
IL_0037: ldloc.0
IL_0038: beq.s IL_0042
IL_003a: ldloc.2
IL_003b: call ""void System.Console.Write(int)""
IL_0040: br.s IL_0046
IL_0042: ldloc.1
IL_0043: ldc.i4.1
IL_0044: sub
IL_0045: stloc.1
IL_0046: ldloc.1
IL_0047: call ""void System.Console.Write(int)""
IL_004c: ldloc.1
IL_004d: ret
}"
);
}
[Fact]
public void ComplexControlFlow_NoAssignmentOnlyOnUnreachableControlPaths()
{
var text = @"using System;
class SwitchTest
{
public static int Main()
{
int goo; // unassigned goo
switch (3)
{
case 1:
mylabel:
try
{
throw new System.ApplicationException();
}
catch(Exception)
{
goo = 0;
}
break;
case 2:
goto mylabel;
case 3:
if (true)
{
goto case 2;
}
break;
case 4:
break;
}
Console.Write(goo); // goo should be definitely assigned here
return goo;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (27,17): warning CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break"),
// (29,17): warning CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break"));
compVerifier.VerifyIL("SwitchTest.Main", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int V_0) //goo
IL_0000: nop
.try
{
IL_0001: newobj ""System.ApplicationException..ctor()""
IL_0006: throw
}
catch System.Exception
{
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: stloc.0
IL_000a: leave.s IL_000c
}
IL_000c: ldloc.0
IL_000d: call ""void System.Console.Write(int)""
IL_0012: ldloc.0
IL_0013: ret
}"
);
}
#endregion
#region "Control flow analysis and warning tests"
[Fact]
public void CS0469_NoImplicitConversionWarning()
{
var text = @"using System;
class A
{
static void Goo(DayOfWeek x)
{
switch (x)
{
case DayOfWeek.Monday:
goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek'
}
}
static void Main() {}
}
";
var compVerifier = CompileAndVerify(text);
compVerifier.VerifyDiagnostics(
// (10,17): warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek'
// goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek'
Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 1;").WithArguments("System.DayOfWeek"));
compVerifier.VerifyIL("A.Goo", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: bne.un.s IL_0006
IL_0004: br.s IL_0004
IL_0006: ret
}"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_01()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 2;
switch (true)
{
case true:
ret = 0;
break;
case false: // unreachable case label
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (14,8): warning CS0162: Unreachable code detected
// ret = 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "ret"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //ret
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call ""void System.Console.Write(int)""
IL_000a: ldloc.0
IL_000b: ret
}
"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_02()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
switch (true)
{
default: // unreachable default label
ret = 1;
break;
case true:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (11,17): warning CS0162: Unreachable code detected
// ret = 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 17)
);
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //ret
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call ""void System.Console.Write(int)""
IL_000a: ldloc.0
IL_000b: ret
}"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_03()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
switch (1)
{
case 1:
return 0;
}
return 1; // unreachable code
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (19,5): warning CS0162: Unreachable code detected
// return 1; // unreachable code
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(19, 5));
compVerifier.VerifyIL("Test.M", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_04()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
switch (1) // no matching case/default label
{
case 2: // unreachable code
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (11,9): warning CS0162: Unreachable code detected
// ret = 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 9)
);
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0) //ret
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call ""void System.Console.Write(int)""
IL_0008: ldloc.0
IL_0009: ret
}"
);
}
[Fact]
public void CS1522_EmptySwitch()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
switch (true) {
}
Console.Write(ret);
return(0);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (7,23): warning CS1522: Empty switch block
// switch (true) {
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 23)
);
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ldc.i4.0
IL_0007: ret
}"
);
}
[WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")]
[Fact]
public void DifferentStrategiesForDifferentSwitches()
{
var text = @"
using System;
public class Test
{
public static void Main(string [] args)
{
switch(args[0])
{
case ""A"": Console.Write(1); break;
}
switch(args[1])
{
case ""B"": Console.Write(2); break;
case ""C"": Console.Write(3); break;
case ""D"": Console.Write(4); break;
case ""E"": Console.Write(5); break;
case ""F"": Console.Write(6); break;
case ""G"": Console.Write(7); break;
case ""H"": Console.Write(8); break;
case ""I"": Console.Write(9); break;
case ""J"": Console.Write(10); break;
}
}
}";
var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
CompileAndVerify(comp).VerifyIL("Test.Main", @"
{
// Code size 326 (0x146)
.maxstack 2
.locals init (string V_0,
uint V_1)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: ldstr ""A""
IL_0008: call ""bool string.op_Equality(string, string)""
IL_000d: brfalse.s IL_0015
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ldarg.0
IL_0016: ldc.i4.1
IL_0017: ldelem.ref
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: call ""ComputeStringHash""
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldc.i4 0xc30bf539
IL_0026: bgt.un.s IL_0055
IL_0028: ldloc.1
IL_0029: ldc.i4 0xc10bf213
IL_002e: bgt.un.s IL_0041
IL_0030: ldloc.1
IL_0031: ldc.i4 0xc00bf080
IL_0036: beq.s IL_00b1
IL_0038: ldloc.1
IL_0039: ldc.i4 0xc10bf213
IL_003e: beq.s IL_00a3
IL_0040: ret
IL_0041: ldloc.1
IL_0042: ldc.i4 0xc20bf3a6
IL_0047: beq IL_00cd
IL_004c: ldloc.1
IL_004d: ldc.i4 0xc30bf539
IL_0052: beq.s IL_00bf
IL_0054: ret
IL_0055: ldloc.1
IL_0056: ldc.i4 0xc70bfb85
IL_005b: bgt.un.s IL_006e
IL_005d: ldloc.1
IL_005e: ldc.i4 0xc60bf9f2
IL_0063: beq.s IL_0095
IL_0065: ldloc.1
IL_0066: ldc.i4 0xc70bfb85
IL_006b: beq.s IL_0087
IL_006d: ret
IL_006e: ldloc.1
IL_006f: ldc.i4 0xcc0c0364
IL_0074: beq.s IL_00e9
IL_0076: ldloc.1
IL_0077: ldc.i4 0xcd0c04f7
IL_007c: beq.s IL_00db
IL_007e: ldloc.1
IL_007f: ldc.i4 0xcf0c081d
IL_0084: beq.s IL_00f7
IL_0086: ret
IL_0087: ldloc.0
IL_0088: ldstr ""B""
IL_008d: call ""bool string.op_Equality(string, string)""
IL_0092: brtrue.s IL_0105
IL_0094: ret
IL_0095: ldloc.0
IL_0096: ldstr ""C""
IL_009b: call ""bool string.op_Equality(string, string)""
IL_00a0: brtrue.s IL_010c
IL_00a2: ret
IL_00a3: ldloc.0
IL_00a4: ldstr ""D""
IL_00a9: call ""bool string.op_Equality(string, string)""
IL_00ae: brtrue.s IL_0113
IL_00b0: ret
IL_00b1: ldloc.0
IL_00b2: ldstr ""E""
IL_00b7: call ""bool string.op_Equality(string, string)""
IL_00bc: brtrue.s IL_011a
IL_00be: ret
IL_00bf: ldloc.0
IL_00c0: ldstr ""F""
IL_00c5: call ""bool string.op_Equality(string, string)""
IL_00ca: brtrue.s IL_0121
IL_00cc: ret
IL_00cd: ldloc.0
IL_00ce: ldstr ""G""
IL_00d3: call ""bool string.op_Equality(string, string)""
IL_00d8: brtrue.s IL_0128
IL_00da: ret
IL_00db: ldloc.0
IL_00dc: ldstr ""H""
IL_00e1: call ""bool string.op_Equality(string, string)""
IL_00e6: brtrue.s IL_012f
IL_00e8: ret
IL_00e9: ldloc.0
IL_00ea: ldstr ""I""
IL_00ef: call ""bool string.op_Equality(string, string)""
IL_00f4: brtrue.s IL_0136
IL_00f6: ret
IL_00f7: ldloc.0
IL_00f8: ldstr ""J""
IL_00fd: call ""bool string.op_Equality(string, string)""
IL_0102: brtrue.s IL_013e
IL_0104: ret
IL_0105: ldc.i4.2
IL_0106: call ""void System.Console.Write(int)""
IL_010b: ret
IL_010c: ldc.i4.3
IL_010d: call ""void System.Console.Write(int)""
IL_0112: ret
IL_0113: ldc.i4.4
IL_0114: call ""void System.Console.Write(int)""
IL_0119: ret
IL_011a: ldc.i4.5
IL_011b: call ""void System.Console.Write(int)""
IL_0120: ret
IL_0121: ldc.i4.6
IL_0122: call ""void System.Console.Write(int)""
IL_0127: ret
IL_0128: ldc.i4.7
IL_0129: call ""void System.Console.Write(int)""
IL_012e: ret
IL_012f: ldc.i4.8
IL_0130: call ""void System.Console.Write(int)""
IL_0135: ret
IL_0136: ldc.i4.s 9
IL_0138: call ""void System.Console.Write(int)""
IL_013d: ret
IL_013e: ldc.i4.s 10
IL_0140: call ""void System.Console.Write(int)""
IL_0145: ret
}");
}
[WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")]
[WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")]
[Fact]
public void LargeStringSwitchWithoutStringChars()
{
var text = @"
using System;
public class Test
{
public static void Main(string [] args)
{
switch(args[0])
{
case ""A"": Console.Write(1); break;
case ""B"": Console.Write(2); break;
case ""C"": Console.Write(3); break;
case ""D"": Console.Write(4); break;
case ""E"": Console.Write(5); break;
case ""F"": Console.Write(6); break;
case ""G"": Console.Write(7); break;
case ""H"": Console.Write(8); break;
case ""I"": Console.Write(9); break;
}
}
}";
var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
// With special members available, we use a hashtable approach.
CompileAndVerify(comp).VerifyIL("Test.Main", @"
{
// Code size 307 (0x133)
.maxstack 2
.locals init (string V_0,
uint V_1)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call ""ComputeStringHash""
IL_000a: stloc.1
IL_000b: ldloc.1
IL_000c: ldc.i4 0xc30bf539
IL_0011: bgt.un.s IL_0043
IL_0013: ldloc.1
IL_0014: ldc.i4 0xc10bf213
IL_0019: bgt.un.s IL_002f
IL_001b: ldloc.1
IL_001c: ldc.i4 0xc00bf080
IL_0021: beq IL_00ad
IL_0026: ldloc.1
IL_0027: ldc.i4 0xc10bf213
IL_002c: beq.s IL_009f
IL_002e: ret
IL_002f: ldloc.1
IL_0030: ldc.i4 0xc20bf3a6
IL_0035: beq IL_00c9
IL_003a: ldloc.1
IL_003b: ldc.i4 0xc30bf539
IL_0040: beq.s IL_00bb
IL_0042: ret
IL_0043: ldloc.1
IL_0044: ldc.i4 0xc60bf9f2
IL_0049: bgt.un.s IL_005c
IL_004b: ldloc.1
IL_004c: ldc.i4 0xc40bf6cc
IL_0051: beq.s IL_0075
IL_0053: ldloc.1
IL_0054: ldc.i4 0xc60bf9f2
IL_0059: beq.s IL_0091
IL_005b: ret
IL_005c: ldloc.1
IL_005d: ldc.i4 0xc70bfb85
IL_0062: beq.s IL_0083
IL_0064: ldloc.1
IL_0065: ldc.i4 0xcc0c0364
IL_006a: beq.s IL_00e5
IL_006c: ldloc.1
IL_006d: ldc.i4 0xcd0c04f7
IL_0072: beq.s IL_00d7
IL_0074: ret
IL_0075: ldloc.0
IL_0076: ldstr ""A""
IL_007b: call ""bool string.op_Equality(string, string)""
IL_0080: brtrue.s IL_00f3
IL_0082: ret
IL_0083: ldloc.0
IL_0084: ldstr ""B""
IL_0089: call ""bool string.op_Equality(string, string)""
IL_008e: brtrue.s IL_00fa
IL_0090: ret
IL_0091: ldloc.0
IL_0092: ldstr ""C""
IL_0097: call ""bool string.op_Equality(string, string)""
IL_009c: brtrue.s IL_0101
IL_009e: ret
IL_009f: ldloc.0
IL_00a0: ldstr ""D""
IL_00a5: call ""bool string.op_Equality(string, string)""
IL_00aa: brtrue.s IL_0108
IL_00ac: ret
IL_00ad: ldloc.0
IL_00ae: ldstr ""E""
IL_00b3: call ""bool string.op_Equality(string, string)""
IL_00b8: brtrue.s IL_010f
IL_00ba: ret
IL_00bb: ldloc.0
IL_00bc: ldstr ""F""
IL_00c1: call ""bool string.op_Equality(string, string)""
IL_00c6: brtrue.s IL_0116
IL_00c8: ret
IL_00c9: ldloc.0
IL_00ca: ldstr ""G""
IL_00cf: call ""bool string.op_Equality(string, string)""
IL_00d4: brtrue.s IL_011d
IL_00d6: ret
IL_00d7: ldloc.0
IL_00d8: ldstr ""H""
IL_00dd: call ""bool string.op_Equality(string, string)""
IL_00e2: brtrue.s IL_0124
IL_00e4: ret
IL_00e5: ldloc.0
IL_00e6: ldstr ""I""
IL_00eb: call ""bool string.op_Equality(string, string)""
IL_00f0: brtrue.s IL_012b
IL_00f2: ret
IL_00f3: ldc.i4.1
IL_00f4: call ""void System.Console.Write(int)""
IL_00f9: ret
IL_00fa: ldc.i4.2
IL_00fb: call ""void System.Console.Write(int)""
IL_0100: ret
IL_0101: ldc.i4.3
IL_0102: call ""void System.Console.Write(int)""
IL_0107: ret
IL_0108: ldc.i4.4
IL_0109: call ""void System.Console.Write(int)""
IL_010e: ret
IL_010f: ldc.i4.5
IL_0110: call ""void System.Console.Write(int)""
IL_0115: ret
IL_0116: ldc.i4.6
IL_0117: call ""void System.Console.Write(int)""
IL_011c: ret
IL_011d: ldc.i4.7
IL_011e: call ""void System.Console.Write(int)""
IL_0123: ret
IL_0124: ldc.i4.8
IL_0125: call ""void System.Console.Write(int)""
IL_012a: ret
IL_012b: ldc.i4.s 9
IL_012d: call ""void System.Console.Write(int)""
IL_0132: ret
}");
comp = CreateCompilation(text);
comp.MakeMemberMissing(SpecialMember.System_String__Chars);
// Can't use the hash version when String.Chars is unavailable.
CompileAndVerify(comp).VerifyIL("Test.Main", @"
{
// Code size 186 (0xba)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: ldstr ""A""
IL_000a: call ""bool string.op_Equality(string, string)""
IL_000f: brtrue.s IL_007a
IL_0011: ldloc.0
IL_0012: ldstr ""B""
IL_0017: call ""bool string.op_Equality(string, string)""
IL_001c: brtrue.s IL_0081
IL_001e: ldloc.0
IL_001f: ldstr ""C""
IL_0024: call ""bool string.op_Equality(string, string)""
IL_0029: brtrue.s IL_0088
IL_002b: ldloc.0
IL_002c: ldstr ""D""
IL_0031: call ""bool string.op_Equality(string, string)""
IL_0036: brtrue.s IL_008f
IL_0038: ldloc.0
IL_0039: ldstr ""E""
IL_003e: call ""bool string.op_Equality(string, string)""
IL_0043: brtrue.s IL_0096
IL_0045: ldloc.0
IL_0046: ldstr ""F""
IL_004b: call ""bool string.op_Equality(string, string)""
IL_0050: brtrue.s IL_009d
IL_0052: ldloc.0
IL_0053: ldstr ""G""
IL_0058: call ""bool string.op_Equality(string, string)""
IL_005d: brtrue.s IL_00a4
IL_005f: ldloc.0
IL_0060: ldstr ""H""
IL_0065: call ""bool string.op_Equality(string, string)""
IL_006a: brtrue.s IL_00ab
IL_006c: ldloc.0
IL_006d: ldstr ""I""
IL_0072: call ""bool string.op_Equality(string, string)""
IL_0077: brtrue.s IL_00b2
IL_0079: ret
IL_007a: ldc.i4.1
IL_007b: call ""void System.Console.Write(int)""
IL_0080: ret
IL_0081: ldc.i4.2
IL_0082: call ""void System.Console.Write(int)""
IL_0087: ret
IL_0088: ldc.i4.3
IL_0089: call ""void System.Console.Write(int)""
IL_008e: ret
IL_008f: ldc.i4.4
IL_0090: call ""void System.Console.Write(int)""
IL_0095: ret
IL_0096: ldc.i4.5
IL_0097: call ""void System.Console.Write(int)""
IL_009c: ret
IL_009d: ldc.i4.6
IL_009e: call ""void System.Console.Write(int)""
IL_00a3: ret
IL_00a4: ldc.i4.7
IL_00a5: call ""void System.Console.Write(int)""
IL_00aa: ret
IL_00ab: ldc.i4.8
IL_00ac: call ""void System.Console.Write(int)""
IL_00b1: ret
IL_00b2: ldc.i4.s 9
IL_00b4: call ""void System.Console.Write(int)""
IL_00b9: ret
}");
}
[WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")]
[Fact]
public void Regress947580()
{
var text = @"
using System;
class Program {
static string boo(int i) {
switch (i) {
case 42:
var x = ""goo"";
if (x != ""bar"")
break;
return x;
}
return null;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //x
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: bne.un.s IL_001a
IL_0005: ldstr ""goo""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""bar""
IL_0011: call ""bool string.op_Inequality(string, string)""
IL_0016: brtrue.s IL_001a
IL_0018: ldloc.0
IL_0019: ret
IL_001a: ldnull
IL_001b: ret
}"
);
}
[WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")]
[Fact]
public void Regress947580a()
{
var text = @"
using System;
class Program {
static string boo(int i) {
switch (i) {
case 42:
var x = ""goo"";
if (x != ""bar"")
break;
break;
}
return null;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 23 (0x17)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: bne.un.s IL_0015
IL_0005: ldstr ""goo""
IL_000a: ldstr ""bar""
IL_000f: call ""bool string.op_Inequality(string, string)""
IL_0014: pop
IL_0015: ldnull
IL_0016: ret
}"
);
}
[WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")]
[Fact]
public void Regress1035228()
{
var text = @"
using System;
class Program {
static bool boo(int i) {
var ii = i;
switch (++ii) {
case 42:
var x = ""goo"";
if (x != ""bar"")
{
return false;
}
break;
}
return true;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ldc.i4.s 42
IL_0005: bne.un.s IL_001a
IL_0007: ldstr ""goo""
IL_000c: ldstr ""bar""
IL_0011: call ""bool string.op_Inequality(string, string)""
IL_0016: brfalse.s IL_001a
IL_0018: ldc.i4.0
IL_0019: ret
IL_001a: ldc.i4.1
IL_001b: ret
}"
);
}
[WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")]
[Fact]
public void Regress1035228a()
{
var text = @"
using System;
class Program {
static bool boo(int i) {
var ii = i;
switch (ii++) {
case 42:
var x = ""goo"";
if (x != ""bar"")
{
return false;
}
break;
}
return true;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: bne.un.s IL_0018
IL_0005: ldstr ""goo""
IL_000a: ldstr ""bar""
IL_000f: call ""bool string.op_Inequality(string, string)""
IL_0014: brfalse.s IL_0018
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldc.i4.1
IL_0019: ret
}"
);
}
[WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")]
[Fact]
public void Regress4701()
{
var text = @"
using System;
namespace ConsoleApplication1
{
class Program
{
private void SwtchTest()
{
int? i;
i = 1;
switch (i)
{
case null:
Console.WriteLine(""In Null case"");
i = 1;
break;
default:
Console.WriteLine(""In DEFAULT case"");
i = i + 2;
break;
}
}
static void Main(string[] args)
{
var p = new Program();
p.SwtchTest();
}
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case");
compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest",
@"
{
// Code size 84 (0x54)
.maxstack 2
.locals init (int? V_0, //i
int? V_1,
int? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""int?..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""bool int?.HasValue.get""
IL_000f: brtrue.s IL_0024
IL_0011: ldstr ""In Null case""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: ldloca.s V_0
IL_001d: ldc.i4.1
IL_001e: call ""int?..ctor(int)""
IL_0023: ret
IL_0024: ldstr ""In DEFAULT case""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ldloc.0
IL_002f: stloc.1
IL_0030: ldloca.s V_1
IL_0032: call ""bool int?.HasValue.get""
IL_0037: brtrue.s IL_0044
IL_0039: ldloca.s V_2
IL_003b: initobj ""int?""
IL_0041: ldloc.2
IL_0042: br.s IL_0052
IL_0044: ldloca.s V_1
IL_0046: call ""int int?.GetValueOrDefault()""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: newobj ""int?..ctor(int)""
IL_0052: stloc.0
IL_0053: ret
}"
);
}
[WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")]
[Fact]
public void Regress4701a()
{
var text = @"
using System;
namespace ConsoleApplication1
{
class Program
{
private void SwtchTest()
{
string i = null;
i = ""1"";
switch (i)
{
case null:
Console.WriteLine(""In Null case"");
break;
default:
Console.WriteLine(""In DEFAULT case"");
break;
}
}
static void Main(string[] args)
{
var p = new Program();
p.SwtchTest();
}
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case");
compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest",
@"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldstr ""1""
IL_0005: brtrue.s IL_0012
IL_0007: ldstr ""In Null case""
IL_000c: call ""void System.Console.WriteLine(string)""
IL_0011: ret
IL_0012: ldstr ""In DEFAULT case""
IL_0017: call ""void System.Console.WriteLine(string)""
IL_001c: ret
}"
);
}
#endregion
#region regression tests
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternSwitch_01()
{
var source = @"using System;
public class Program
{
public static void Main()
{
switch (StringSplitOptions.RemoveEmptyEntries)
{
case object o:
Console.WriteLine(o);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: box ""System.StringSplitOptions""
IL_0006: call ""void System.Console.WriteLine(object)""
IL_000b: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 26 (0x1a)
.maxstack 1
.locals init (object V_0, //o
System.StringSplitOptions V_1,
System.StringSplitOptions V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldc.i4.1
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""System.StringSplitOptions""
IL_000b: stloc.0
IL_000c: br.s IL_000e
IL_000e: br.s IL_0010
IL_0010: ldloc.0
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: nop
IL_0017: br.s IL_0019
IL_0019: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void ExplicitNullablePatternSwitch_02()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(null);
M(1);
}
public static void M(int? x)
{
switch (x)
{
case int i: // explicit nullable conversion
Console.Write(i);
break;
case null:
Console.Write(""null"");
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "null1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 33 (0x21)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldstr ""null""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "null1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 49 (0x31)
.maxstack 1
.locals init (int V_0, //i
int? V_1,
int? V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloca.s V_1
IL_0007: call ""bool int?.HasValue.get""
IL_000c: brfalse.s IL_0023
IL_000e: ldloca.s V_1
IL_0010: call ""int int?.GetValueOrDefault()""
IL_0015: stloc.0
IL_0016: br.s IL_0018
IL_0018: br.s IL_001a
IL_001a: ldloc.0
IL_001b: call ""void System.Console.Write(int)""
IL_0020: nop
IL_0021: br.s IL_0030
IL_0023: ldstr ""null""
IL_0028: call ""void System.Console.Write(string)""
IL_002d: nop
IL_002e: br.s IL_0030
IL_0030: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternSwitch_04()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(1);
}
public static void M(int x)
{
switch (x)
{
case System.IComparable i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""int""
IL_0006: call ""void System.Console.Write(object)""
IL_000b: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
.locals init (System.IComparable V_0, //i
int V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""int""
IL_000b: stloc.0
IL_000c: br.s IL_000e
IL_000e: br.s IL_0010
IL_0010: ldloc.0
IL_0011: call ""void System.Console.Write(object)""
IL_0016: nop
IL_0017: br.s IL_0019
IL_0019: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternSwitch_05()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(1);
M(null);
}
public static void M(int? x)
{
switch (x)
{
case System.IComparable i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init (System.IComparable V_0) //i
IL_0000: ldarg.0
IL_0001: box ""int?""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: call ""void System.Console.Write(object)""
IL_0010: ret
}
"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (System.IComparable V_0, //i
int? V_1,
int? V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""int?""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0011
IL_000f: br.s IL_001c
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: call ""void System.Console.Write(object)""
IL_0019: nop
IL_001a: br.s IL_001c
IL_001c: ret
}
"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnboxInPatternSwitch_06()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(1);
M(null);
M(nameof(Main));
}
public static void M(object x)
{
switch (x)
{
case int i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 20 (0x14)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brfalse.s IL_0013
IL_0008: ldarg.0
IL_0009: unbox.any ""int""
IL_000e: call ""void System.Console.Write(int)""
IL_0013: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 34 (0x22)
.maxstack 1
.locals init (int V_0, //i
object V_1,
object V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0021
IL_000d: ldloc.1
IL_000e: unbox.any ""int""
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: br.s IL_0018
IL_0018: ldloc.0
IL_0019: call ""void System.Console.Write(int)""
IL_001e: nop
IL_001f: br.s IL_0021
IL_0021: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnboxInPatternSwitch_07()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M<int>(1);
M<int>(null);
M<int>(10.5);
}
public static void M<T>(object x)
{
// when T is not known to be a reference type, there is an unboxing conversion from
// the effective base class C of T to T and from any base class of C to T.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""T""
IL_0006: brfalse.s IL_0018
IL_0008: ldarg.0
IL_0009: unbox.any ""T""
IL_000e: box ""T""
IL_0013: call ""void System.Console.Write(object)""
IL_0018: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (T V_0, //i
object V_1,
object V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0026
IL_000d: ldloc.1
IL_000e: unbox.any ""T""
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: br.s IL_0018
IL_0018: ldloc.0
IL_0019: box ""T""
IL_001e: call ""void System.Console.Write(object)""
IL_0023: nop
IL_0024: br.s IL_0026
IL_0026: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnboxInPatternSwitch_08()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M<int>(1);
M<int>(null);
M<int>(10.5);
}
public static void M<T>(IComparable x)
{
// when T is not known to be a reference type, there is an unboxing conversion from
// any interface type to T.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""T""
IL_0006: brfalse.s IL_0018
IL_0008: ldarg.0
IL_0009: unbox.any ""T""
IL_000e: box ""T""
IL_0013: call ""void System.Console.Write(object)""
IL_0018: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (T V_0, //i
System.IComparable V_1,
System.IComparable V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0026
IL_000d: ldloc.1
IL_000e: unbox.any ""T""
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: br.s IL_0018
IL_0018: ldloc.0
IL_0019: box ""T""
IL_001e: call ""void System.Console.Write(object)""
IL_0023: nop
IL_0024: br.s IL_0026
IL_0026: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnoxInPatternSwitch_09()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M<int, object>(1);
M<int, object>(null);
M<int, object>(10.5);
}
public static void M<T, U>(U x) where T : U
{
// when T is not known to be a reference type, there is an unboxing conversion from
// a type parameter U to T, provided T depends on U.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T, U>",
@"{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""U""
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0022
IL_000d: ldarg.0
IL_000e: box ""U""
IL_0013: unbox.any ""T""
IL_0018: box ""T""
IL_001d: call ""void System.Console.Write(object)""
IL_0022: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T, U>",
@"{
// Code size 49 (0x31)
.maxstack 1
.locals init (T V_0, //i
U V_1,
U V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""U""
IL_000b: isinst ""T""
IL_0010: brfalse.s IL_0030
IL_0012: ldloc.1
IL_0013: box ""U""
IL_0018: unbox.any ""T""
IL_001d: stloc.0
IL_001e: br.s IL_0020
IL_0020: br.s IL_0022
IL_0022: ldloc.0
IL_0023: box ""T""
IL_0028: call ""void System.Console.Write(object)""
IL_002d: nop
IL_002e: br.s IL_0030
IL_0030: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternIf_02()
{
var source = @"using System;
public class Program
{
public static void Main()
{
if (StringSplitOptions.RemoveEmptyEntries is object o)
{
Console.WriteLine(o);
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 14 (0xe)
.maxstack 1
.locals init (object V_0) //o
IL_0000: ldc.i4.1
IL_0001: box ""System.StringSplitOptions""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void System.Console.WriteLine(object)""
IL_000d: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (object V_0, //o
bool V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""System.StringSplitOptions""
IL_0007: stloc.0
IL_0008: ldc.i4.1
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: brfalse.s IL_0016
IL_000d: nop
IL_000e: ldloc.0
IL_000f: call ""void System.Console.WriteLine(object)""
IL_0014: nop
IL_0015: nop
IL_0016: ret
}"
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_01()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<int>(2));
Console.Write(M2<int>(3));
Console.Write(M1<int>(1.1));
Console.Write(M2<int>(1.1));
}
public static T M1<T>(ValueType o)
{
return o is T t ? t : default(T);
}
public static T M2<T>(ValueType o)
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t ? t : default(T);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(19, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 34 (0x22)
.maxstack 1
.locals init (T V_0, //t
T V_1)
IL_0000: ldarg.0
IL_0001: isinst ""T""
IL_0006: brfalse.s IL_0016
IL_0008: ldarg.0
IL_0009: isinst ""T""
IL_000e: unbox.any ""T""
IL_0013: stloc.0
IL_0014: br.s IL_0020
IL_0016: ldloca.s V_1
IL_0018: initobj ""T""
IL_001e: ldloc.1
IL_001f: ret
IL_0020: ldloc.0
IL_0021: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (T V_0, //t
T V_1,
T V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""T""
IL_0007: brfalse.s IL_0017
IL_0009: ldarg.0
IL_000a: isinst ""T""
IL_000f: unbox.any ""T""
IL_0014: stloc.0
IL_0015: br.s IL_0022
IL_0017: ldloca.s V_1
IL_0019: initobj ""T""
IL_001f: ldloc.1
IL_0020: br.s IL_0023
IL_0022: ldloc.0
IL_0023: stloc.2
IL_0024: br.s IL_0026
IL_0026: ldloc.2
IL_0027: ret
}"
);
compVerifier.VerifyIL("Program.M2<T>",
@"{
// Code size 48 (0x30)
.maxstack 1
.locals init (T V_0, //t
System.ValueType V_1,
System.ValueType V_2,
T V_3,
T V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0021
IL_000d: ldloc.1
IL_000e: isinst ""T""
IL_0013: unbox.any ""T""
IL_0018: stloc.0
IL_0019: br.s IL_001b
IL_001b: br.s IL_001d
IL_001d: ldloc.0
IL_001e: stloc.3
IL_001f: br.s IL_002e
IL_0021: ldloca.s V_4
IL_0023: initobj ""T""
IL_0029: ldloc.s V_4
IL_002b: stloc.3
IL_002c: br.s IL_002e
IL_002e: ldloc.3
IL_002f: ret
}"
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_02()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1(2));
Console.Write(M2(3));
Console.Write(M1(1.1));
Console.Write(M2(1.1));
}
public static int M1<T>(T o)
{
return o is int t ? t : default(int);
}
public static int M2<T>(T o)
{
switch (o)
{
case int t:
return t;
default:
return default(int);
}
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater.
// return o is int t ? t : default(int);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater.
// case int t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(19, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 36 (0x24)
.maxstack 1
.locals init (int V_0) //t
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0020
IL_000d: ldarg.0
IL_000e: box ""T""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: stloc.0
IL_001e: br.s IL_0022
IL_0020: ldc.i4.0
IL_0021: ret
IL_0022: ldloc.0
IL_0023: ret
}
"
);
compVerifier.VerifyIL("Program.M2<T>",
@"{
// Code size 32 (0x20)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_001e
IL_000d: ldarg.0
IL_000e: box ""T""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: ret
IL_001e: ldc.i4.0
IL_001f: ret
}
"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 42 (0x2a)
.maxstack 1
.locals init (int V_0, //t
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: isinst ""int""
IL_000c: brfalse.s IL_0021
IL_000e: ldarg.0
IL_000f: box ""T""
IL_0014: isinst ""int""
IL_0019: unbox.any ""int""
IL_001e: stloc.0
IL_001f: br.s IL_0024
IL_0021: ldc.i4.0
IL_0022: br.s IL_0025
IL_0024: ldloc.0
IL_0025: stloc.1
IL_0026: br.s IL_0028
IL_0028: ldloc.1
IL_0029: ret
}
"
);
compVerifier.VerifyIL("Program.M2<T>",
@"{
// Code size 49 (0x31)
.maxstack 1
.locals init (int V_0, //t
T V_1,
T V_2,
int V_3)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""T""
IL_000b: isinst ""int""
IL_0010: brfalse.s IL_002b
IL_0012: ldloc.1
IL_0013: box ""T""
IL_0018: isinst ""int""
IL_001d: unbox.any ""int""
IL_0022: stloc.0
IL_0023: br.s IL_0025
IL_0025: br.s IL_0027
IL_0027: ldloc.0
IL_0028: stloc.3
IL_0029: br.s IL_002f
IL_002b: ldc.i4.0
IL_002c: stloc.3
IL_002d: br.s IL_002f
IL_002f: ldloc.3
IL_0030: ret
}
"
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_03()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<int>(2));
Console.Write(M2<int>(3));
Console.Write(M1<int>(1.1));
Console.Write(M2<int>(1.1));
}
public static T M1<T>(ValueType o) where T : struct
{
return o is T t ? t : default(T);
}
public static T M2<T>(ValueType o) where T : struct
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "2300");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_04()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var x = new X();
Console.Write(M1<B>(new A()) ?? x);
Console.Write(M2<B>(new A()) ?? x);
Console.Write(M1<B>(new B()) ?? x);
Console.Write(M2<B>(new B()) ?? x);
}
public static T M1<T>(A o) where T : class
{
return o is T t ? t : default(T);
}
public static T M2<T>(A o) where T : class
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
class A
{
}
class B : A
{
}
class X : B { }
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t ? t : default(T);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21),
// (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "XXBB");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_05()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var x = new X();
Console.Write(M1<B>(new A()) ?? x);
Console.Write(M2<B>(new A()) ?? x);
Console.Write(M1<B>(new B()) ?? x);
Console.Write(M2<B>(new B()) ?? x);
}
public static T M1<T>(A o) where T : I1
{
return o is T t ? t : default(T);
}
public static T M2<T>(A o) where T : I1
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
interface I1
{
}
class A : I1
{
}
class B : A
{
}
class X : B { }
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t ? t : default(T);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21),
// (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "XXBB");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_06()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<B>(new A()));
Console.Write(M2<B>(new A()));
Console.Write(M1<A>(new A()));
Console.Write(M2<A>(new A()));
}
public static bool M1<T>(A o) where T : I1
{
return o is T t;
}
public static bool M2<T>(A o) where T : I1
{
switch (o)
{
case T t:
return true;
default:
return false;
}
}
}
interface I1
{
}
struct A : I1
{
}
struct B : I1
{
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t;
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18)
);
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: "FalseFalseTrueTrue");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_07()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<B>(new A()));
Console.Write(M2<B>(new A()));
Console.Write(M1<A>(new A()));
Console.Write(M2<A>(new A()));
}
public static bool M1<T>(A o) where T : new()
{
return o is T t;
}
public static bool M2<T>(A o) where T : new()
{
switch (o)
{
case T t:
return true;
default:
return false;
}
}
}
struct A
{
}
struct B
{
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t;
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18)
);
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: "FalseFalseTrueTrue");
compVerifier.VerifyDiagnostics();
}
[Fact]
[WorkItem(16195, "https://github.com/dotnet/roslyn/issues/31269")]
public void TestIgnoreDynamicVsObjectAndTupleElementNames_01()
{
var source =
@"public class Generic<T>
{
public enum Color { Red=1, Blue=2 }
}
class Program
{
public static void Main(string[] args)
{
}
public static void M2(object o)
{
switch (o)
{
case Generic<long>.Color c:
case Generic<object>.Color.Red:
case Generic<(int x, int y)>.Color.Blue:
case Generic<string>.Color.Red:
case Generic<dynamic>.Color.Red: // error: duplicate case
case Generic<(int z, int w)>.Color.Blue: // error: duplicate case
case Generic<(int z, long w)>.Color.Blue:
default:
break;
}
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (18,13): error CS0152: The switch statement contains multiple cases with the label value '1'
// case Generic<dynamic>.Color.Red: // error: duplicate case
Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<dynamic>.Color.Red:").WithArguments("1").WithLocation(18, 13),
// (19,13): error CS0152: The switch statement contains multiple cases with the label value '2'
// case Generic<(int z, int w)>.Color.Blue: // error: duplicate case
Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<(int z, int w)>.Color.Blue:").WithArguments("2").WithLocation(19, 13)
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestIgnoreDynamicVsObjectAndTupleElementNames_02()
{
var source =
@"using System;
public class Generic<T>
{
public enum Color { X0, X1, X2, Green, Blue, Red }
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(M1<Generic<int>.Color>(Generic<long>.Color.Red)); // False
Console.WriteLine(M1<Generic<string>.Color>(Generic<object>.Color.Red)); // False
Console.WriteLine(M1<Generic<(int x, int y)>.Color>(Generic<(int z, int w)>.Color.Red)); // True
Console.WriteLine(M1<Generic<object>.Color>(Generic<dynamic>.Color.Blue)); // True
Console.WriteLine(M2(Generic<long>.Color.Red)); // Generic<long>.Color.Red
Console.WriteLine(M2(Generic<object>.Color.Blue)); // Generic<dynamic>.Color.Blue
Console.WriteLine(M2(Generic<int>.Color.Red)); // None
Console.WriteLine(M2(Generic<dynamic>.Color.Red)); // Generic<object>.Color.Red
}
public static bool M1<T>(object o)
{
return o is T t;
}
public static string M2(object o)
{
switch (o)
{
case Generic<long>.Color c:
return ""Generic<long>.Color."" + c;
case Generic<object>.Color.Red:
return ""Generic<object>.Color.Red"";
case Generic<dynamic>.Color.Blue:
return ""Generic<dynamic>.Color.Blue"";
default:
return ""None"";
}
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication))
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: @"False
False
True
True
Generic<long>.Color.Red
Generic<dynamic>.Color.Blue
None
Generic<object>.Color.Red");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 108 (0x6c)
.maxstack 2
.locals init (Generic<long>.Color V_0, //c
object V_1,
Generic<object>.Color V_2,
object V_3,
string V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""Generic<long>.Color""
IL_000b: brfalse.s IL_0016
IL_000d: ldloc.1
IL_000e: unbox.any ""Generic<long>.Color""
IL_0013: stloc.0
IL_0014: br.s IL_0031
IL_0016: ldloc.1
IL_0017: isinst ""Generic<object>.Color""
IL_001c: brfalse.s IL_0060
IL_001e: ldloc.1
IL_001f: unbox.any ""Generic<object>.Color""
IL_0024: stloc.2
IL_0025: ldloc.2
IL_0026: ldc.i4.4
IL_0027: beq.s IL_0057
IL_0029: br.s IL_002b
IL_002b: ldloc.2
IL_002c: ldc.i4.5
IL_002d: beq.s IL_004e
IL_002f: br.s IL_0060
IL_0031: br.s IL_0033
IL_0033: ldstr ""Generic<long>.Color.""
IL_0038: ldloca.s V_0
IL_003a: constrained. ""Generic<long>.Color""
IL_0040: callvirt ""string object.ToString()""
IL_0045: call ""string string.Concat(string, string)""
IL_004a: stloc.s V_4
IL_004c: br.s IL_0069
IL_004e: ldstr ""Generic<object>.Color.Red""
IL_0053: stloc.s V_4
IL_0055: br.s IL_0069
IL_0057: ldstr ""Generic<dynamic>.Color.Blue""
IL_005c: stloc.s V_4
IL_005e: br.s IL_0069
IL_0060: ldstr ""None""
IL_0065: stloc.s V_4
IL_0067: br.s IL_0069
IL_0069: ldloc.s V_4
IL_006b: ret
}
"
);
}
[Fact, WorkItem(16129, "https://github.com/dotnet/roslyn/issues/16129")]
public void ExactPatternMatch()
{
var source =
@"using System;
class C
{
static void Main()
{
if (TrySomething() is ValueTuple<string, bool> v && v.Item2)
{
System.Console.Write(v.Item1 == null);
}
}
static (string Value, bool Success) TrySomething()
{
return (null, true);
}
}";
var compilation = CreateCompilation(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication))
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: @"True");
compVerifier.VerifyIL("C.Main",
@"{
// Code size 29 (0x1d)
.maxstack 2
.locals init (System.ValueTuple<string, bool> V_0) //v
IL_0000: call ""System.ValueTuple<string, bool> C.TrySomething()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldfld ""bool System.ValueTuple<string, bool>.Item2""
IL_000c: brfalse.s IL_001c
IL_000e: ldloc.0
IL_000f: ldfld ""string System.ValueTuple<string, bool>.Item1""
IL_0014: ldnull
IL_0015: ceq
IL_0017: call ""void System.Console.Write(bool)""
IL_001c: ret
}"
);
}
[WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void ShareLikeKindedTemps_01()
{
var source = @"using System;
public class Program
{
public static void Main()
{
}
static bool b = false;
public static void M(object o)
{
switch (o)
{
case int i when b: break;
case var _ when b: break;
case int i when b: break;
case var _ when b: break;
case int i when b: break;
case var _ when b: break;
case int i when b: break;
case var _ when b: break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 106 (0x6a)
.maxstack 1
.locals init (int V_0, //i
object V_1)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: isinst ""int""
IL_0008: brfalse.s IL_0021
IL_000a: ldloc.1
IL_000b: unbox.any ""int""
IL_0010: stloc.0
IL_0011: ldsfld ""bool Program.b""
IL_0016: brtrue.s IL_0069
IL_0018: ldsfld ""bool Program.b""
IL_001d: brtrue.s IL_0069
IL_001f: br.s IL_002a
IL_0021: ldsfld ""bool Program.b""
IL_0026: brtrue.s IL_0069
IL_0028: br.s IL_003a
IL_002a: ldsfld ""bool Program.b""
IL_002f: brtrue.s IL_0069
IL_0031: ldsfld ""bool Program.b""
IL_0036: brtrue.s IL_0069
IL_0038: br.s IL_0043
IL_003a: ldsfld ""bool Program.b""
IL_003f: brtrue.s IL_0069
IL_0041: br.s IL_0053
IL_0043: ldsfld ""bool Program.b""
IL_0048: brtrue.s IL_0069
IL_004a: ldsfld ""bool Program.b""
IL_004f: brtrue.s IL_0069
IL_0051: br.s IL_005c
IL_0053: ldsfld ""bool Program.b""
IL_0058: brtrue.s IL_0069
IL_005a: br.s IL_0063
IL_005c: ldsfld ""bool Program.b""
IL_0061: brtrue.s IL_0069
IL_0063: ldsfld ""bool Program.b""
IL_0068: pop
IL_0069: ret
}"
);
compVerifier = CompileAndVerify(source,
expectedOutput: "",
symbolValidator: validator,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication).WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Program");
Assert.Null(type.GetMember(".cctor"));
}
compVerifier.VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source,
expectedIL: @"{
// Code size 149 (0x95)
.maxstack 1
.locals init (int V_0, //i
int V_1, //i
int V_2, //i
int V_3, //i
object V_4,
object V_5)
// sequence point: {
IL_0000: nop
// sequence point: switch (o)
IL_0001: ldarg.0
IL_0002: stloc.s V_5
// sequence point: <hidden>
IL_0004: ldloc.s V_5
IL_0006: stloc.s V_4
// sequence point: <hidden>
IL_0008: ldloc.s V_4
IL_000a: isinst ""int""
IL_000f: brfalse.s IL_002f
IL_0011: ldloc.s V_4
IL_0013: unbox.any ""int""
IL_0018: stloc.0
// sequence point: <hidden>
IL_0019: br.s IL_001b
// sequence point: when b
IL_001b: ldsfld ""bool Program.b""
IL_0020: brtrue.s IL_0024
// sequence point: <hidden>
IL_0022: br.s IL_0026
// sequence point: break;
IL_0024: br.s IL_0094
// sequence point: when b
IL_0026: ldsfld ""bool Program.b""
IL_002b: brtrue.s IL_0038
// sequence point: <hidden>
IL_002d: br.s IL_003a
// sequence point: when b
IL_002f: ldsfld ""bool Program.b""
IL_0034: brtrue.s IL_0038
// sequence point: <hidden>
IL_0036: br.s IL_0050
// sequence point: break;
IL_0038: br.s IL_0094
// sequence point: <hidden>
IL_003a: ldloc.0
IL_003b: stloc.1
// sequence point: when b
IL_003c: ldsfld ""bool Program.b""
IL_0041: brtrue.s IL_0045
// sequence point: <hidden>
IL_0043: br.s IL_0047
// sequence point: break;
IL_0045: br.s IL_0094
// sequence point: when b
IL_0047: ldsfld ""bool Program.b""
IL_004c: brtrue.s IL_0059
// sequence point: <hidden>
IL_004e: br.s IL_005b
// sequence point: when b
IL_0050: ldsfld ""bool Program.b""
IL_0055: brtrue.s IL_0059
// sequence point: <hidden>
IL_0057: br.s IL_0071
// sequence point: break;
IL_0059: br.s IL_0094
// sequence point: <hidden>
IL_005b: ldloc.0
IL_005c: stloc.2
// sequence point: when b
IL_005d: ldsfld ""bool Program.b""
IL_0062: brtrue.s IL_0066
// sequence point: <hidden>
IL_0064: br.s IL_0068
// sequence point: break;
IL_0066: br.s IL_0094
// sequence point: when b
IL_0068: ldsfld ""bool Program.b""
IL_006d: brtrue.s IL_007a
// sequence point: <hidden>
IL_006f: br.s IL_007c
// sequence point: when b
IL_0071: ldsfld ""bool Program.b""
IL_0076: brtrue.s IL_007a
// sequence point: <hidden>
IL_0078: br.s IL_0089
// sequence point: break;
IL_007a: br.s IL_0094
// sequence point: <hidden>
IL_007c: ldloc.0
IL_007d: stloc.3
// sequence point: when b
IL_007e: ldsfld ""bool Program.b""
IL_0083: brtrue.s IL_0087
// sequence point: <hidden>
IL_0085: br.s IL_0089
// sequence point: break;
IL_0087: br.s IL_0094
// sequence point: when b
IL_0089: ldsfld ""bool Program.b""
IL_008e: brtrue.s IL_0092
// sequence point: <hidden>
IL_0090: br.s IL_0094
// sequence point: break;
IL_0092: br.s IL_0094
// sequence point: }
IL_0094: ret
}"
);
compVerifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""Program"" methodName=""Main"" />
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Program"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""55"" />
<slot kind=""0"" offset=""133"" />
<slot kind=""0"" offset=""211"" />
<slot kind=""0"" offset=""289"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""38"" document=""1"" />
<entry offset=""0x26"" startLine=""13"" startColumn=""24"" endLine=""13"" endColumn=""30"" document=""1"" />
<entry offset=""0x2d"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""13"" startColumn=""24"" endLine=""13"" endColumn=""30"" document=""1"" />
<entry offset=""0x36"" hidden=""true"" document=""1"" />
<entry offset=""0x38"" startLine=""13"" startColumn=""32"" endLine=""13"" endColumn=""38"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""14"" startColumn=""24"" endLine=""14"" endColumn=""30"" document=""1"" />
<entry offset=""0x43"" hidden=""true"" document=""1"" />
<entry offset=""0x45"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""38"" document=""1"" />
<entry offset=""0x47"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""30"" document=""1"" />
<entry offset=""0x4e"" hidden=""true"" document=""1"" />
<entry offset=""0x50"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""30"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x59"" startLine=""15"" startColumn=""32"" endLine=""15"" endColumn=""38"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x5d"" startLine=""16"" startColumn=""24"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x64"" hidden=""true"" document=""1"" />
<entry offset=""0x66"" startLine=""16"" startColumn=""32"" endLine=""16"" endColumn=""38"" document=""1"" />
<entry offset=""0x68"" startLine=""17"" startColumn=""24"" endLine=""17"" endColumn=""30"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x71"" startLine=""17"" startColumn=""24"" endLine=""17"" endColumn=""30"" document=""1"" />
<entry offset=""0x78"" hidden=""true"" document=""1"" />
<entry offset=""0x7a"" startLine=""17"" startColumn=""32"" endLine=""17"" endColumn=""38"" document=""1"" />
<entry offset=""0x7c"" hidden=""true"" document=""1"" />
<entry offset=""0x7e"" startLine=""18"" startColumn=""24"" endLine=""18"" endColumn=""30"" document=""1"" />
<entry offset=""0x85"" hidden=""true"" document=""1"" />
<entry offset=""0x87"" startLine=""18"" startColumn=""32"" endLine=""18"" endColumn=""38"" document=""1"" />
<entry offset=""0x89"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""30"" document=""1"" />
<entry offset=""0x90"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" startLine=""19"" startColumn=""32"" endLine=""19"" endColumn=""38"" document=""1"" />
<entry offset=""0x94"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x95"">
<scope startOffset=""0x1b"" endOffset=""0x26"">
<local name=""i"" il_index=""0"" il_start=""0x1b"" il_end=""0x26"" attributes=""0"" />
</scope>
<scope startOffset=""0x3a"" endOffset=""0x47"">
<local name=""i"" il_index=""1"" il_start=""0x3a"" il_end=""0x47"" attributes=""0"" />
</scope>
<scope startOffset=""0x5b"" endOffset=""0x68"">
<local name=""i"" il_index=""2"" il_start=""0x5b"" il_end=""0x68"" attributes=""0"" />
</scope>
<scope startOffset=""0x7c"" endOffset=""0x89"">
<local name=""i"" il_index=""3"" il_start=""0x7c"" il_end=""0x89"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")]
public void TestSignificanceOfDynamicVersusObjectAndTupleNamesInUniquenessOfPatternMatchingTemps()
{
var source =
@"using System;
public class Generic<T,U>
{
}
class Program
{
public static void Main(string[] args)
{
var g = new Generic<object, (int, int)>();
M2(g, true, false, false);
M2(g, false, true, false);
M2(g, false, false, true);
}
public static void M2(object o, bool b1, bool b2, bool b3)
{
switch (o)
{
case Generic<object, (int a, int b)> g when b1: Console.Write(""a""); break;
case var _ when b2: Console.Write(""b""); break;
case Generic<dynamic, (int x, int y)> g when b3: Console.Write(""c""); break;
}
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication))
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "abc");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 79 (0x4f)
.maxstack 1
.locals init (Generic<object, System.ValueTuple<int, int>> V_0, //g
Generic<dynamic, System.ValueTuple<int, int>> V_1, //g
object V_2,
object V_3)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.2
IL_0005: ldloc.2
IL_0006: isinst ""Generic<object, System.ValueTuple<int, int>>""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0011
IL_000f: br.s IL_0028
IL_0011: ldarg.1
IL_0012: brtrue.s IL_0016
IL_0014: br.s IL_0023
IL_0016: ldstr ""a""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: nop
IL_0021: br.s IL_004e
IL_0023: ldarg.2
IL_0024: brtrue.s IL_002d
IL_0026: br.s IL_003a
IL_0028: ldarg.2
IL_0029: brtrue.s IL_002d
IL_002b: br.s IL_004e
IL_002d: ldstr ""b""
IL_0032: call ""void System.Console.Write(string)""
IL_0037: nop
IL_0038: br.s IL_004e
IL_003a: ldloc.0
IL_003b: stloc.1
IL_003c: ldarg.3
IL_003d: brtrue.s IL_0041
IL_003f: br.s IL_004e
IL_0041: ldstr ""c""
IL_0046: call ""void System.Console.Write(string)""
IL_004b: nop
IL_004c: br.s IL_004e
IL_004e: ret
}
"
);
}
[Fact]
[WorkItem(39564, "https://github.com/dotnet/roslyn/issues/39564")]
public void OrderOfEvaluationOfTupleAsSwitchExpressionArgument()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
using var sr = new System.IO.StringReader(""fiz\nbar"");
var r = (sr.ReadLine(), sr.ReadLine()) switch
{
(""fiz"", ""bar"") => ""Yep, all good!"",
var (a, b) => $""Wait, what? I got ({a}, {b})!"",
};
Console.WriteLine(r);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!");
compVerifier.VerifyIL("Program.Main", @"
{
// Code size 144 (0x90)
.maxstack 4
.locals init (System.IO.StringReader V_0, //sr
string V_1, //r
string V_2, //a
string V_3, //b
string V_4)
IL_0000: nop
IL_0001: ldstr ""fiz
bar""
IL_0006: newobj ""System.IO.StringReader..ctor(string)""
IL_000b: stloc.0
.try
{
IL_000c: ldloc.0
IL_000d: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0012: stloc.2
IL_0013: ldloc.0
IL_0014: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0019: stloc.3
IL_001a: ldc.i4.1
IL_001b: brtrue.s IL_001e
IL_001d: nop
IL_001e: ldloc.2
IL_001f: ldstr ""fiz""
IL_0024: call ""bool string.op_Equality(string, string)""
IL_0029: brfalse.s IL_0043
IL_002b: ldloc.3
IL_002c: ldstr ""bar""
IL_0031: call ""bool string.op_Equality(string, string)""
IL_0036: brtrue.s IL_003a
IL_0038: br.s IL_0043
IL_003a: ldstr ""Yep, all good!""
IL_003f: stloc.s V_4
IL_0041: br.s IL_0074
IL_0043: br.s IL_0045
IL_0045: ldc.i4.5
IL_0046: newarr ""string""
IL_004b: dup
IL_004c: ldc.i4.0
IL_004d: ldstr ""Wait, what? I got (""
IL_0052: stelem.ref
IL_0053: dup
IL_0054: ldc.i4.1
IL_0055: ldloc.2
IL_0056: stelem.ref
IL_0057: dup
IL_0058: ldc.i4.2
IL_0059: ldstr "", ""
IL_005e: stelem.ref
IL_005f: dup
IL_0060: ldc.i4.3
IL_0061: ldloc.3
IL_0062: stelem.ref
IL_0063: dup
IL_0064: ldc.i4.4
IL_0065: ldstr "")!""
IL_006a: stelem.ref
IL_006b: call ""string string.Concat(params string[])""
IL_0070: stloc.s V_4
IL_0072: br.s IL_0074
IL_0074: ldc.i4.1
IL_0075: brtrue.s IL_0078
IL_0077: nop
IL_0078: ldloc.s V_4
IL_007a: stloc.1
IL_007b: ldloc.1
IL_007c: call ""void System.Console.WriteLine(string)""
IL_0081: nop
IL_0082: leave.s IL_008f
}
finally
{
IL_0084: ldloc.0
IL_0085: brfalse.s IL_008e
IL_0087: ldloc.0
IL_0088: callvirt ""void System.IDisposable.Dispose()""
IL_008d: nop
IL_008e: endfinally
}
IL_008f: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe)
.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!");
compVerifier.VerifyIL("Program.Main", @"
{
// Code size 122 (0x7a)
.maxstack 4
.locals init (System.IO.StringReader V_0, //sr
string V_1, //a
string V_2, //b
string V_3)
IL_0000: ldstr ""fiz
bar""
IL_0005: newobj ""System.IO.StringReader..ctor(string)""
IL_000a: stloc.0
.try
{
IL_000b: ldloc.0
IL_000c: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0018: stloc.2
IL_0019: ldloc.1
IL_001a: ldstr ""fiz""
IL_001f: call ""bool string.op_Equality(string, string)""
IL_0024: brfalse.s IL_003b
IL_0026: ldloc.2
IL_0027: ldstr ""bar""
IL_002c: call ""bool string.op_Equality(string, string)""
IL_0031: brfalse.s IL_003b
IL_0033: ldstr ""Yep, all good!""
IL_0038: stloc.3
IL_0039: br.s IL_0067
IL_003b: ldc.i4.5
IL_003c: newarr ""string""
IL_0041: dup
IL_0042: ldc.i4.0
IL_0043: ldstr ""Wait, what? I got (""
IL_0048: stelem.ref
IL_0049: dup
IL_004a: ldc.i4.1
IL_004b: ldloc.1
IL_004c: stelem.ref
IL_004d: dup
IL_004e: ldc.i4.2
IL_004f: ldstr "", ""
IL_0054: stelem.ref
IL_0055: dup
IL_0056: ldc.i4.3
IL_0057: ldloc.2
IL_0058: stelem.ref
IL_0059: dup
IL_005a: ldc.i4.4
IL_005b: ldstr "")!""
IL_0060: stelem.ref
IL_0061: call ""string string.Concat(params string[])""
IL_0066: stloc.3
IL_0067: ldloc.3
IL_0068: call ""void System.Console.WriteLine(string)""
IL_006d: leave.s IL_0079
}
finally
{
IL_006f: ldloc.0
IL_0070: brfalse.s IL_0078
IL_0072: ldloc.0
IL_0073: callvirt ""void System.IDisposable.Dispose()""
IL_0078: endfinally
}
IL_0079: ret
}
");
}
[Fact]
[WorkItem(41502, "https://github.com/dotnet/roslyn/issues/41502")]
public void PatternSwitchDagReduction_01()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
M(1, 1, 6); // 1
M(1, 2, 6); // 2
M(1, 1, 3); // 3
M(1, 2, 3); // 3
M(1, 5, 3); // 3
M(2, 5, 3); // 3
M(1, 3, 4); // 4
M(2, 1, 4); // 5
M(2, 2, 2); // 6
}
public static void M(int a, int b, int c) => Console.Write(M2(a, b, c));
public static int M2(int a, int b, int c) => (a, b, c) switch
{
(1, 1, 6) => 1,
(1, 2, 6) => 2,
(_, _, 3) => 3,
(1, _, _) => 4,
(_, 1, _) => 5,
(_, _, _) => 6,
};
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456");
compVerifier.VerifyIL("Program.M2", @"
{
// Code size 76 (0x4c)
.maxstack 2
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.0
IL_0005: ldc.i4.1
IL_0006: bne.un.s IL_0024
IL_0008: ldarg.1
IL_0009: ldc.i4.1
IL_000a: beq.s IL_0014
IL_000c: br.s IL_000e
IL_000e: ldarg.1
IL_000f: ldc.i4.2
IL_0010: beq.s IL_001a
IL_0012: br.s IL_001e
IL_0014: ldarg.2
IL_0015: ldc.i4.6
IL_0016: beq.s IL_002e
IL_0018: br.s IL_001e
IL_001a: ldarg.2
IL_001b: ldc.i4.6
IL_001c: beq.s IL_0032
IL_001e: ldarg.2
IL_001f: ldc.i4.3
IL_0020: beq.s IL_0036
IL_0022: br.s IL_003a
IL_0024: ldarg.2
IL_0025: ldc.i4.3
IL_0026: beq.s IL_0036
IL_0028: ldarg.1
IL_0029: ldc.i4.1
IL_002a: beq.s IL_003e
IL_002c: br.s IL_0042
IL_002e: ldc.i4.1
IL_002f: stloc.0
IL_0030: br.s IL_0046
IL_0032: ldc.i4.2
IL_0033: stloc.0
IL_0034: br.s IL_0046
IL_0036: ldc.i4.3
IL_0037: stloc.0
IL_0038: br.s IL_0046
IL_003a: ldc.i4.4
IL_003b: stloc.0
IL_003c: br.s IL_0046
IL_003e: ldc.i4.5
IL_003f: stloc.0
IL_0040: br.s IL_0046
IL_0042: ldc.i4.6
IL_0043: stloc.0
IL_0044: br.s IL_0046
IL_0046: ldc.i4.1
IL_0047: brtrue.s IL_004a
IL_0049: nop
IL_004a: ldloc.0
IL_004b: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9)
.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456");
compVerifier.VerifyIL("Program.M2", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: bne.un.s IL_001e
IL_0004: ldarg.1
IL_0005: ldc.i4.1
IL_0006: beq.s IL_000e
IL_0008: ldarg.1
IL_0009: ldc.i4.2
IL_000a: beq.s IL_0014
IL_000c: br.s IL_0018
IL_000e: ldarg.2
IL_000f: ldc.i4.6
IL_0010: beq.s IL_0028
IL_0012: br.s IL_0018
IL_0014: ldarg.2
IL_0015: ldc.i4.6
IL_0016: beq.s IL_002c
IL_0018: ldarg.2
IL_0019: ldc.i4.3
IL_001a: beq.s IL_0030
IL_001c: br.s IL_0034
IL_001e: ldarg.2
IL_001f: ldc.i4.3
IL_0020: beq.s IL_0030
IL_0022: ldarg.1
IL_0023: ldc.i4.1
IL_0024: beq.s IL_0038
IL_0026: br.s IL_003c
IL_0028: ldc.i4.1
IL_0029: stloc.0
IL_002a: br.s IL_003e
IL_002c: ldc.i4.2
IL_002d: stloc.0
IL_002e: br.s IL_003e
IL_0030: ldc.i4.3
IL_0031: stloc.0
IL_0032: br.s IL_003e
IL_0034: ldc.i4.4
IL_0035: stloc.0
IL_0036: br.s IL_003e
IL_0038: ldc.i4.5
IL_0039: stloc.0
IL_003a: br.s IL_003e
IL_003c: ldc.i4.6
IL_003d: stloc.0
IL_003e: ldloc.0
IL_003f: ret
}
");
}
#endregion "regression tests"
#region Code Quality tests
[Fact]
public void BalancedSwitchDispatch_Double()
{
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2.1D));
Console.WriteLine(M(3.1D));
Console.WriteLine(M(4.1D));
Console.WriteLine(M(5.1D));
Console.WriteLine(M(6.1D));
Console.WriteLine(M(7.1D));
Console.WriteLine(M(8.1D));
Console.WriteLine(M(9.1D));
Console.WriteLine(M(10.1D));
Console.WriteLine(M(11.1D));
Console.WriteLine(M(12.1D));
Console.WriteLine(M(13.1D));
Console.WriteLine(M(14.1D));
Console.WriteLine(M(15.1D));
Console.WriteLine(M(16.1D));
Console.WriteLine(M(17.1D));
Console.WriteLine(M(18.1D));
Console.WriteLine(M(19.1D));
Console.WriteLine(M(20.1D));
Console.WriteLine(M(21.1D));
Console.WriteLine(M(22.1D));
Console.WriteLine(M(23.1D));
Console.WriteLine(M(24.1D));
Console.WriteLine(M(25.1D));
Console.WriteLine(M(26.1D));
Console.WriteLine(M(27.1D));
Console.WriteLine(M(28.1D));
Console.WriteLine(M(29.1D));
}
static int M(double d)
{
return d switch
{
>= 27.1D and < 29.1D => 19,
26.1D => 18,
9.1D => 5,
>= 2.1D and < 4.1D => 1,
12.1D => 8,
>= 21.1D and < 23.1D => 15,
19.1D => 13,
29.1D => 20,
>= 13.1D and < 15.1D => 9,
10.1D => 6,
15.1D => 10,
11.1D => 7,
4.1D => 2,
>= 16.1D and < 18.1D => 11,
>= 23.1D and < 25.1D => 16,
18.1D => 12,
>= 7.1D and < 9.1D => 4,
25.1D => 17,
20.1D => 14,
>= 5.1D and < 7.1D => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 499 (0x1f3)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.r8 13.1
IL_000a: blt.un IL_00fb
IL_000f: ldarg.0
IL_0010: ldc.r8 21.1
IL_0019: blt.un.s IL_008b
IL_001b: ldarg.0
IL_001c: ldc.r8 27.1
IL_0025: blt.un.s IL_004a
IL_0027: ldarg.0
IL_0028: ldc.r8 29.1
IL_0031: blt IL_0193
IL_0036: ldarg.0
IL_0037: ldc.r8 29.1
IL_0040: beq IL_01b3
IL_0045: br IL_01ef
IL_004a: ldarg.0
IL_004b: ldc.r8 23.1
IL_0054: blt IL_01a9
IL_0059: ldarg.0
IL_005a: ldc.r8 25.1
IL_0063: blt IL_01d3
IL_0068: ldarg.0
IL_0069: ldc.r8 25.1
IL_0072: beq IL_01e1
IL_0077: ldarg.0
IL_0078: ldc.r8 26.1
IL_0081: beq IL_0198
IL_0086: br IL_01ef
IL_008b: ldarg.0
IL_008c: ldc.r8 16.1
IL_0095: blt.un.s IL_00d8
IL_0097: ldarg.0
IL_0098: ldc.r8 18.1
IL_00a1: blt IL_01ce
IL_00a6: ldarg.0
IL_00a7: ldc.r8 18.1
IL_00b0: beq IL_01d8
IL_00b5: ldarg.0
IL_00b6: ldc.r8 19.1
IL_00bf: beq IL_01ae
IL_00c4: ldarg.0
IL_00c5: ldc.r8 20.1
IL_00ce: beq IL_01e6
IL_00d3: br IL_01ef
IL_00d8: ldarg.0
IL_00d9: ldc.r8 15.1
IL_00e2: blt IL_01b8
IL_00e7: ldarg.0
IL_00e8: ldc.r8 15.1
IL_00f1: beq IL_01c1
IL_00f6: br IL_01ef
IL_00fb: ldarg.0
IL_00fc: ldc.r8 7.1
IL_0105: blt.un.s IL_015f
IL_0107: ldarg.0
IL_0108: ldc.r8 9.1
IL_0111: blt IL_01dd
IL_0116: ldarg.0
IL_0117: ldc.r8 10.1
IL_0120: bgt.un.s IL_0142
IL_0122: ldarg.0
IL_0123: ldc.r8 9.1
IL_012c: beq.s IL_019d
IL_012e: ldarg.0
IL_012f: ldc.r8 10.1
IL_0138: beq IL_01bd
IL_013d: br IL_01ef
IL_0142: ldarg.0
IL_0143: ldc.r8 11.1
IL_014c: beq.s IL_01c6
IL_014e: ldarg.0
IL_014f: ldc.r8 12.1
IL_0158: beq.s IL_01a5
IL_015a: br IL_01ef
IL_015f: ldarg.0
IL_0160: ldc.r8 4.1
IL_0169: bge.un.s IL_0179
IL_016b: ldarg.0
IL_016c: ldc.r8 2.1
IL_0175: bge.s IL_01a1
IL_0177: br.s IL_01ef
IL_0179: ldarg.0
IL_017a: ldc.r8 5.1
IL_0183: bge.s IL_01eb
IL_0185: ldarg.0
IL_0186: ldc.r8 4.1
IL_018f: beq.s IL_01ca
IL_0191: br.s IL_01ef
IL_0193: ldc.i4.s 19
IL_0195: stloc.0
IL_0196: br.s IL_01f1
IL_0198: ldc.i4.s 18
IL_019a: stloc.0
IL_019b: br.s IL_01f1
IL_019d: ldc.i4.5
IL_019e: stloc.0
IL_019f: br.s IL_01f1
IL_01a1: ldc.i4.1
IL_01a2: stloc.0
IL_01a3: br.s IL_01f1
IL_01a5: ldc.i4.8
IL_01a6: stloc.0
IL_01a7: br.s IL_01f1
IL_01a9: ldc.i4.s 15
IL_01ab: stloc.0
IL_01ac: br.s IL_01f1
IL_01ae: ldc.i4.s 13
IL_01b0: stloc.0
IL_01b1: br.s IL_01f1
IL_01b3: ldc.i4.s 20
IL_01b5: stloc.0
IL_01b6: br.s IL_01f1
IL_01b8: ldc.i4.s 9
IL_01ba: stloc.0
IL_01bb: br.s IL_01f1
IL_01bd: ldc.i4.6
IL_01be: stloc.0
IL_01bf: br.s IL_01f1
IL_01c1: ldc.i4.s 10
IL_01c3: stloc.0
IL_01c4: br.s IL_01f1
IL_01c6: ldc.i4.7
IL_01c7: stloc.0
IL_01c8: br.s IL_01f1
IL_01ca: ldc.i4.2
IL_01cb: stloc.0
IL_01cc: br.s IL_01f1
IL_01ce: ldc.i4.s 11
IL_01d0: stloc.0
IL_01d1: br.s IL_01f1
IL_01d3: ldc.i4.s 16
IL_01d5: stloc.0
IL_01d6: br.s IL_01f1
IL_01d8: ldc.i4.s 12
IL_01da: stloc.0
IL_01db: br.s IL_01f1
IL_01dd: ldc.i4.4
IL_01de: stloc.0
IL_01df: br.s IL_01f1
IL_01e1: ldc.i4.s 17
IL_01e3: stloc.0
IL_01e4: br.s IL_01f1
IL_01e6: ldc.i4.s 14
IL_01e8: stloc.0
IL_01e9: br.s IL_01f1
IL_01eb: ldc.i4.3
IL_01ec: stloc.0
IL_01ed: br.s IL_01f1
IL_01ef: ldc.i4.0
IL_01f0: stloc.0
IL_01f1: ldloc.0
IL_01f2: ret
}
"
);
}
[Fact]
public void BalancedSwitchDispatch_Float()
{
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2.1F));
Console.WriteLine(M(3.1F));
Console.WriteLine(M(4.1F));
Console.WriteLine(M(5.1F));
Console.WriteLine(M(6.1F));
Console.WriteLine(M(7.1F));
Console.WriteLine(M(8.1F));
Console.WriteLine(M(9.1F));
Console.WriteLine(M(10.1F));
Console.WriteLine(M(11.1F));
Console.WriteLine(M(12.1F));
Console.WriteLine(M(13.1F));
Console.WriteLine(M(14.1F));
Console.WriteLine(M(15.1F));
Console.WriteLine(M(16.1F));
Console.WriteLine(M(17.1F));
Console.WriteLine(M(18.1F));
Console.WriteLine(M(19.1F));
Console.WriteLine(M(20.1F));
Console.WriteLine(M(21.1F));
Console.WriteLine(M(22.1F));
Console.WriteLine(M(23.1F));
Console.WriteLine(M(24.1F));
Console.WriteLine(M(25.1F));
Console.WriteLine(M(26.1F));
Console.WriteLine(M(27.1F));
Console.WriteLine(M(28.1F));
Console.WriteLine(M(29.1F));
}
static int M(float d)
{
return d switch
{
>= 27.1F and < 29.1F => 19,
26.1F => 18,
9.1F => 5,
>= 2.1F and < 4.1F => 1,
12.1F => 8,
>= 21.1F and < 23.1F => 15,
19.1F => 13,
29.1F => 20,
>= 13.1F and < 15.1F => 9,
10.1F => 6,
15.1F => 10,
11.1F => 7,
4.1F => 2,
>= 16.1F and < 18.1F => 11,
>= 23.1F and < 25.1F => 16,
18.1F => 12,
>= 7.1F and < 9.1F => 4,
25.1F => 17,
20.1F => 14,
>= 5.1F and < 7.1F => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 388 (0x184)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.r4 13.1
IL_0006: blt.un IL_00bb
IL_000b: ldarg.0
IL_000c: ldc.r4 21.1
IL_0011: blt.un.s IL_0067
IL_0013: ldarg.0
IL_0014: ldc.r4 27.1
IL_0019: blt.un.s IL_0036
IL_001b: ldarg.0
IL_001c: ldc.r4 29.1
IL_0021: blt IL_0124
IL_0026: ldarg.0
IL_0027: ldc.r4 29.1
IL_002c: beq IL_0144
IL_0031: br IL_0180
IL_0036: ldarg.0
IL_0037: ldc.r4 23.1
IL_003c: blt IL_013a
IL_0041: ldarg.0
IL_0042: ldc.r4 25.1
IL_0047: blt IL_0164
IL_004c: ldarg.0
IL_004d: ldc.r4 25.1
IL_0052: beq IL_0172
IL_0057: ldarg.0
IL_0058: ldc.r4 26.1
IL_005d: beq IL_0129
IL_0062: br IL_0180
IL_0067: ldarg.0
IL_0068: ldc.r4 16.1
IL_006d: blt.un.s IL_00a0
IL_006f: ldarg.0
IL_0070: ldc.r4 18.1
IL_0075: blt IL_015f
IL_007a: ldarg.0
IL_007b: ldc.r4 18.1
IL_0080: beq IL_0169
IL_0085: ldarg.0
IL_0086: ldc.r4 19.1
IL_008b: beq IL_013f
IL_0090: ldarg.0
IL_0091: ldc.r4 20.1
IL_0096: beq IL_0177
IL_009b: br IL_0180
IL_00a0: ldarg.0
IL_00a1: ldc.r4 15.1
IL_00a6: blt IL_0149
IL_00ab: ldarg.0
IL_00ac: ldc.r4 15.1
IL_00b1: beq IL_0152
IL_00b6: br IL_0180
IL_00bb: ldarg.0
IL_00bc: ldc.r4 7.1
IL_00c1: blt.un.s IL_0100
IL_00c3: ldarg.0
IL_00c4: ldc.r4 9.1
IL_00c9: blt IL_016e
IL_00ce: ldarg.0
IL_00cf: ldc.r4 10.1
IL_00d4: bgt.un.s IL_00eb
IL_00d6: ldarg.0
IL_00d7: ldc.r4 9.1
IL_00dc: beq.s IL_012e
IL_00de: ldarg.0
IL_00df: ldc.r4 10.1
IL_00e4: beq.s IL_014e
IL_00e6: br IL_0180
IL_00eb: ldarg.0
IL_00ec: ldc.r4 11.1
IL_00f1: beq.s IL_0157
IL_00f3: ldarg.0
IL_00f4: ldc.r4 12.1
IL_00f9: beq.s IL_0136
IL_00fb: br IL_0180
IL_0100: ldarg.0
IL_0101: ldc.r4 4.1
IL_0106: bge.un.s IL_0112
IL_0108: ldarg.0
IL_0109: ldc.r4 2.1
IL_010e: bge.s IL_0132
IL_0110: br.s IL_0180
IL_0112: ldarg.0
IL_0113: ldc.r4 5.1
IL_0118: bge.s IL_017c
IL_011a: ldarg.0
IL_011b: ldc.r4 4.1
IL_0120: beq.s IL_015b
IL_0122: br.s IL_0180
IL_0124: ldc.i4.s 19
IL_0126: stloc.0
IL_0127: br.s IL_0182
IL_0129: ldc.i4.s 18
IL_012b: stloc.0
IL_012c: br.s IL_0182
IL_012e: ldc.i4.5
IL_012f: stloc.0
IL_0130: br.s IL_0182
IL_0132: ldc.i4.1
IL_0133: stloc.0
IL_0134: br.s IL_0182
IL_0136: ldc.i4.8
IL_0137: stloc.0
IL_0138: br.s IL_0182
IL_013a: ldc.i4.s 15
IL_013c: stloc.0
IL_013d: br.s IL_0182
IL_013f: ldc.i4.s 13
IL_0141: stloc.0
IL_0142: br.s IL_0182
IL_0144: ldc.i4.s 20
IL_0146: stloc.0
IL_0147: br.s IL_0182
IL_0149: ldc.i4.s 9
IL_014b: stloc.0
IL_014c: br.s IL_0182
IL_014e: ldc.i4.6
IL_014f: stloc.0
IL_0150: br.s IL_0182
IL_0152: ldc.i4.s 10
IL_0154: stloc.0
IL_0155: br.s IL_0182
IL_0157: ldc.i4.7
IL_0158: stloc.0
IL_0159: br.s IL_0182
IL_015b: ldc.i4.2
IL_015c: stloc.0
IL_015d: br.s IL_0182
IL_015f: ldc.i4.s 11
IL_0161: stloc.0
IL_0162: br.s IL_0182
IL_0164: ldc.i4.s 16
IL_0166: stloc.0
IL_0167: br.s IL_0182
IL_0169: ldc.i4.s 12
IL_016b: stloc.0
IL_016c: br.s IL_0182
IL_016e: ldc.i4.4
IL_016f: stloc.0
IL_0170: br.s IL_0182
IL_0172: ldc.i4.s 17
IL_0174: stloc.0
IL_0175: br.s IL_0182
IL_0177: ldc.i4.s 14
IL_0179: stloc.0
IL_017a: br.s IL_0182
IL_017c: ldc.i4.3
IL_017d: stloc.0
IL_017e: br.s IL_0182
IL_0180: ldc.i4.0
IL_0181: stloc.0
IL_0182: ldloc.0
IL_0183: ret
}
"
);
}
[Fact]
public void BalancedSwitchDispatch_Decimal()
{
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2.1M));
Console.WriteLine(M(3.1M));
Console.WriteLine(M(4.1M));
Console.WriteLine(M(5.1M));
Console.WriteLine(M(6.1M));
Console.WriteLine(M(7.1M));
Console.WriteLine(M(8.1M));
Console.WriteLine(M(9.1M));
Console.WriteLine(M(10.1M));
Console.WriteLine(M(11.1M));
Console.WriteLine(M(12.1M));
Console.WriteLine(M(13.1M));
Console.WriteLine(M(14.1M));
Console.WriteLine(M(15.1M));
Console.WriteLine(M(16.1M));
Console.WriteLine(M(17.1M));
Console.WriteLine(M(18.1M));
Console.WriteLine(M(19.1M));
Console.WriteLine(M(20.1M));
Console.WriteLine(M(21.1M));
Console.WriteLine(M(22.1M));
Console.WriteLine(M(23.1M));
Console.WriteLine(M(24.1M));
Console.WriteLine(M(25.1M));
Console.WriteLine(M(26.1M));
Console.WriteLine(M(27.1M));
Console.WriteLine(M(28.1M));
Console.WriteLine(M(29.1M));
}
static int M(decimal d)
{
return d switch
{
>= 27.1M and < 29.1M => 19,
26.1M => 18,
9.1M => 5,
>= 2.1M and < 4.1M => 1,
12.1M => 8,
>= 21.1M and < 23.1M => 15,
19.1M => 13,
29.1M => 20,
>= 13.1M and < 15.1M => 9,
10.1M => 6,
15.1M => 10,
11.1M => 7,
4.1M => 2,
>= 16.1M and < 18.1M => 11,
>= 23.1M and < 25.1M => 16,
18.1M => 12,
>= 7.1M and < 9.1M => 4,
25.1M => 17,
20.1M => 14,
>= 5.1M and < 7.1M => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 751 (0x2ef)
.maxstack 6
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4 0x83
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000f: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0014: brfalse IL_019e
IL_0019: ldarg.0
IL_001a: ldc.i4 0xd3
IL_001f: ldc.i4.0
IL_0020: ldc.i4.0
IL_0021: ldc.i4.0
IL_0022: ldc.i4.1
IL_0023: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0028: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_002d: brfalse IL_00e8
IL_0032: ldarg.0
IL_0033: ldc.i4 0x10f
IL_0038: ldc.i4.0
IL_0039: ldc.i4.0
IL_003a: ldc.i4.0
IL_003b: ldc.i4.1
IL_003c: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0041: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0046: brfalse.s IL_007f
IL_0048: ldarg.0
IL_0049: ldc.i4 0x123
IL_004e: ldc.i4.0
IL_004f: ldc.i4.0
IL_0050: ldc.i4.0
IL_0051: ldc.i4.1
IL_0052: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0057: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_005c: brtrue IL_028f
IL_0061: ldarg.0
IL_0062: ldc.i4 0x123
IL_0067: ldc.i4.0
IL_0068: ldc.i4.0
IL_0069: ldc.i4.0
IL_006a: ldc.i4.1
IL_006b: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0070: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0075: brtrue IL_02af
IL_007a: br IL_02eb
IL_007f: ldarg.0
IL_0080: ldc.i4 0xe7
IL_0085: ldc.i4.0
IL_0086: ldc.i4.0
IL_0087: ldc.i4.0
IL_0088: ldc.i4.1
IL_0089: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_008e: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_0093: brtrue IL_02a5
IL_0098: ldarg.0
IL_0099: ldc.i4 0xfb
IL_009e: ldc.i4.0
IL_009f: ldc.i4.0
IL_00a0: ldc.i4.0
IL_00a1: ldc.i4.1
IL_00a2: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00a7: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_00ac: brtrue IL_02cf
IL_00b1: ldarg.0
IL_00b2: ldc.i4 0xfb
IL_00b7: ldc.i4.0
IL_00b8: ldc.i4.0
IL_00b9: ldc.i4.0
IL_00ba: ldc.i4.1
IL_00bb: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00c0: call ""bool decimal.op_Equality(decimal, decimal)""
IL_00c5: brtrue IL_02dd
IL_00ca: ldarg.0
IL_00cb: ldc.i4 0x105
IL_00d0: ldc.i4.0
IL_00d1: ldc.i4.0
IL_00d2: ldc.i4.0
IL_00d3: ldc.i4.1
IL_00d4: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00d9: call ""bool decimal.op_Equality(decimal, decimal)""
IL_00de: brtrue IL_0294
IL_00e3: br IL_02eb
IL_00e8: ldarg.0
IL_00e9: ldc.i4 0xa1
IL_00ee: ldc.i4.0
IL_00ef: ldc.i4.0
IL_00f0: ldc.i4.0
IL_00f1: ldc.i4.1
IL_00f2: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00f7: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_00fc: brfalse.s IL_0167
IL_00fe: ldarg.0
IL_00ff: ldc.i4 0xb5
IL_0104: ldc.i4.0
IL_0105: ldc.i4.0
IL_0106: ldc.i4.0
IL_0107: ldc.i4.1
IL_0108: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_010d: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_0112: brtrue IL_02ca
IL_0117: ldarg.0
IL_0118: ldc.i4 0xb5
IL_011d: ldc.i4.0
IL_011e: ldc.i4.0
IL_011f: ldc.i4.0
IL_0120: ldc.i4.1
IL_0121: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0126: call ""bool decimal.op_Equality(decimal, decimal)""
IL_012b: brtrue IL_02d4
IL_0130: ldarg.0
IL_0131: ldc.i4 0xbf
IL_0136: ldc.i4.0
IL_0137: ldc.i4.0
IL_0138: ldc.i4.0
IL_0139: ldc.i4.1
IL_013a: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_013f: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0144: brtrue IL_02aa
IL_0149: ldarg.0
IL_014a: ldc.i4 0xc9
IL_014f: ldc.i4.0
IL_0150: ldc.i4.0
IL_0151: ldc.i4.0
IL_0152: ldc.i4.1
IL_0153: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0158: call ""bool decimal.op_Equality(decimal, decimal)""
IL_015d: brtrue IL_02e2
IL_0162: br IL_02eb
IL_0167: ldarg.0
IL_0168: ldc.i4 0x97
IL_016d: ldc.i4.0
IL_016e: ldc.i4.0
IL_016f: ldc.i4.0
IL_0170: ldc.i4.1
IL_0171: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0176: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_017b: brtrue IL_02b4
IL_0180: ldarg.0
IL_0181: ldc.i4 0x97
IL_0186: ldc.i4.0
IL_0187: ldc.i4.0
IL_0188: ldc.i4.0
IL_0189: ldc.i4.1
IL_018a: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_018f: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0194: brtrue IL_02bd
IL_0199: br IL_02eb
IL_019e: ldarg.0
IL_019f: ldc.i4.s 71
IL_01a1: ldc.i4.0
IL_01a2: ldc.i4.0
IL_01a3: ldc.i4.0
IL_01a4: ldc.i4.1
IL_01a5: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01aa: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_01af: brfalse IL_023c
IL_01b4: ldarg.0
IL_01b5: ldc.i4.s 91
IL_01b7: ldc.i4.0
IL_01b8: ldc.i4.0
IL_01b9: ldc.i4.0
IL_01ba: ldc.i4.1
IL_01bb: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01c0: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_01c5: brtrue IL_02d9
IL_01ca: ldarg.0
IL_01cb: ldc.i4.s 101
IL_01cd: ldc.i4.0
IL_01ce: ldc.i4.0
IL_01cf: ldc.i4.0
IL_01d0: ldc.i4.1
IL_01d1: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01d6: call ""bool decimal.op_LessThanOrEqual(decimal, decimal)""
IL_01db: brfalse.s IL_020e
IL_01dd: ldarg.0
IL_01de: ldc.i4.s 91
IL_01e0: ldc.i4.0
IL_01e1: ldc.i4.0
IL_01e2: ldc.i4.0
IL_01e3: ldc.i4.1
IL_01e4: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01e9: call ""bool decimal.op_Equality(decimal, decimal)""
IL_01ee: brtrue IL_0299
IL_01f3: ldarg.0
IL_01f4: ldc.i4.s 101
IL_01f6: ldc.i4.0
IL_01f7: ldc.i4.0
IL_01f8: ldc.i4.0
IL_01f9: ldc.i4.1
IL_01fa: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01ff: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0204: brtrue IL_02b9
IL_0209: br IL_02eb
IL_020e: ldarg.0
IL_020f: ldc.i4.s 111
IL_0211: ldc.i4.0
IL_0212: ldc.i4.0
IL_0213: ldc.i4.0
IL_0214: ldc.i4.1
IL_0215: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_021a: call ""bool decimal.op_Equality(decimal, decimal)""
IL_021f: brtrue IL_02c2
IL_0224: ldarg.0
IL_0225: ldc.i4.s 121
IL_0227: ldc.i4.0
IL_0228: ldc.i4.0
IL_0229: ldc.i4.0
IL_022a: ldc.i4.1
IL_022b: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0230: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0235: brtrue.s IL_02a1
IL_0237: br IL_02eb
IL_023c: ldarg.0
IL_023d: ldc.i4.s 41
IL_023f: ldc.i4.0
IL_0240: ldc.i4.0
IL_0241: ldc.i4.0
IL_0242: ldc.i4.1
IL_0243: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0248: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_024d: brfalse.s IL_0267
IL_024f: ldarg.0
IL_0250: ldc.i4.s 21
IL_0252: ldc.i4.0
IL_0253: ldc.i4.0
IL_0254: ldc.i4.0
IL_0255: ldc.i4.1
IL_0256: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_025b: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0260: brtrue.s IL_029d
IL_0262: br IL_02eb
IL_0267: ldarg.0
IL_0268: ldc.i4.s 51
IL_026a: ldc.i4.0
IL_026b: ldc.i4.0
IL_026c: ldc.i4.0
IL_026d: ldc.i4.1
IL_026e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0273: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0278: brtrue.s IL_02e7
IL_027a: ldarg.0
IL_027b: ldc.i4.s 41
IL_027d: ldc.i4.0
IL_027e: ldc.i4.0
IL_027f: ldc.i4.0
IL_0280: ldc.i4.1
IL_0281: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0286: call ""bool decimal.op_Equality(decimal, decimal)""
IL_028b: brtrue.s IL_02c6
IL_028d: br.s IL_02eb
IL_028f: ldc.i4.s 19
IL_0291: stloc.0
IL_0292: br.s IL_02ed
IL_0294: ldc.i4.s 18
IL_0296: stloc.0
IL_0297: br.s IL_02ed
IL_0299: ldc.i4.5
IL_029a: stloc.0
IL_029b: br.s IL_02ed
IL_029d: ldc.i4.1
IL_029e: stloc.0
IL_029f: br.s IL_02ed
IL_02a1: ldc.i4.8
IL_02a2: stloc.0
IL_02a3: br.s IL_02ed
IL_02a5: ldc.i4.s 15
IL_02a7: stloc.0
IL_02a8: br.s IL_02ed
IL_02aa: ldc.i4.s 13
IL_02ac: stloc.0
IL_02ad: br.s IL_02ed
IL_02af: ldc.i4.s 20
IL_02b1: stloc.0
IL_02b2: br.s IL_02ed
IL_02b4: ldc.i4.s 9
IL_02b6: stloc.0
IL_02b7: br.s IL_02ed
IL_02b9: ldc.i4.6
IL_02ba: stloc.0
IL_02bb: br.s IL_02ed
IL_02bd: ldc.i4.s 10
IL_02bf: stloc.0
IL_02c0: br.s IL_02ed
IL_02c2: ldc.i4.7
IL_02c3: stloc.0
IL_02c4: br.s IL_02ed
IL_02c6: ldc.i4.2
IL_02c7: stloc.0
IL_02c8: br.s IL_02ed
IL_02ca: ldc.i4.s 11
IL_02cc: stloc.0
IL_02cd: br.s IL_02ed
IL_02cf: ldc.i4.s 16
IL_02d1: stloc.0
IL_02d2: br.s IL_02ed
IL_02d4: ldc.i4.s 12
IL_02d6: stloc.0
IL_02d7: br.s IL_02ed
IL_02d9: ldc.i4.4
IL_02da: stloc.0
IL_02db: br.s IL_02ed
IL_02dd: ldc.i4.s 17
IL_02df: stloc.0
IL_02e0: br.s IL_02ed
IL_02e2: ldc.i4.s 14
IL_02e4: stloc.0
IL_02e5: br.s IL_02ed
IL_02e7: ldc.i4.3
IL_02e8: stloc.0
IL_02e9: br.s IL_02ed
IL_02eb: ldc.i4.0
IL_02ec: stloc.0
IL_02ed: ldloc.0
IL_02ee: ret
}
"
);
}
[Fact]
public void BalancedSwitchDispatch_Uint32()
{
// We do not currently detect that the set of values that we are dispatching on is a compact set,
// which would enable us to use the IL switch instruction even though the input was expressed using
// a set of relational comparisons.
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2U));
Console.WriteLine(M(3U));
Console.WriteLine(M(4U));
Console.WriteLine(M(5U));
Console.WriteLine(M(6U));
Console.WriteLine(M(7U));
Console.WriteLine(M(8U));
Console.WriteLine(M(9U));
Console.WriteLine(M(10U));
Console.WriteLine(M(11U));
Console.WriteLine(M(12U));
Console.WriteLine(M(13U));
Console.WriteLine(M(14U));
Console.WriteLine(M(15U));
Console.WriteLine(M(16U));
Console.WriteLine(M(17U));
Console.WriteLine(M(18U));
Console.WriteLine(M(19U));
Console.WriteLine(M(20U));
Console.WriteLine(M(21U));
Console.WriteLine(M(22U));
Console.WriteLine(M(23U));
Console.WriteLine(M(24U));
Console.WriteLine(M(25U));
Console.WriteLine(M(26U));
Console.WriteLine(M(27U));
Console.WriteLine(M(28U));
Console.WriteLine(M(29U));
}
static int M(uint d)
{
return d switch
{
>= 27U and < 29U => 19,
26U => 18,
9U => 5,
>= 2U and < 4U => 1,
12U => 8,
>= 21U and < 23U => 15,
19U => 13,
29U => 20,
>= 13U and < 15U => 9,
10U => 6,
15U => 10,
11U => 7,
4U => 2,
>= 16U and < 18U => 11,
>= 23U and < 25U => 16,
18U => 12,
>= 7U and < 9U => 4,
25U => 17,
20U => 14,
>= 5U and < 7U => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 243 (0xf3)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 21
IL_0003: blt.un.s IL_0039
IL_0005: ldarg.0
IL_0006: ldc.i4.s 27
IL_0008: blt.un.s IL_001f
IL_000a: ldarg.0
IL_000b: ldc.i4.s 29
IL_000d: blt.un IL_0093
IL_0012: ldarg.0
IL_0013: ldc.i4.s 29
IL_0015: beq IL_00b3
IL_001a: br IL_00ef
IL_001f: ldarg.0
IL_0020: ldc.i4.s 23
IL_0022: blt.un IL_00a9
IL_0027: ldarg.0
IL_0028: ldc.i4.s 25
IL_002a: blt.un IL_00d3
IL_002f: ldarg.0
IL_0030: ldc.i4.s 26
IL_0032: beq.s IL_0098
IL_0034: br IL_00e1
IL_0039: ldarg.0
IL_003a: ldc.i4.s 13
IL_003c: blt.un.s IL_0061
IL_003e: ldarg.0
IL_003f: ldc.i4.s 15
IL_0041: blt.un.s IL_00b8
IL_0043: ldarg.0
IL_0044: ldc.i4.s 18
IL_0046: bge.un.s IL_004f
IL_0048: ldarg.0
IL_0049: ldc.i4.s 15
IL_004b: beq.s IL_00c1
IL_004d: br.s IL_00ce
IL_004f: ldarg.0
IL_0050: ldc.i4.s 18
IL_0052: beq IL_00d8
IL_0057: ldarg.0
IL_0058: ldc.i4.s 19
IL_005a: beq.s IL_00ae
IL_005c: br IL_00e6
IL_0061: ldarg.0
IL_0062: ldc.i4.4
IL_0063: bge.un.s IL_006e
IL_0065: ldarg.0
IL_0066: ldc.i4.2
IL_0067: bge.un.s IL_00a1
IL_0069: br IL_00ef
IL_006e: ldarg.0
IL_006f: ldc.i4.7
IL_0070: blt.un.s IL_008d
IL_0072: ldarg.0
IL_0073: ldc.i4.s 9
IL_0075: sub
IL_0076: switch (
IL_009d,
IL_00bd,
IL_00c6,
IL_00a5)
IL_008b: br.s IL_00dd
IL_008d: ldarg.0
IL_008e: ldc.i4.4
IL_008f: beq.s IL_00ca
IL_0091: br.s IL_00eb
IL_0093: ldc.i4.s 19
IL_0095: stloc.0
IL_0096: br.s IL_00f1
IL_0098: ldc.i4.s 18
IL_009a: stloc.0
IL_009b: br.s IL_00f1
IL_009d: ldc.i4.5
IL_009e: stloc.0
IL_009f: br.s IL_00f1
IL_00a1: ldc.i4.1
IL_00a2: stloc.0
IL_00a3: br.s IL_00f1
IL_00a5: ldc.i4.8
IL_00a6: stloc.0
IL_00a7: br.s IL_00f1
IL_00a9: ldc.i4.s 15
IL_00ab: stloc.0
IL_00ac: br.s IL_00f1
IL_00ae: ldc.i4.s 13
IL_00b0: stloc.0
IL_00b1: br.s IL_00f1
IL_00b3: ldc.i4.s 20
IL_00b5: stloc.0
IL_00b6: br.s IL_00f1
IL_00b8: ldc.i4.s 9
IL_00ba: stloc.0
IL_00bb: br.s IL_00f1
IL_00bd: ldc.i4.6
IL_00be: stloc.0
IL_00bf: br.s IL_00f1
IL_00c1: ldc.i4.s 10
IL_00c3: stloc.0
IL_00c4: br.s IL_00f1
IL_00c6: ldc.i4.7
IL_00c7: stloc.0
IL_00c8: br.s IL_00f1
IL_00ca: ldc.i4.2
IL_00cb: stloc.0
IL_00cc: br.s IL_00f1
IL_00ce: ldc.i4.s 11
IL_00d0: stloc.0
IL_00d1: br.s IL_00f1
IL_00d3: ldc.i4.s 16
IL_00d5: stloc.0
IL_00d6: br.s IL_00f1
IL_00d8: ldc.i4.s 12
IL_00da: stloc.0
IL_00db: br.s IL_00f1
IL_00dd: ldc.i4.4
IL_00de: stloc.0
IL_00df: br.s IL_00f1
IL_00e1: ldc.i4.s 17
IL_00e3: stloc.0
IL_00e4: br.s IL_00f1
IL_00e6: ldc.i4.s 14
IL_00e8: stloc.0
IL_00e9: br.s IL_00f1
IL_00eb: ldc.i4.3
IL_00ec: stloc.0
IL_00ed: br.s IL_00f1
IL_00ef: ldc.i4.0
IL_00f0: stloc.0
IL_00f1: ldloc.0
IL_00f2: ret
}
"
);
}
#endregion Code Quality tests
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class SwitchTests : EmitMetadataTestBase
{
#region Functionality tests
[Fact]
public void DefaultOnlySwitch()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
switch (true) {
default:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: dup
IL_0002: call ""void System.Console.Write(int)""
IL_0007: ret
}");
}
[WorkItem(542298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542298")]
[Fact]
public void DefaultOnlySwitch_02()
{
string text = @"using System;
public class Test
{
public static void Main()
{
int status = 2;
switch (status)
{
default: status--; break;
}
string str = ""string"";
switch (str)
{
default: status--; break;
}
Console.WriteLine(status);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main",
@"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldc.i4.2
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: call ""void System.Console.WriteLine(int)""
IL_000a: ret
}"
);
}
[Fact]
public void ConstantIntegerSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
switch (true) {
case true:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: dup
IL_0002: call ""void System.Console.Write(int)""
IL_0007: ret
}"
);
}
[Fact]
public void ConstantNullSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
const string s = null;
switch (s)
{
case null:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: dup
IL_0002: call ""void System.Console.Write(int)""
IL_0007: ret
}"
);
}
[Fact]
public void NonConstantSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
int value = 1;
switch (value) {
case 2:
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: ldc.i4.2
IL_0004: bne.un.s IL_0008
IL_0006: ldc.i4.1
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: call ""void System.Console.Write(int)""
IL_000e: ldloc.0
IL_000f: ret
}"
);
}
[Fact]
public void ConstantVariableInCaseLabel()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
int value = 23;
switch (value) {
case kValue:
ret = 0;
break;
default:
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
const int kValue = 23;
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.s 23
IL_0004: ldc.i4.s 23
IL_0006: bne.un.s IL_000c
IL_0008: ldc.i4.0
IL_0009: stloc.0
IL_000a: br.s IL_000e
IL_000c: ldc.i4.1
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: call ""void System.Console.Write(int)""
IL_0014: ldloc.0
IL_0015: ret
}"
);
}
[Fact]
public void DefaultExpressionInLabel()
{
var source = @"
class C
{
static void Main()
{
switch (0)
{
case default(int): return;
}
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void SwitchWith_NoMatchingCaseLabel_And_NoDefaultLabel()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 5;
switch (i)
{
case 1:
case 2:
case 3:
return 1;
case 1001:
case 1002:
case 1003:
return 2;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.5
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: ldc.i4.2
IL_0006: ble.un.s IL_0014
IL_0008: ldloc.0
IL_0009: ldc.i4 0x3e9
IL_000e: sub
IL_000f: ldc.i4.2
IL_0010: ble.un.s IL_0016
IL_0012: br.s IL_0018
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.2
IL_0017: ret
IL_0018: ldc.i4.0
IL_0019: ret
}"
);
}
[Fact]
public void DegenerateSwitch001()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(100);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return 1;
case 100:
goto case 3;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.6
IL_0002: ble.un.s IL_0009
IL_0004: ldarg.0
IL_0005: ldc.i4.s 100
IL_0007: bne.un.s IL_000b
IL_0009: ldc.i4.1
IL_000a: ret
IL_000b: ldc.i4.0
IL_000c: ret
}"
);
}
[Fact]
public void DegenerateSwitch001_Debug()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(100);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return 1;
case 100:
goto case 3;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1", options: TestOptions.DebugExe);
compVerifier.VerifyIL("Test.M", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (int V_0,
int V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: ldc.i4.6
IL_0007: ble.un.s IL_0012
IL_0009: br.s IL_000b
IL_000b: ldloc.0
IL_000c: ldc.i4.s 100
IL_000e: beq.s IL_0016
IL_0010: br.s IL_0018
IL_0012: ldc.i4.1
IL_0013: stloc.2
IL_0014: br.s IL_001c
IL_0016: br.s IL_0012
IL_0018: ldc.i4.0
IL_0019: stloc.2
IL_001a: br.s IL_001c
IL_001c: ldloc.2
IL_001d: ret
}"
);
}
[Fact]
public void DegenerateSwitch002()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(5);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 1:
case 5:
case 6:
case 3:
case 4:
case 2:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ldc.i4.5
IL_0004: bgt.un.s IL_0008
IL_0006: ldc.i4.1
IL_0007: ret
IL_0008: ldc.i4.0
IL_0009: ret
}
"
);
}
[Fact]
public void DegenerateSwitch003()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(4);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case -2:
case -1:
case 0:
case 2:
case 1:
case 4:
case 3:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s -2
IL_0003: sub
IL_0004: ldc.i4.6
IL_0005: bgt.un.s IL_0009
IL_0007: ldc.i4.1
IL_0008: ret
IL_0009: ldc.i4.0
IL_000a: ret
}"
);
}
[Fact]
public void DegenerateSwitch004()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(int.MaxValue - 1);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case int.MinValue + 1:
case int.MinValue:
case int.MaxValue:
case int.MaxValue - 1:
case int.MaxValue - 2:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x80000000
IL_0006: sub
IL_0007: ldc.i4.1
IL_0008: ble.un.s IL_0014
IL_000a: ldarg.0
IL_000b: ldc.i4 0x7ffffffd
IL_0010: sub
IL_0011: ldc.i4.2
IL_0012: bgt.un.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}"
);
}
[Fact]
public void DegenerateSwitch005()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(int.MaxValue + 1L);
Console.Write(ret);
return(ret);
}
public static int M(long i)
{
switch (i)
{
case int.MaxValue:
case int.MaxValue + 1L:
case int.MaxValue + 2L:
case int.MaxValue + 3L:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x7fffffff
IL_0006: conv.i8
IL_0007: sub
IL_0008: ldc.i4.3
IL_0009: conv.i8
IL_000a: bgt.un.s IL_000e
IL_000c: ldc.i4.1
IL_000d: ret
IL_000e: ldc.i4.0
IL_000f: ret
}"
);
}
[Fact]
public void DegenerateSwitch006()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(35);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 1:
case 5:
case 6:
case 3:
case 4:
case 2:
return 1;
case 31:
case 35:
case 36:
case 33:
case 34:
case 32:
return 4;
case 41:
case 45:
case 46:
case 43:
case 44:
case 42:
return 5;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "4");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 30 (0x1e)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ldc.i4.5
IL_0004: ble.un.s IL_0016
IL_0006: ldarg.0
IL_0007: ldc.i4.s 31
IL_0009: sub
IL_000a: ldc.i4.5
IL_000b: ble.un.s IL_0018
IL_000d: ldarg.0
IL_000e: ldc.i4.s 41
IL_0010: sub
IL_0011: ldc.i4.5
IL_0012: ble.un.s IL_001a
IL_0014: br.s IL_001c
IL_0016: ldc.i4.1
IL_0017: ret
IL_0018: ldc.i4.4
IL_0019: ret
IL_001a: ldc.i4.5
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}"
);
}
[Fact]
public void NotDegenerateSwitch006()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(35);
Console.Write(ret);
return(ret);
}
public static int M(int i)
{
switch (i)
{
case 1:
case 5:
case 6:
case 3:
case 4:
case 2:
return 1;
case 11:
case 15:
case 16:
case 13:
case 14:
case 12:
return 2;
case 21:
case 25:
case 26:
case 23:
case 24:
case 22:
return 3;
case 31:
case 35:
case 36:
case 33:
case 34:
case 32:
return 4;
case 41:
case 45:
case 46:
case 43:
case 44:
case 42:
return 5;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "4");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 206 (0xce)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: switch (
IL_00c2,
IL_00c2,
IL_00c2,
IL_00c2,
IL_00c2,
IL_00c2,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00c4,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00c6,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00c8,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00cc,
IL_00ca,
IL_00ca,
IL_00ca,
IL_00ca,
IL_00ca,
IL_00ca)
IL_00c0: br.s IL_00cc
IL_00c2: ldc.i4.1
IL_00c3: ret
IL_00c4: ldc.i4.2
IL_00c5: ret
IL_00c6: ldc.i4.3
IL_00c7: ret
IL_00c8: ldc.i4.4
IL_00c9: ret
IL_00ca: ldc.i4.5
IL_00cb: ret
IL_00cc: ldc.i4.0
IL_00cd: ret
}");
}
[Fact]
public void DegenerateSwitch007()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(5);
Console.Write(ret);
return(ret);
}
public static int M(int? i)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
return 1;
default:
return 0;
case null:
return 2;
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0019
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldc.i4.6
IL_0013: bgt.un.s IL_0017
IL_0015: ldc.i4.1
IL_0016: ret
IL_0017: ldc.i4.0
IL_0018: ret
IL_0019: ldc.i4.2
IL_001a: ret
}"
);
}
[Fact]
public void DegenerateSwitch008()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M((uint)int.MaxValue + (uint)1);
Console.Write(ret);
return(ret);
}
public static int M(uint i)
{
switch (i)
{
case (uint)int.MaxValue:
case (uint)int.MaxValue + (uint)1:
case (uint)int.MaxValue + (uint)2:
case (uint)int.MaxValue + (uint)3:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x7fffffff
IL_0006: sub
IL_0007: ldc.i4.3
IL_0008: bgt.un.s IL_000c
IL_000a: ldc.i4.1
IL_000b: ret
IL_000c: ldc.i4.0
IL_000d: ret
}"
);
}
[Fact]
public void DegenerateSwitch009()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M(uint.MaxValue);
Console.Write(ret);
return(ret);
}
public static int M(uint i)
{
switch (i)
{
case 0:
case 1:
case uint.MaxValue:
case uint.MaxValue - 1:
case uint.MaxValue - 2:
case uint.MaxValue - 3:
return 1;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: ble.un.s IL_000b
IL_0004: ldarg.0
IL_0005: ldc.i4.s -4
IL_0007: sub
IL_0008: ldc.i4.3
IL_0009: bgt.un.s IL_000d
IL_000b: ldc.i4.1
IL_000c: ret
IL_000d: ldc.i4.0
IL_000e: ret
}"
);
}
[Fact]
public void ByteTypeSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
ret = DoByte();
return(ret);
}
private static int DoByte()
{
int ret = 2;
byte b = 2;
switch (b) {
case 1:
case 2:
ret--;
break;
case 3:
break;
default:
break;
}
switch (b) {
case 1:
case 3:
break;
default:
ret--;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.DoByte",
@"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (int V_0, //ret
byte V_1) //b
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldc.i4.1
IL_0006: sub
IL_0007: ldc.i4.1
IL_0008: ble.un.s IL_0010
IL_000a: ldloc.1
IL_000b: ldc.i4.3
IL_000c: beq.s IL_0014
IL_000e: br.s IL_0014
IL_0010: ldloc.0
IL_0011: ldc.i4.1
IL_0012: sub
IL_0013: stloc.0
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: beq.s IL_0020
IL_0018: ldloc.1
IL_0019: ldc.i4.3
IL_001a: beq.s IL_0020
IL_001c: ldloc.0
IL_001d: ldc.i4.1
IL_001e: sub
IL_001f: stloc.0
IL_0020: ldloc.0
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ldloc.0
IL_0027: ret
}"
);
}
[Fact]
public void LongTypeSwitchArgumentExpression()
{
var text = @"
using System;
public class Test
{
public static void Main(string [] args)
{
int ret = 0;
ret = DoLong(2);
Console.Write(ret);
ret = DoLong(4);
Console.Write(ret);
ret = DoLong(42);
Console.Write(ret);
}
private static int DoLong(long b)
{
int ret = 2;
switch (b) {
case 1:
ret++;
break;
case 2:
ret--;
break;
case 3:
break;
case 4:
ret += 7;
break;
default:
ret+=2;
break;
}
return ret;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "194");
compVerifier.VerifyIL("Test.DoLong",
@"
{
// Code size 62 (0x3e)
.maxstack 3
.locals init (int V_0) //ret
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldc.i4.1
IL_0004: conv.i8
IL_0005: sub
IL_0006: dup
IL_0007: ldc.i4.3
IL_0008: conv.i8
IL_0009: ble.un.s IL_000e
IL_000b: pop
IL_000c: br.s IL_0038
IL_000e: conv.u4
IL_000f: switch (
IL_0026,
IL_002c,
IL_003c,
IL_0032)
IL_0024: br.s IL_0038
IL_0026: ldloc.0
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stloc.0
IL_002a: br.s IL_003c
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: sub
IL_002f: stloc.0
IL_0030: br.s IL_003c
IL_0032: ldloc.0
IL_0033: ldc.i4.7
IL_0034: add
IL_0035: stloc.0
IL_0036: br.s IL_003c
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: add
IL_003b: stloc.0
IL_003c: ldloc.0
IL_003d: ret
}"
);
}
[WorkItem(740058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740058")]
[Fact]
public void LongTypeSwitchArgumentExpressionOverflow()
{
var text = @"
using System;
public class Test
{
public static void Main(string[] args)
{
string ret;
ret = DoLong(long.MaxValue);
Console.Write(ret);
ret = DoLong(long.MinValue);
Console.Write(ret);
ret = DoLong(1L);
Console.Write(ret);
ret = DoLong(0L);
Console.Write(ret);
}
private static string DoLong(long b)
{
switch (b)
{
case long.MaxValue:
return ""max"";
case 1L:
return ""one"";
case long.MinValue:
return ""min"";
default:
return ""default"";
}
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "maxminonedefault");
compVerifier.VerifyIL("Test.DoLong",
@"
{
// Code size 53 (0x35)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i8 0x8000000000000000
IL_000a: beq.s IL_0029
IL_000c: ldarg.0
IL_000d: ldc.i4.1
IL_000e: conv.i8
IL_000f: beq.s IL_0023
IL_0011: ldarg.0
IL_0012: ldc.i8 0x7fffffffffffffff
IL_001b: bne.un.s IL_002f
IL_001d: ldstr ""max""
IL_0022: ret
IL_0023: ldstr ""one""
IL_0028: ret
IL_0029: ldstr ""min""
IL_002e: ret
IL_002f: ldstr ""default""
IL_0034: ret
}"
);
}
[Fact]
public void ULongTypeSwitchArgumentExpression()
{
var text = @"
using System;
public class Test
{
public static void Main(string[] args)
{
int ret = 0;
ret = DoULong(0x1000000000000001L);
Console.Write(ret);
}
private static int DoULong(ulong b)
{
int ret = 2;
switch (b)
{
case 0:
ret++;
break;
case 1:
ret--;
break;
case 2:
break;
case 3:
ret += 7;
break;
default:
ret += 40;
break;
}
return ret;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "42");
compVerifier.VerifyIL("Test.DoULong",
@"
{
// Code size 60 (0x3c)
.maxstack 3
.locals init (int V_0) //ret
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: dup
IL_0004: ldc.i4.3
IL_0005: conv.i8
IL_0006: ble.un.s IL_000b
IL_0008: pop
IL_0009: br.s IL_0035
IL_000b: conv.u4
IL_000c: switch (
IL_0023,
IL_0029,
IL_003a,
IL_002f)
IL_0021: br.s IL_0035
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.0
IL_0027: br.s IL_003a
IL_0029: ldloc.0
IL_002a: ldc.i4.1
IL_002b: sub
IL_002c: stloc.0
IL_002d: br.s IL_003a
IL_002f: ldloc.0
IL_0030: ldc.i4.7
IL_0031: add
IL_0032: stloc.0
IL_0033: br.s IL_003a
IL_0035: ldloc.0
IL_0036: ldc.i4.s 40
IL_0038: add
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ret
}"
);
}
[Fact]
public void EnumTypeSwitchArgumentExpressionWithCasts()
{
var text = @"using System;
public class Test
{
enum eTypes {
kFirst,
kSecond,
kThird,
};
public static int Main(string [] args)
{
int ret = 0;
ret = DoEnum();
return(ret);
}
private static int DoEnum()
{
int ret = 2;
eTypes e = eTypes.kSecond;
switch (e) {
case eTypes.kThird:
case eTypes.kSecond:
ret--;
break;
case (eTypes) (-1):
break;
default:
break;
}
switch (e) {
case (eTypes)100:
case (eTypes) (-1):
break;
default:
ret--;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.DoEnum",
@"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (int V_0, //ret
Test.eTypes V_1) //e
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldc.i4.m1
IL_0006: beq.s IL_0012
IL_0008: ldloc.1
IL_0009: ldc.i4.1
IL_000a: sub
IL_000b: ldc.i4.1
IL_000c: bgt.un.s IL_0012
IL_000e: ldloc.0
IL_000f: ldc.i4.1
IL_0010: sub
IL_0011: stloc.0
IL_0012: ldloc.1
IL_0013: ldc.i4.m1
IL_0014: beq.s IL_001f
IL_0016: ldloc.1
IL_0017: ldc.i4.s 100
IL_0019: beq.s IL_001f
IL_001b: ldloc.0
IL_001c: ldc.i4.1
IL_001d: sub
IL_001e: stloc.0
IL_001f: ldloc.0
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ldloc.0
IL_0026: ret
}"
);
}
[Fact]
public void NullableEnumTypeSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
enum eTypes {
kFirst,
kSecond,
kThird,
};
public static int Main(string [] args)
{
int ret = 0;
ret = DoEnum();
return(ret);
}
private static int DoEnum()
{
int ret = 3;
eTypes? e = eTypes.kSecond;
switch (e)
{
case eTypes.kThird:
case eTypes.kSecond:
ret--;
break;
default:
break;
}
switch (e)
{
case null:
case (eTypes) (-1):
break;
default:
ret--;
break;
}
e = null;
switch (e)
{
case null:
ret--;
break;
case (eTypes) (-1):
case eTypes.kThird:
case eTypes.kSecond:
default:
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.DoEnum", @"
{
// Code size 109 (0x6d)
.maxstack 2
.locals init (int V_0, //ret
Test.eTypes? V_1, //e
Test.eTypes V_2)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.1
IL_0005: call ""Test.eTypes?..ctor(Test.eTypes)""
IL_000a: ldloca.s V_1
IL_000c: call ""bool Test.eTypes?.HasValue.get""
IL_0011: brfalse.s IL_0025
IL_0013: ldloca.s V_1
IL_0015: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()""
IL_001a: stloc.2
IL_001b: ldloc.2
IL_001c: ldc.i4.1
IL_001d: sub
IL_001e: ldc.i4.1
IL_001f: bgt.un.s IL_0025
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: sub
IL_0024: stloc.0
IL_0025: ldloca.s V_1
IL_0027: call ""bool Test.eTypes?.HasValue.get""
IL_002c: brfalse.s IL_003c
IL_002e: ldloca.s V_1
IL_0030: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()""
IL_0035: ldc.i4.m1
IL_0036: beq.s IL_003c
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: sub
IL_003b: stloc.0
IL_003c: ldloca.s V_1
IL_003e: initobj ""Test.eTypes?""
IL_0044: ldloca.s V_1
IL_0046: call ""bool Test.eTypes?.HasValue.get""
IL_004b: brfalse.s IL_0061
IL_004d: ldloca.s V_1
IL_004f: call ""Test.eTypes Test.eTypes?.GetValueOrDefault()""
IL_0054: stloc.2
IL_0055: ldloc.2
IL_0056: ldc.i4.m1
IL_0057: beq.s IL_0065
IL_0059: ldloc.2
IL_005a: ldc.i4.1
IL_005b: sub
IL_005c: ldc.i4.1
IL_005d: ble.un.s IL_0065
IL_005f: br.s IL_0065
IL_0061: ldloc.0
IL_0062: ldc.i4.1
IL_0063: sub
IL_0064: stloc.0
IL_0065: ldloc.0
IL_0066: call ""void System.Console.Write(int)""
IL_006b: ldloc.0
IL_006c: ret
}");
}
[Fact]
public void SwitchSectionWithGotoNonSwitchLabel()
{
var text = @"
class Test
{
public static int Main()
{
int ret = 1;
switch (10)
{
case 123: // No unreachable code warning here
mylabel:
--ret;
break;
case 9: // No unreachable code warning here
case 10:
case 11: // No unreachable code warning here
goto mylabel;
}
System.Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics();
compVerifier.VerifyIL("Test.Main",
@"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""void System.Console.Write(int)""
IL_000c: ldloc.0
IL_000d: ret
}"
);
}
[Fact]
public void SwitchSectionWithGotoNonSwitchLabel_02()
{
var text = @"class Test
{
delegate void D();
public static void Main()
{
int i = 0;
switch (10)
{
case 5:
goto mylabel;
case 10:
goto case 5;
case 15:
mylabel:
D d1 = delegate() { System.Console.Write(i); };
d1();
return;
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (Test.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Test.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.0
IL_0008: stfld ""int Test.<>c__DisplayClass1_0.i""
IL_000d: ldloc.0
IL_000e: ldftn ""void Test.<>c__DisplayClass1_0.<Main>b__0()""
IL_0014: newobj ""Test.D..ctor(object, System.IntPtr)""
IL_0019: callvirt ""void Test.D.Invoke()""
IL_001e: ret
}
"
);
}
[Fact]
public void SwitchSectionWithReturnStatement()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 3;
for (int i = 0; i < 3; i++) {
switch (i) {
case 1:
case 0:
case 2:
ret--;
break;
default:
Console.Write(1);
return(1);
}
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (int V_0, //ret
int V_1) //i
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_001c
IL_0006: ldloc.1
IL_0007: ldc.i4.2
IL_0008: bgt.un.s IL_0010
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: sub
IL_000d: stloc.0
IL_000e: br.s IL_0018
IL_0010: ldc.i4.1
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.1
IL_0017: ret
IL_0018: ldloc.1
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.3
IL_001e: blt.s IL_0006
IL_0020: ldloc.0
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ldloc.0
IL_0027: ret
}"
);
}
[Fact]
public void SwitchSectionWithReturnStatement_02()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 5;
switch (i)
{
case 1:
return 1;
}
return 0;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.5
IL_0001: ldc.i4.1
IL_0002: bne.un.s IL_0006
IL_0004: ldc.i4.1
IL_0005: ret
IL_0006: ldc.i4.0
IL_0007: ret
}"
);
}
[Fact]
public void CaseLabelWithTypeCastToGoverningType()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 5;
switch (i)
{
case (int) 5.0f:
return 0;
default:
return 1;
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldc.i4.5
IL_0001: ldc.i4.5
IL_0002: bne.un.s IL_0006
IL_0004: ldc.i4.0
IL_0005: ret
IL_0006: ldc.i4.1
IL_0007: ret
}"
);
}
[Fact]
public void SwitchSectionWithTryFinally()
{
var text = @"using System;
class Class1
{
static int Main()
{
int j = 0;
int i = 3;
switch (j)
{
case 0:
try
{
i = 0;
}
catch
{
i = 1;
}
finally
{
j = 2;
}
break;
default:
i = 2;
break;
}
Console.Write(i);
return i;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Class1.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.0
IL_0001: ldc.i4.3
IL_0002: stloc.0
IL_0003: brtrue.s IL_0010
IL_0005: nop
.try
{
.try
{
IL_0006: ldc.i4.0
IL_0007: stloc.0
IL_0008: leave.s IL_0012
}
catch object
{
IL_000a: pop
IL_000b: ldc.i4.1
IL_000c: stloc.0
IL_000d: leave.s IL_0012
}
}
finally
{
IL_000f: endfinally
}
IL_0010: ldc.i4.2
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: call ""void System.Console.Write(int)""
IL_0018: ldloc.0
IL_0019: ret
}"
);
}
[Fact]
public void MultipleSwitchSectionsWithGotoCase()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int ret = 6;
switch (ret) {
case 0:
ret--; // 2
Console.Write(""case 0: "");
Console.WriteLine(ret);
goto case 9999;
case 2:
ret--; // 4
Console.Write(""case 2: "");
Console.WriteLine(ret);
goto case 255;
case 6: // start here
ret--; // 5
Console.Write(""case 5: "");
Console.WriteLine(ret);
goto case 2;
case 9999:
ret--; // 1
Console.Write(""case 9999: "");
Console.WriteLine(ret);
goto default;
case 0xff:
ret--; // 3
Console.Write(""case 0xff: "");
Console.WriteLine(ret);
goto case 0;
default:
ret--;
Console.Write(""Default: "");
Console.WriteLine(ret);
if (ret > 0) {
goto case -1;
}
break;
case -1:
ret = 999;
Console.WriteLine(""case -1: "");
Console.Write(ret);
break;
}
return(ret);
}
}";
string expectedOutput = @"case 5: 5
case 2: 4
case 0xff: 3
case 0: 2
case 9999: 1
Default: 0
0";
var compVerifier = CompileAndVerify(text, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Test.M",
@"
{
// Code size 215 (0xd7)
.maxstack 2
.locals init (int V_0) //ret
IL_0000: ldc.i4.6
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.6
IL_0004: bgt.s IL_0027
IL_0006: ldloc.0
IL_0007: ldc.i4.m1
IL_0008: sub
IL_0009: switch (
IL_00bf,
IL_0039,
IL_00a7,
IL_004f)
IL_001e: ldloc.0
IL_001f: ldc.i4.6
IL_0020: beq.s IL_0065
IL_0022: br IL_00a7
IL_0027: ldloc.0
IL_0028: ldc.i4 0xff
IL_002d: beq.s IL_0091
IL_002f: ldloc.0
IL_0030: ldc.i4 0x270f
IL_0035: beq.s IL_007b
IL_0037: br.s IL_00a7
IL_0039: ldloc.0
IL_003a: ldc.i4.1
IL_003b: sub
IL_003c: stloc.0
IL_003d: ldstr ""case 0: ""
IL_0042: call ""void System.Console.Write(string)""
IL_0047: ldloc.0
IL_0048: call ""void System.Console.WriteLine(int)""
IL_004d: br.s IL_007b
IL_004f: ldloc.0
IL_0050: ldc.i4.1
IL_0051: sub
IL_0052: stloc.0
IL_0053: ldstr ""case 2: ""
IL_0058: call ""void System.Console.Write(string)""
IL_005d: ldloc.0
IL_005e: call ""void System.Console.WriteLine(int)""
IL_0063: br.s IL_0091
IL_0065: ldloc.0
IL_0066: ldc.i4.1
IL_0067: sub
IL_0068: stloc.0
IL_0069: ldstr ""case 5: ""
IL_006e: call ""void System.Console.Write(string)""
IL_0073: ldloc.0
IL_0074: call ""void System.Console.WriteLine(int)""
IL_0079: br.s IL_004f
IL_007b: ldloc.0
IL_007c: ldc.i4.1
IL_007d: sub
IL_007e: stloc.0
IL_007f: ldstr ""case 9999: ""
IL_0084: call ""void System.Console.Write(string)""
IL_0089: ldloc.0
IL_008a: call ""void System.Console.WriteLine(int)""
IL_008f: br.s IL_00a7
IL_0091: ldloc.0
IL_0092: ldc.i4.1
IL_0093: sub
IL_0094: stloc.0
IL_0095: ldstr ""case 0xff: ""
IL_009a: call ""void System.Console.Write(string)""
IL_009f: ldloc.0
IL_00a0: call ""void System.Console.WriteLine(int)""
IL_00a5: br.s IL_0039
IL_00a7: ldloc.0
IL_00a8: ldc.i4.1
IL_00a9: sub
IL_00aa: stloc.0
IL_00ab: ldstr ""Default: ""
IL_00b0: call ""void System.Console.Write(string)""
IL_00b5: ldloc.0
IL_00b6: call ""void System.Console.WriteLine(int)""
IL_00bb: ldloc.0
IL_00bc: ldc.i4.0
IL_00bd: ble.s IL_00d5
IL_00bf: ldc.i4 0x3e7
IL_00c4: stloc.0
IL_00c5: ldstr ""case -1: ""
IL_00ca: call ""void System.Console.WriteLine(string)""
IL_00cf: ldloc.0
IL_00d0: call ""void System.Console.Write(int)""
IL_00d5: ldloc.0
IL_00d6: ret
}"
);
}
[Fact]
public void Switch_TestSwitchBuckets_01()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 0;
// Expected switch buckets: (10, 12, 14) (1000) (2000, 2001, 2005, 2008, 2009, 2010)
switch (i)
{
case 10:
case 2000:
case 12:
return 1;
case 2001:
case 14:
return 2;
case 1000:
case 2010:
case 2008:
return 3;
case 2005:
case 2009:
return 2;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 107 (0x6b)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.s 10
IL_0005: sub
IL_0006: switch (
IL_0061,
IL_0069,
IL_0061,
IL_0069,
IL_0063)
IL_001f: ldloc.0
IL_0020: ldc.i4 0x3e8
IL_0025: beq.s IL_0065
IL_0027: ldloc.0
IL_0028: ldc.i4 0x7d0
IL_002d: sub
IL_002e: switch (
IL_0061,
IL_0063,
IL_0069,
IL_0069,
IL_0069,
IL_0067,
IL_0069,
IL_0069,
IL_0065,
IL_0067,
IL_0065)
IL_005f: br.s IL_0069
IL_0061: ldc.i4.1
IL_0062: ret
IL_0063: ldc.i4.2
IL_0064: ret
IL_0065: ldc.i4.3
IL_0066: ret
IL_0067: ldc.i4.2
IL_0068: ret
IL_0069: ldc.i4.0
IL_006a: ret
}"
);
}
[Fact]
public void Switch_TestSwitchBuckets_02()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
int i = 0;
// Expected switch buckets: (10, 12, 14) (1000) (2000, 2001) (2008, 2009, 2010)
switch (i)
{
case 10:
case 2000:
case 12:
return 1;
case 2001:
case 14:
return 2;
case 1000:
case 2010:
case 2008:
return 3;
case 2009:
return 2;
}
return 0;
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 101 (0x65)
.maxstack 2
.locals init (int V_0) //i
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4 0x3e8
IL_0008: bgt.s IL_0031
IL_000a: ldloc.0
IL_000b: ldc.i4.s 10
IL_000d: sub
IL_000e: switch (
IL_005b,
IL_0063,
IL_005b,
IL_0063,
IL_005d)
IL_0027: ldloc.0
IL_0028: ldc.i4 0x3e8
IL_002d: beq.s IL_005f
IL_002f: br.s IL_0063
IL_0031: ldloc.0
IL_0032: ldc.i4 0x7d0
IL_0037: beq.s IL_005b
IL_0039: ldloc.0
IL_003a: ldc.i4 0x7d1
IL_003f: beq.s IL_005d
IL_0041: ldloc.0
IL_0042: ldc.i4 0x7d8
IL_0047: sub
IL_0048: switch (
IL_005f,
IL_0061,
IL_005f)
IL_0059: br.s IL_0063
IL_005b: ldc.i4.1
IL_005c: ret
IL_005d: ldc.i4.2
IL_005e: ret
IL_005f: ldc.i4.3
IL_0060: ret
IL_0061: ldc.i4.2
IL_0062: ret
IL_0063: ldc.i4.0
IL_0064: ret
}"
);
}
[WorkItem(542398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542398")]
[Fact]
public void MaxValueGotoCaseExpression()
{
var text = @"
class Program
{
static void Main(string[] args)
{
ulong a = 0;
switch (a)
{
case long.MaxValue:
goto case ulong.MaxValue;
case ulong.MaxValue:
break;
}
}
}
";
CompileAndVerify(text, expectedOutput: "");
}
[WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")]
[Fact()]
public void NullableAsSwitchExpression()
{
var text = @"using System;
class Program
{
static void Main()
{
sbyte? local = null;
switch (local)
{
case null:
Console.Write(""null "");
break;
case 1:
Console.Write(""1 "");
break;
}
Goo(1);
}
static void Goo(sbyte? p)
{
switch (p)
{
case 1:
Console.Write(""1 "");
break;
case null:
Console.Write(""null "");
break;
}
}
}
";
var verifier = CompileAndVerify(text, expectedOutput: "null 1");
verifier.VerifyIL("Program.Main", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (sbyte? V_0) //local
IL_0000: ldloca.s V_0
IL_0002: initobj ""sbyte?""
IL_0008: ldloca.s V_0
IL_000a: call ""bool sbyte?.HasValue.get""
IL_000f: brfalse.s IL_001d
IL_0011: ldloca.s V_0
IL_0013: call ""sbyte sbyte?.GetValueOrDefault()""
IL_0018: ldc.i4.1
IL_0019: beq.s IL_0029
IL_001b: br.s IL_0033
IL_001d: ldstr ""null ""
IL_0022: call ""void System.Console.Write(string)""
IL_0027: br.s IL_0033
IL_0029: ldstr ""1 ""
IL_002e: call ""void System.Console.Write(string)""
IL_0033: ldc.i4.1
IL_0034: conv.i1
IL_0035: newobj ""sbyte?..ctor(sbyte)""
IL_003a: call ""void Program.Goo(sbyte?)""
IL_003f: ret
}");
}
[WorkItem(543967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543967")]
[Fact()]
public void NullableAsSwitchExpression_02()
{
var text = @"using System;
class Program
{
static void Main()
{
Goo(null);
Goo(100);
}
static void Goo(short? p)
{
switch (p)
{
case null:
Console.Write(""null "");
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 100:
Console.Write(""100 "");
break;
case 101:
break;
case 103:
break;
case 1001:
break;
case 1002:
break;
case 1003:
break;
}
switch (p)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 101:
break;
case 103:
break;
case 1001:
break;
case 1002:
break;
case 1003:
break;
default:
Console.Write(""default "");
break;
}
switch (p)
{
case 1:
Console.Write(""FAIL"");
break;
case 2:
Console.Write(""FAIL"");
break;
case 3:
Console.Write(""FAIL"");
break;
case 101:
Console.Write(""FAIL"");
break;
case 103:
Console.Write(""FAIL"");
break;
case 1001:
Console.Write(""FAIL"");
break;
case 1002:
Console.Write(""FAIL"");
break;
case 1003:
Console.Write(""FAIL"");
break;
}
}
}
";
var verifier = CompileAndVerify(text, expectedOutput: "null default 100 default ");
verifier.VerifyIL("Program.Goo", @"
{
// Code size 367 (0x16f)
.maxstack 2
.locals init (short V_0)
IL_0000: ldarga.s V_0
IL_0002: call ""bool short?.HasValue.get""
IL_0007: brfalse.s IL_0058
IL_0009: ldarga.s V_0
IL_000b: call ""short short?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldc.i4.1
IL_0013: sub
IL_0014: switch (
IL_006e,
IL_006e,
IL_006e)
IL_0025: ldloc.0
IL_0026: ldc.i4.s 100
IL_0028: sub
IL_0029: switch (
IL_0064,
IL_006e,
IL_006e,
IL_006e)
IL_003e: ldloc.0
IL_003f: ldc.i4 0x3e9
IL_0044: sub
IL_0045: switch (
IL_006e,
IL_006e,
IL_006e)
IL_0056: br.s IL_006e
IL_0058: ldstr ""null ""
IL_005d: call ""void System.Console.Write(string)""
IL_0062: br.s IL_006e
IL_0064: ldstr ""100 ""
IL_0069: call ""void System.Console.Write(string)""
IL_006e: ldarga.s V_0
IL_0070: call ""bool short?.HasValue.get""
IL_0075: brfalse.s IL_00bc
IL_0077: ldarga.s V_0
IL_0079: call ""short short?.GetValueOrDefault()""
IL_007e: stloc.0
IL_007f: ldloc.0
IL_0080: ldc.i4.s 101
IL_0082: bgt.s IL_009f
IL_0084: ldloc.0
IL_0085: ldc.i4.1
IL_0086: sub
IL_0087: switch (
IL_00c6,
IL_00c6,
IL_00c6)
IL_0098: ldloc.0
IL_0099: ldc.i4.s 101
IL_009b: beq.s IL_00c6
IL_009d: br.s IL_00bc
IL_009f: ldloc.0
IL_00a0: ldc.i4.s 103
IL_00a2: beq.s IL_00c6
IL_00a4: ldloc.0
IL_00a5: ldc.i4 0x3e9
IL_00aa: sub
IL_00ab: switch (
IL_00c6,
IL_00c6,
IL_00c6)
IL_00bc: ldstr ""default ""
IL_00c1: call ""void System.Console.Write(string)""
IL_00c6: ldarga.s V_0
IL_00c8: call ""bool short?.HasValue.get""
IL_00cd: brfalse IL_016e
IL_00d2: ldarga.s V_0
IL_00d4: call ""short short?.GetValueOrDefault()""
IL_00d9: stloc.0
IL_00da: ldloc.0
IL_00db: ldc.i4.s 101
IL_00dd: bgt.s IL_00f9
IL_00df: ldloc.0
IL_00e0: ldc.i4.1
IL_00e1: sub
IL_00e2: switch (
IL_0117,
IL_0122,
IL_012d)
IL_00f3: ldloc.0
IL_00f4: ldc.i4.s 101
IL_00f6: beq.s IL_0138
IL_00f8: ret
IL_00f9: ldloc.0
IL_00fa: ldc.i4.s 103
IL_00fc: beq.s IL_0143
IL_00fe: ldloc.0
IL_00ff: ldc.i4 0x3e9
IL_0104: sub
IL_0105: switch (
IL_014e,
IL_0159,
IL_0164)
IL_0116: ret
IL_0117: ldstr ""FAIL""
IL_011c: call ""void System.Console.Write(string)""
IL_0121: ret
IL_0122: ldstr ""FAIL""
IL_0127: call ""void System.Console.Write(string)""
IL_012c: ret
IL_012d: ldstr ""FAIL""
IL_0132: call ""void System.Console.Write(string)""
IL_0137: ret
IL_0138: ldstr ""FAIL""
IL_013d: call ""void System.Console.Write(string)""
IL_0142: ret
IL_0143: ldstr ""FAIL""
IL_0148: call ""void System.Console.Write(string)""
IL_014d: ret
IL_014e: ldstr ""FAIL""
IL_0153: call ""void System.Console.Write(string)""
IL_0158: ret
IL_0159: ldstr ""FAIL""
IL_015e: call ""void System.Console.Write(string)""
IL_0163: ret
IL_0164: ldstr ""FAIL""
IL_0169: call ""void System.Console.Write(string)""
IL_016e: ret
}");
}
[Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")]
public void SwitchOnNullableInt64WithInt32Label()
{
var text = @"public static class C
{
public static bool F(long? x)
{
switch (x)
{
case 1:
return true;
default:
return false;
}
}
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "True");
compVerifier.VerifyIL("C.F(long?)",
@"{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool long?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""long long?.GetValueOrDefault()""
IL_0010: ldc.i4.1
IL_0011: conv.i8
IL_0012: bne.un.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}"
);
}
[Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")]
public void SwitchOnNullableWithNonConstant()
{
var text = @"public static class C
{
public static bool F(int? x)
{
int i = 4;
switch (x)
{
case i:
return true;
default:
return false;
}
}
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compilation = base.CreateCSharpCompilation(text);
compilation.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case i:
Diagnostic(ErrorCode.ERR_ConstantExpected, "i").WithLocation(8, 18)
);
}
[Fact, WorkItem(7625, "https://github.com/dotnet/roslyn/issues/7625")]
public void SwitchOnNullableWithNonCompatibleType()
{
var text = @"public static class C
{
public static bool F(int? x)
{
switch (x)
{
case default(System.DateTime):
return true;
default:
return false;
}
}
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compilation = base.CreateCSharpCompilation(text);
// (7,18): error CS0029: Cannot implicitly convert type 'System.DateTime' to 'int?'
// case default(System.DateTime):
var expected = Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(System.DateTime)").WithArguments("System.DateTime", "int?");
compilation.VerifyDiagnostics(expected);
}
[Fact]
public void SwitchOnNullableInt64WithInt32LabelWithEnum()
{
var text = @"public static class C
{
public static bool F(long? x)
{
switch (x)
{
case (int)Goo.X:
return true;
default:
return false;
}
}
public enum Goo : int { X = 1 }
static void Main()
{
System.Console.WriteLine(F(1));
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "True");
compVerifier.VerifyIL("C.F(long?)",
@"{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool long?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""long long?.GetValueOrDefault()""
IL_0010: ldc.i4.1
IL_0011: conv.i8
IL_0012: bne.un.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}"
);
}
// TODO: Add more targeted tests for verifying switch bucketing
#region "String tests"
[Fact]
public void StringTypeSwitchArgumentExpression()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
string s = ""hello"";
switch (s)
{
default:
return 1;
case null:
return 1;
case ""hello"":
return 0;
}
return 1;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (25,5): warning CS0162: Unreachable code detected
// return 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "return"));
compVerifier.VerifyIL("Test.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //s
IL_0000: ldstr ""hello""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brfalse.s IL_0018
IL_0009: ldloc.0
IL_000a: ldstr ""hello""
IL_000f: call ""bool string.op_Equality(string, string)""
IL_0014: brtrue.s IL_001a
IL_0016: ldc.i4.1
IL_0017: ret
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldc.i4.0
IL_001b: ret
}"
);
// We shouldn't generate a string hash synthesized method if we are generating non hash string switch
VerifySynthesizedStringHashMethod(compVerifier, expected: false);
}
[Fact]
public void StringSwitch_SwitchOnNull()
{
var text = @"using System;
public class Test
{
public static int Main(string[] args)
{
string s = null;
int ret = 0;
switch (s)
{
case null + ""abc"":
ret = 1;
break;
case null + ""def"":
ret = 1;
break;
}
Console.Write(ret);
return ret;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (string V_0, //s
int V_1) //ret
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: ldstr ""abc""
IL_000a: call ""bool string.op_Equality(string, string)""
IL_000f: brtrue.s IL_0020
IL_0011: ldloc.0
IL_0012: ldstr ""def""
IL_0017: call ""bool string.op_Equality(string, string)""
IL_001c: brtrue.s IL_0024
IL_001e: br.s IL_0026
IL_0020: ldc.i4.1
IL_0021: stloc.1
IL_0022: br.s IL_0026
IL_0024: ldc.i4.1
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: call ""void System.Console.Write(int)""
IL_002c: ldloc.1
IL_002d: ret
}"
);
// We shouldn't generate a string hash synthesized method if we are generating non hash string switch
VerifySynthesizedStringHashMethod(compVerifier, expected: false);
}
[Fact]
[WorkItem(546632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546632")]
public void StringSwitch_HashTableSwitch_01()
{
var text = @"using System;
class Test
{
public static bool M(string test)
{
string value = """";
if (test != null && test.IndexOf(""C#"") != -1)
test = test.Remove(0, 2);
switch (test)
{
case null:
value = null;
break;
case """":
break;
case ""_"":
value = ""_"";
break;
case ""W"":
value = ""W"";
break;
case ""B"":
value = ""B"";
break;
case ""C"":
value = ""C"";
break;
case ""<"":
value = ""<"";
break;
case ""T"":
value = ""T"";
break;
case ""M"":
value = ""M"";
break;
}
return (value == test);
}
public static void Main()
{
bool success = Test.M(""C#"");
success &= Test.M(""C#_"");
success &= Test.M(""C#W"");
success &= Test.M(""C#B"");
success &= Test.M(""C#C"");
success &= Test.M(""C#<"");
success &= Test.M(""C#T"");
success &= Test.M(""C#M"");
success &= Test.M(null);
Console.WriteLine(success);
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "True");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 365 (0x16d)
.maxstack 3
.locals init (string V_0, //value
uint V_1)
IL_0000: ldstr """"
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: brfalse.s IL_0021
IL_0009: ldarg.0
IL_000a: ldstr ""C#""
IL_000f: callvirt ""int string.IndexOf(string)""
IL_0014: ldc.i4.m1
IL_0015: beq.s IL_0021
IL_0017: ldarg.0
IL_0018: ldc.i4.0
IL_0019: ldc.i4.2
IL_001a: callvirt ""string string.Remove(int, int)""
IL_001f: starg.s V_0
IL_0021: ldarg.0
IL_0022: brfalse IL_012b
IL_0027: ldarg.0
IL_0028: call ""ComputeStringHash""
IL_002d: stloc.1
IL_002e: ldloc.1
IL_002f: ldc.i4 0xc70bfb85
IL_0034: bgt.un.s IL_006e
IL_0036: ldloc.1
IL_0037: ldc.i4 0x811c9dc5
IL_003c: bgt.un.s IL_0056
IL_003e: ldloc.1
IL_003f: ldc.i4 0x390caefb
IL_0044: beq IL_00fe
IL_0049: ldloc.1
IL_004a: ldc.i4 0x811c9dc5
IL_004f: beq.s IL_00a6
IL_0051: br IL_0165
IL_0056: ldloc.1
IL_0057: ldc.i4 0xc60bf9f2
IL_005c: beq IL_00ef
IL_0061: ldloc.1
IL_0062: ldc.i4 0xc70bfb85
IL_0067: beq.s IL_00e0
IL_0069: br IL_0165
IL_006e: ldloc.1
IL_006f: ldc.i4 0xd10c0b43
IL_0074: bgt.un.s IL_0091
IL_0076: ldloc.1
IL_0077: ldc.i4 0xc80bfd18
IL_007c: beq IL_011c
IL_0081: ldloc.1
IL_0082: ldc.i4 0xd10c0b43
IL_0087: beq IL_010d
IL_008c: br IL_0165
IL_0091: ldloc.1
IL_0092: ldc.i4 0xd20c0cd6
IL_0097: beq.s IL_00ce
IL_0099: ldloc.1
IL_009a: ldc.i4 0xda0c196e
IL_009f: beq.s IL_00bc
IL_00a1: br IL_0165
IL_00a6: ldarg.0
IL_00a7: brfalse IL_0165
IL_00ac: ldarg.0
IL_00ad: call ""int string.Length.get""
IL_00b2: brfalse IL_0165
IL_00b7: br IL_0165
IL_00bc: ldarg.0
IL_00bd: ldstr ""_""
IL_00c2: call ""bool string.op_Equality(string, string)""
IL_00c7: brtrue.s IL_012f
IL_00c9: br IL_0165
IL_00ce: ldarg.0
IL_00cf: ldstr ""W""
IL_00d4: call ""bool string.op_Equality(string, string)""
IL_00d9: brtrue.s IL_0137
IL_00db: br IL_0165
IL_00e0: ldarg.0
IL_00e1: ldstr ""B""
IL_00e6: call ""bool string.op_Equality(string, string)""
IL_00eb: brtrue.s IL_013f
IL_00ed: br.s IL_0165
IL_00ef: ldarg.0
IL_00f0: ldstr ""C""
IL_00f5: call ""bool string.op_Equality(string, string)""
IL_00fa: brtrue.s IL_0147
IL_00fc: br.s IL_0165
IL_00fe: ldarg.0
IL_00ff: ldstr ""<""
IL_0104: call ""bool string.op_Equality(string, string)""
IL_0109: brtrue.s IL_014f
IL_010b: br.s IL_0165
IL_010d: ldarg.0
IL_010e: ldstr ""T""
IL_0113: call ""bool string.op_Equality(string, string)""
IL_0118: brtrue.s IL_0157
IL_011a: br.s IL_0165
IL_011c: ldarg.0
IL_011d: ldstr ""M""
IL_0122: call ""bool string.op_Equality(string, string)""
IL_0127: brtrue.s IL_015f
IL_0129: br.s IL_0165
IL_012b: ldnull
IL_012c: stloc.0
IL_012d: br.s IL_0165
IL_012f: ldstr ""_""
IL_0134: stloc.0
IL_0135: br.s IL_0165
IL_0137: ldstr ""W""
IL_013c: stloc.0
IL_013d: br.s IL_0165
IL_013f: ldstr ""B""
IL_0144: stloc.0
IL_0145: br.s IL_0165
IL_0147: ldstr ""C""
IL_014c: stloc.0
IL_014d: br.s IL_0165
IL_014f: ldstr ""<""
IL_0154: stloc.0
IL_0155: br.s IL_0165
IL_0157: ldstr ""T""
IL_015c: stloc.0
IL_015d: br.s IL_0165
IL_015f: ldstr ""M""
IL_0164: stloc.0
IL_0165: ldloc.0
IL_0166: ldarg.0
IL_0167: call ""bool string.op_Equality(string, string)""
IL_016c: ret
}"
);
// Verify string hash synthesized method for hash table switch
VerifySynthesizedStringHashMethod(compVerifier, expected: true);
// verify that hash method is internal:
var reference = compVerifier.Compilation.EmitToImageReference();
var comp = CSharpCompilation.Create("Name", references: new[] { reference }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
var pid = ((NamedTypeSymbol)comp.GlobalNamespace.GetMembers().Single(s => s.Name.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
var member = pid.GetMembers(PrivateImplementationDetails.SynthesizedStringHashFunctionName).Single();
Assert.Equal(Accessibility.Internal, member.DeclaredAccessibility);
}
[Fact]
public void StringSwitch_HashTableSwitch_02()
{
var text = @"
using System;
using System.Text;
class Test
{
public static bool Switcheroo(string test)
{
string value = """";
if (test.IndexOf(""C#"") != -1)
test = test.Remove(0, 2);
switch (test)
{
case ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"":
value = ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"";
break;
case ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"":
value = ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"";
break;
case ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"":
value = ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"";
break;
case ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"":
value = ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"";
break;
case ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"":
value = ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"";
break;
case ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"":
value = ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"";
break;
case ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"":
value = ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"";
break;
case ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"":
value = ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"";
break;
case ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"":
value = ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"";
break;
case ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"":
value = ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"";
break;
case "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"":
value = "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"";
break;
case ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"":
value = ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"";
break;
case ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"":
value = ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"";
break;
case ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"":
value = ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"";
break;
case ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"":
value = ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"";
break;
case ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"":
value = ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"";
break;
case ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"":
value = ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"";
break;
case ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"":
value = ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"";
break;
case ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"":
value = ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"";
break;
case ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"":
value = ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"";
break;
case ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"":
value = ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"";
break;
case ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"":
value = ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"";
break;
case ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"":
value = ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"";
break;
case ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"":
value = ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"";
break;
}
return (value == test);
}
public static void Main()
{
string status = ""PASS"";
bool retval;
retval = Test.Switcheroo(""C#N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#>AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4"");
if (!retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#a@=FkgImdk5<Wn0DRYa?m0<F0JT4kha;H:HIZ;6C"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Zbk^]59O<<GHe8MjRMOh4]c3@RQ?hU>^G81cOMW:"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#hP<l25H@W60UF4bYYDU]0AjIE6oCQ^k66F9gNJ`Q"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#XS9dCIb;9T`;JJ1Jmimba@@0[l[B=BgDhKZ05DO2"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#JbMbko?;e@1XLU>:=c_Vg>0YTJ7Qd]6KLh26miBV"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#IW3:>L<H<kf:AS2ZYDGaE`?^HZY_D]cRO[lNjd4;"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#NC>J^E3;VJ`nKSjVbJ_Il^^@0Xof9CFA2I1I^9c>"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#TfjQOCnAhM8[T3JUbLlQMS=`F=?:FPT3=X0Q]aj:"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#H_6fHA8OKO><TYDXiIg[Qed<=71KC>^6cTMOjT]d"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#jN>cSCF0?I<1RSQ^g^HnBABPhUc>5Y`ahlY9HS]5"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#V;`Q_kEGIX=Mh9=UVF[Q@Q=QTT@oC]IRF]<bA1R9"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#7DKT?2VIk2^XUJ>C]G_IDe?299DJTD>1RO18Ql>F"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#U`^]IeJC;o^90V=5<ToV<Gj26hnZLolffohc8iZX"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#9S?>A?E>gBl_dC[iCiiNnW7<BP;eGHf>8ceTGZ6C"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#ALLhjN7]XVBBA=VcYM8iWg^FGiG[QG03dlKYnIAe"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#6<]i]EllPZf6mnAM0D1;0eP6_G1HmRSi?`1o[a_a"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#]5Tb^6:NB]>ahEoWI5U9N5beS<?da]A]fL08AelQ"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#KhPBV8=H?G^Hmaaf^n<GcoI8eC1O_0]579;MY=81"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#A8iN_OFUPIcWac0^LU1;^HaEX[_E]<8h3N:Hm_XX"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Y811aKWEJYcX6Y1aj_I]O7TXP5j_lo;71kAiB:;:"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#P@ok2DgbUDeLVA:POd`B_S@2Ocg99VQBZ<LI<gd1"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#9V84FSRoD9453VdERM86a6B12VeN]hNNU:]XE`W9"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#Tegah0mKcWmFhaH0K0oSjKGkmH8gDEF3SBVd2H1P"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#=II;VADkVKf7JV55ca5oUjkPaWSY7`LXTlgTV4^W"");
if (retval) status = ""FAIL"";
retval = Test.Switcheroo(""C#k7XPoXNhd8P0V7@Sd5ohO>h7io3Pl[J[8g:[_da^"");
if (retval) status = ""FAIL"";
Console.Write(status);
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput: "PASS");
compVerifier.VerifyIL("Test.Switcheroo", @"
{
// Code size 1115 (0x45b)
.maxstack 3
.locals init (string V_0, //value
uint V_1)
IL_0000: ldstr """"
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldstr ""C#""
IL_000c: callvirt ""int string.IndexOf(string)""
IL_0011: ldc.i4.m1
IL_0012: beq.s IL_001e
IL_0014: ldarg.0
IL_0015: ldc.i4.0
IL_0016: ldc.i4.2
IL_0017: callvirt ""string string.Remove(int, int)""
IL_001c: starg.s V_0
IL_001e: ldarg.0
IL_001f: call ""ComputeStringHash""
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: ldc.i4 0xb2f29419
IL_002b: bgt.un IL_00e0
IL_0030: ldloc.1
IL_0031: ldc.i4 0x619348d8
IL_0036: bgt.un.s IL_008c
IL_0038: ldloc.1
IL_0039: ldc.i4 0x36758e37
IL_003e: bgt.un.s IL_0066
IL_0040: ldloc.1
IL_0041: ldc.i4 0x144fd20d
IL_0046: beq IL_02ae
IL_004b: ldloc.1
IL_004c: ldc.i4 0x14ca99e2
IL_0051: beq IL_025a
IL_0056: ldloc.1
IL_0057: ldc.i4 0x36758e37
IL_005c: beq IL_0206
IL_0061: br IL_0453
IL_0066: ldloc.1
IL_0067: ldc.i4 0x5398a778
IL_006c: beq IL_021b
IL_0071: ldloc.1
IL_0072: ldc.i4 0x616477cf
IL_0077: beq IL_01b2
IL_007c: ldloc.1
IL_007d: ldc.i4 0x619348d8
IL_0082: beq IL_02ed
IL_0087: br IL_0453
IL_008c: ldloc.1
IL_008d: ldc.i4 0x78a826a8
IL_0092: bgt.un.s IL_00ba
IL_0094: ldloc.1
IL_0095: ldc.i4 0x65b3e3e5
IL_009a: beq IL_02c3
IL_009f: ldloc.1
IL_00a0: ldc.i4 0x7822b5bc
IL_00a5: beq IL_0284
IL_00aa: ldloc.1
IL_00ab: ldc.i4 0x78a826a8
IL_00b0: beq IL_01dc
IL_00b5: br IL_0453
IL_00ba: ldloc.1
IL_00bb: ldc.i4 0x7f66da4e
IL_00c0: beq IL_0356
IL_00c5: ldloc.1
IL_00c6: ldc.i4 0xb13d374d
IL_00cb: beq IL_032c
IL_00d0: ldloc.1
IL_00d1: ldc.i4 0xb2f29419
IL_00d6: beq IL_0302
IL_00db: br IL_0453
IL_00e0: ldloc.1
IL_00e1: ldc.i4 0xd59864f4
IL_00e6: bgt.un.s IL_013c
IL_00e8: ldloc.1
IL_00e9: ldc.i4 0xbf4a9f8e
IL_00ee: bgt.un.s IL_0116
IL_00f0: ldloc.1
IL_00f1: ldc.i4 0xb6e02d3a
IL_00f6: beq IL_0299
IL_00fb: ldloc.1
IL_00fc: ldc.i4 0xbaed3db3
IL_0101: beq IL_0317
IL_0106: ldloc.1
IL_0107: ldc.i4 0xbf4a9f8e
IL_010c: beq IL_0230
IL_0111: br IL_0453
IL_0116: ldloc.1
IL_0117: ldc.i4 0xc6284d42
IL_011c: beq IL_01f1
IL_0121: ldloc.1
IL_0122: ldc.i4 0xd1761402
IL_0127: beq IL_01c7
IL_012c: ldloc.1
IL_012d: ldc.i4 0xd59864f4
IL_0132: beq IL_026f
IL_0137: br IL_0453
IL_013c: ldloc.1
IL_013d: ldc.i4 0xeb323c73
IL_0142: bgt.un.s IL_016a
IL_0144: ldloc.1
IL_0145: ldc.i4 0xdca4b248
IL_014a: beq IL_0245
IL_014f: ldloc.1
IL_0150: ldc.i4 0xe926f470
IL_0155: beq IL_036b
IL_015a: ldloc.1
IL_015b: ldc.i4 0xeb323c73
IL_0160: beq IL_02d8
IL_0165: br IL_0453
IL_016a: ldloc.1
IL_016b: ldc.i4 0xf1ea0ad5
IL_0170: beq IL_0341
IL_0175: ldloc.1
IL_0176: ldc.i4 0xfa67b44d
IL_017b: beq.s IL_019d
IL_017d: ldloc.1
IL_017e: ldc.i4 0xfea21584
IL_0183: bne.un IL_0453
IL_0188: ldarg.0
IL_0189: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""
IL_018e: call ""bool string.op_Equality(string, string)""
IL_0193: brtrue IL_0380
IL_0198: br IL_0453
IL_019d: ldarg.0
IL_019e: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""
IL_01a3: call ""bool string.op_Equality(string, string)""
IL_01a8: brtrue IL_038b
IL_01ad: br IL_0453
IL_01b2: ldarg.0
IL_01b3: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""
IL_01b8: call ""bool string.op_Equality(string, string)""
IL_01bd: brtrue IL_0396
IL_01c2: br IL_0453
IL_01c7: ldarg.0
IL_01c8: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""
IL_01cd: call ""bool string.op_Equality(string, string)""
IL_01d2: brtrue IL_03a1
IL_01d7: br IL_0453
IL_01dc: ldarg.0
IL_01dd: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""
IL_01e2: call ""bool string.op_Equality(string, string)""
IL_01e7: brtrue IL_03ac
IL_01ec: br IL_0453
IL_01f1: ldarg.0
IL_01f2: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""
IL_01f7: call ""bool string.op_Equality(string, string)""
IL_01fc: brtrue IL_03b7
IL_0201: br IL_0453
IL_0206: ldarg.0
IL_0207: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""
IL_020c: call ""bool string.op_Equality(string, string)""
IL_0211: brtrue IL_03c2
IL_0216: br IL_0453
IL_021b: ldarg.0
IL_021c: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""
IL_0221: call ""bool string.op_Equality(string, string)""
IL_0226: brtrue IL_03cd
IL_022b: br IL_0453
IL_0230: ldarg.0
IL_0231: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""
IL_0236: call ""bool string.op_Equality(string, string)""
IL_023b: brtrue IL_03d5
IL_0240: br IL_0453
IL_0245: ldarg.0
IL_0246: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""
IL_024b: call ""bool string.op_Equality(string, string)""
IL_0250: brtrue IL_03dd
IL_0255: br IL_0453
IL_025a: ldarg.0
IL_025b: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""
IL_0260: call ""bool string.op_Equality(string, string)""
IL_0265: brtrue IL_03e5
IL_026a: br IL_0453
IL_026f: ldarg.0
IL_0270: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""
IL_0275: call ""bool string.op_Equality(string, string)""
IL_027a: brtrue IL_03ed
IL_027f: br IL_0453
IL_0284: ldarg.0
IL_0285: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""
IL_028a: call ""bool string.op_Equality(string, string)""
IL_028f: brtrue IL_03f5
IL_0294: br IL_0453
IL_0299: ldarg.0
IL_029a: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""
IL_029f: call ""bool string.op_Equality(string, string)""
IL_02a4: brtrue IL_03fd
IL_02a9: br IL_0453
IL_02ae: ldarg.0
IL_02af: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""
IL_02b4: call ""bool string.op_Equality(string, string)""
IL_02b9: brtrue IL_0405
IL_02be: br IL_0453
IL_02c3: ldarg.0
IL_02c4: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""
IL_02c9: call ""bool string.op_Equality(string, string)""
IL_02ce: brtrue IL_040d
IL_02d3: br IL_0453
IL_02d8: ldarg.0
IL_02d9: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""
IL_02de: call ""bool string.op_Equality(string, string)""
IL_02e3: brtrue IL_0415
IL_02e8: br IL_0453
IL_02ed: ldarg.0
IL_02ee: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""
IL_02f3: call ""bool string.op_Equality(string, string)""
IL_02f8: brtrue IL_041d
IL_02fd: br IL_0453
IL_0302: ldarg.0
IL_0303: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""
IL_0308: call ""bool string.op_Equality(string, string)""
IL_030d: brtrue IL_0425
IL_0312: br IL_0453
IL_0317: ldarg.0
IL_0318: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""
IL_031d: call ""bool string.op_Equality(string, string)""
IL_0322: brtrue IL_042d
IL_0327: br IL_0453
IL_032c: ldarg.0
IL_032d: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""
IL_0332: call ""bool string.op_Equality(string, string)""
IL_0337: brtrue IL_0435
IL_033c: br IL_0453
IL_0341: ldarg.0
IL_0342: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""
IL_0347: call ""bool string.op_Equality(string, string)""
IL_034c: brtrue IL_043d
IL_0351: br IL_0453
IL_0356: ldarg.0
IL_0357: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""
IL_035c: call ""bool string.op_Equality(string, string)""
IL_0361: brtrue IL_0445
IL_0366: br IL_0453
IL_036b: ldarg.0
IL_036c: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""
IL_0371: call ""bool string.op_Equality(string, string)""
IL_0376: brtrue IL_044d
IL_037b: br IL_0453
IL_0380: ldstr ""N?_2hBEJa_klm0=BRoM]mBSY3l=Zm<Aj:mBNm9[9""
IL_0385: stloc.0
IL_0386: br IL_0453
IL_038b: ldstr ""emoYDC`E3JS]IU[X55VKF<e5CjkZb0S0VYQlcS]I""
IL_0390: stloc.0
IL_0391: br IL_0453
IL_0396: ldstr ""Ye]@FRVZi8Rbn0;43c8lo5`W]1CK;cfa2485N45m""
IL_039b: stloc.0
IL_039c: br IL_0453
IL_03a1: ldstr ""[Q0V3M_N2;9jTP=79iBK6<edbYXh;`FcaEGD0RhD""
IL_03a6: stloc.0
IL_03a7: br IL_0453
IL_03ac: ldstr ""<9Ria992H`W:DNX7lm]LV]9LUnJKDXcCo6Zd_FM]""
IL_03b1: stloc.0
IL_03b2: br IL_0453
IL_03b7: ldstr ""[Z`j:cCFgh2cd3:>1Z@T0o<Q<0o_;11]nMd3bP9c""
IL_03bc: stloc.0
IL_03bd: br IL_0453
IL_03c2: ldstr ""d2U5RWR:j0RS9MZZP3[f@NPgKFS9mQi:na@4Z_G0""
IL_03c7: stloc.0
IL_03c8: br IL_0453
IL_03cd: ldstr ""n7AOl<DYj1]k>F7FaW^5b2Ki6UP0@=glIc@RE]3>""
IL_03d2: stloc.0
IL_03d3: br.s IL_0453
IL_03d5: ldstr ""H==7DT_M5125HT:m@`7cgg>WbZ4HAFg`Am:Ba:fF""
IL_03da: stloc.0
IL_03db: br.s IL_0453
IL_03dd: ldstr ""iEj07Ik=?G35AfEf?8@5[@4OGYeXIHYH]CZlHY7:""
IL_03e2: stloc.0
IL_03e3: br.s IL_0453
IL_03e5: ldstr "">AcFS3V9Y@g<55K`=QnYTS=B^CS@kg6:Hc_UaRTj""
IL_03ea: stloc.0
IL_03eb: br.s IL_0453
IL_03ed: ldstr ""d1QZgJ_jT]UeL^UF2XWS@I?Hdi1MTm9Z3mdV7]0:""
IL_03f2: stloc.0
IL_03f3: br.s IL_0453
IL_03f5: ldstr ""fVObMkcK:_AQae0VY4N]bDXXI_KkoeNZ9ohT?gfU""
IL_03fa: stloc.0
IL_03fb: br.s IL_0453
IL_03fd: ldstr ""9o4i04]a4g2PRLBl@`]OaoY]1<h3on[5=I3U[9RR""
IL_0402: stloc.0
IL_0403: br.s IL_0453
IL_0405: ldstr ""A1>CNg1bZTYE64G<Adn;aE957eWjEcaXZUf<TlGj""
IL_040a: stloc.0
IL_040b: br.s IL_0453
IL_040d: ldstr ""SK`1T7]RZZR]lkZ`nFcm]k0RJlcF>eN5=jEi=A^k""
IL_0412: stloc.0
IL_0413: br.s IL_0453
IL_0415: ldstr ""0@U=MkSf3niYF;8aC0U]IX=X[Y]Kjmj<4CR5:4R4""
IL_041a: stloc.0
IL_041b: br.s IL_0453
IL_041d: ldstr ""4g1JY?VRdh5RYS[Z;ElS=5I`7?>OKlD3mF1;]M<O""
IL_0422: stloc.0
IL_0423: br.s IL_0453
IL_0425: ldstr ""EH=noQ6]]@Vj5PDW;KFeEE7j>I<Q>4243W`AGHAe""
IL_042a: stloc.0
IL_042b: br.s IL_0453
IL_042d: ldstr ""?k3Amd3aFf3_4S<bJ9;UdR7WYVmbZLh[2ekHKdTM""
IL_0432: stloc.0
IL_0433: br.s IL_0453
IL_0435: ldstr ""HR9nATB9C[FY7B]9iI6IbodSencFWSVlhL879C:W""
IL_043a: stloc.0
IL_043b: br.s IL_0453
IL_043d: ldstr ""XPTnWmDfL^AIH];Ek6l1AV9J020j<W:V6SU9VA@D""
IL_0442: stloc.0
IL_0443: br.s IL_0453
IL_0445: ldstr ""MXO]7S@eM`o>LUXfLTk^m3eP2NbAj8N^[]J7PCh9""
IL_044a: stloc.0
IL_044b: br.s IL_0453
IL_044d: ldstr ""L=FTZJ_V59eFjg_REMagg4n0Sng1]3mOgEAQ]EL4""
IL_0452: stloc.0
IL_0453: ldloc.0
IL_0454: ldarg.0
IL_0455: call ""bool string.op_Equality(string, string)""
IL_045a: ret
}"
);
// Verify string hash synthesized method for hash table switch
VerifySynthesizedStringHashMethod(compVerifier, expected: true);
}
[WorkItem(544322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544322")]
[Fact]
public void StringSwitch_HashTableSwitch_03()
{
var text = @"
using System;
class Goo
{
public static void Main()
{
Console.WriteLine(M(""blah""));
}
static int M(string s)
{
byte[] bytes = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
switch (s)
{
case ""blah"":
return 1;
case ""help"":
return 2;
case ""ooof"":
return 3;
case ""walk"":
return 4;
case ""bark"":
return 5;
case ""xblah"":
return 1;
case ""xhelp"":
return 2;
case ""xooof"":
return 3;
case ""xwalk"":
return 4;
case ""xbark"":
return 5;
case ""rblah"":
return 1;
case ""rhelp"":
return 2;
case ""rooof"":
return 3;
case ""rwalk"":
return 4;
case ""rbark"":
return 5;
}
return bytes.Length;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "1");
// Verify string hash synthesized method for hash table switch
VerifySynthesizedStringHashMethod(compVerifier, expected: true);
}
private static void VerifySynthesizedStringHashMethod(CompilationVerifier compVerifier, bool expected)
{
compVerifier.VerifyMemberInIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName, expected);
if (expected)
{
compVerifier.VerifyIL(PrivateImplementationDetails.SynthesizedStringHashFunctionName,
@"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (uint V_0,
int V_1)
IL_0000: ldarg.0
IL_0001: brfalse.s IL_002a
IL_0003: ldc.i4 0x811c9dc5
IL_0008: stloc.0
IL_0009: ldc.i4.0
IL_000a: stloc.1
IL_000b: br.s IL_0021
IL_000d: ldarg.0
IL_000e: ldloc.1
IL_000f: callvirt ""char string.this[int].get""
IL_0014: ldloc.0
IL_0015: xor
IL_0016: ldc.i4 0x1000193
IL_001b: mul
IL_001c: stloc.0
IL_001d: ldloc.1
IL_001e: ldc.i4.1
IL_001f: add
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.0
IL_0023: callvirt ""int string.Length.get""
IL_0028: blt.s IL_000d
IL_002a: ldloc.0
IL_002b: ret
}
");
}
}
#endregion
#region "Implicit user defined conversion tests"
[WorkItem(543602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543602")]
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_01()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var source = @"using System;
public class Test
{
public static implicit operator int(Test val)
{
return 1;
}
public static implicit operator float(Test val2)
{
return 2.1f;
}
public static int Main()
{
Test t = new Test();
switch (t)
{
case 1:
Console.WriteLine(0);
return 0;
default:
Console.WriteLine(1);
return 1;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_02()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
class X {}
class Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator X (Conv C2)
{
return new X();
}
public static int Main()
{
Conv C = new Conv();
switch(C)
{
case 1:
System.Console.WriteLine(""Pass"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 1;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_03()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
enum X { F = 0 }
class Conv
{
// only valid operator
public static implicit operator int (Conv C)
{
return 1;
}
// bool type is not valid
public static implicit operator bool (Conv C2)
{
return false;
}
// enum type is not valid
public static implicit operator X (Conv C3)
{
return X.F;
}
public static int Main()
{
Conv C = new Conv();
switch(C)
{
case 1:
System.Console.WriteLine(""Pass"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 1;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_04()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator int? (Conv? C2)
{
return null;
}
public static int Main()
{
Conv? D = new Conv();
switch(D)
{
case 1:
System.Console.WriteLine(""Fail"");
return 1;
case null:
System.Console.WriteLine(""Pass"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 1;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_06()
{
// Exactly ONE user-defined implicit conversion (6.4) must exist from the type of
// the switch expression to one of the following possible governing types: sbyte, byte, short,
// ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if
// more than one such implicit conversion exists, a compile-time error occurs.
var text = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator int? (Conv? C)
{
return null;
}
public static int Main()
{
Conv? C = new Conv();
switch(C)
{
case null:
System.Console.WriteLine(""Pass"");
return 0;
case 1:
System.Console.WriteLine(""Fail"");
return 0;
default:
System.Console.WriteLine(""Fail"");
return 0;
}
}
}
";
CompileAndVerify(text, expectedOutput: "Pass");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_3()
{
var text =
@"using System;
struct A
{
public static implicit operator int?(A? a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int(A a)
{
Console.WriteLine(""1"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "0");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_2_4()
{
var text =
@"using System;
struct A
{
public static implicit operator int?(A a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int(A? a)
{
Console.WriteLine(""1"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "1");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_1()
{
var text =
@"using System;
struct A
{
public static implicit operator int(A a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int(A? a)
{
Console.WriteLine(""1"");
return 0;
}
public static implicit operator int?(A a)
{
Console.WriteLine(""2"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "1");
}
[WorkItem(543673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543673")]
[Fact()]
public void ImplicitUserDefinedConversionToSwitchGoverningType_11564_3_3()
{
var text =
@"using System;
struct A
{
public static implicit operator int?(A a)
{
Console.WriteLine(""0"");
return 0;
}
public static implicit operator int?(A? a)
{
Console.WriteLine(""1"");
return 0;
}
public static implicit operator int(A a)
{
Console.WriteLine(""2"");
return 0;
}
class B
{
static void Main()
{
A? aNullable = new A();
switch(aNullable)
{
default: break;
}
}
}
}
";
CompileAndVerify(text, expectedOutput: "1");
}
#endregion
[WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")]
[Fact()]
public void MissingCharsProperty()
{
var text = @"
using System;
class Program
{
static string d = null;
static void Main()
{
string s = ""hello"";
switch (s)
{
case ""Hi"":
d = "" Hi "";
break;
case ""Bye"":
d = "" Bye "";
break;
case ""qwe"":
d = "" qwe "";
break;
case ""ert"":
d = "" ert "";
break;
case ""asd"":
d = "" asd "";
break;
case ""hello"":
d = "" hello "";
break;
case ""qrs"":
d = "" qrs "";
break;
case ""tuv"":
d = "" tuv "";
break;
case ""wxy"":
d = "" wxy "";
break;
}
}
}
";
var comp = CreateEmptyCompilation(
source: new[] { Parse(text) },
references: new[] { AacorlibRef });
var verifier = CompileAndVerify(comp, verify: Verification.Fails);
verifier.VerifyIL("Program.Main", @"
{
// Code size 223 (0xdf)
.maxstack 2
.locals init (string V_0) //s
IL_0000: ldstr ""hello""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""Hi""
IL_000c: call ""bool string.op_Equality(string, string)""
IL_0011: brtrue.s IL_007c
IL_0013: ldloc.0
IL_0014: ldstr ""Bye""
IL_0019: call ""bool string.op_Equality(string, string)""
IL_001e: brtrue.s IL_0087
IL_0020: ldloc.0
IL_0021: ldstr ""qwe""
IL_0026: call ""bool string.op_Equality(string, string)""
IL_002b: brtrue.s IL_0092
IL_002d: ldloc.0
IL_002e: ldstr ""ert""
IL_0033: call ""bool string.op_Equality(string, string)""
IL_0038: brtrue.s IL_009d
IL_003a: ldloc.0
IL_003b: ldstr ""asd""
IL_0040: call ""bool string.op_Equality(string, string)""
IL_0045: brtrue.s IL_00a8
IL_0047: ldloc.0
IL_0048: ldstr ""hello""
IL_004d: call ""bool string.op_Equality(string, string)""
IL_0052: brtrue.s IL_00b3
IL_0054: ldloc.0
IL_0055: ldstr ""qrs""
IL_005a: call ""bool string.op_Equality(string, string)""
IL_005f: brtrue.s IL_00be
IL_0061: ldloc.0
IL_0062: ldstr ""tuv""
IL_0067: call ""bool string.op_Equality(string, string)""
IL_006c: brtrue.s IL_00c9
IL_006e: ldloc.0
IL_006f: ldstr ""wxy""
IL_0074: call ""bool string.op_Equality(string, string)""
IL_0079: brtrue.s IL_00d4
IL_007b: ret
IL_007c: ldstr "" Hi ""
IL_0081: stsfld ""string Program.d""
IL_0086: ret
IL_0087: ldstr "" Bye ""
IL_008c: stsfld ""string Program.d""
IL_0091: ret
IL_0092: ldstr "" qwe ""
IL_0097: stsfld ""string Program.d""
IL_009c: ret
IL_009d: ldstr "" ert ""
IL_00a2: stsfld ""string Program.d""
IL_00a7: ret
IL_00a8: ldstr "" asd ""
IL_00ad: stsfld ""string Program.d""
IL_00b2: ret
IL_00b3: ldstr "" hello ""
IL_00b8: stsfld ""string Program.d""
IL_00bd: ret
IL_00be: ldstr "" qrs ""
IL_00c3: stsfld ""string Program.d""
IL_00c8: ret
IL_00c9: ldstr "" tuv ""
IL_00ce: stsfld ""string Program.d""
IL_00d3: ret
IL_00d4: ldstr "" wxy ""
IL_00d9: stsfld ""string Program.d""
IL_00de: ret
}");
}
[WorkItem(642186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642186")]
[Fact()]
public void IsWarningSwitchEmit()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication24
{
class Program
{
static void Main(string[] args)
{
TimeIt();
TimeIt();
TimeIt();
TimeIt();
TimeIt();
TimeIt();
TimeIt();
}
private static void TimeIt()
{
// var sw = System.Diagnostics.Stopwatch.StartNew();
//
// for (int i = 0; i < 100000000; i++)
// {
// IsWarning((ErrorCode)(i % 10002));
// }
//
// sw.Stop();
// System.Console.WriteLine(sw.ElapsedMilliseconds);
}
public static bool IsWarning(ErrorCode code)
{
switch (code)
{
case ErrorCode.WRN_InvalidMainSig:
case ErrorCode.WRN_UnreferencedEvent:
case ErrorCode.WRN_LowercaseEllSuffix:
case ErrorCode.WRN_DuplicateUsing:
case ErrorCode.WRN_NewRequired:
case ErrorCode.WRN_NewNotRequired:
case ErrorCode.WRN_NewOrOverrideExpected:
case ErrorCode.WRN_UnreachableCode:
case ErrorCode.WRN_UnreferencedLabel:
case ErrorCode.WRN_UnreferencedVar:
case ErrorCode.WRN_UnreferencedField:
case ErrorCode.WRN_IsAlwaysTrue:
case ErrorCode.WRN_IsAlwaysFalse:
case ErrorCode.WRN_ByRefNonAgileField:
case ErrorCode.WRN_OldWarning_UnsafeProp:
case ErrorCode.WRN_UnreferencedVarAssg:
case ErrorCode.WRN_NegativeArrayIndex:
case ErrorCode.WRN_BadRefCompareLeft:
case ErrorCode.WRN_BadRefCompareRight:
case ErrorCode.WRN_PatternIsAmbiguous:
case ErrorCode.WRN_PatternStaticOrInaccessible:
case ErrorCode.WRN_PatternBadSignature:
case ErrorCode.WRN_SequentialOnPartialClass:
case ErrorCode.WRN_MainCantBeGeneric:
case ErrorCode.WRN_UnreferencedFieldAssg:
case ErrorCode.WRN_AmbiguousXMLReference:
case ErrorCode.WRN_VolatileByRef:
case ErrorCode.WRN_IncrSwitchObsolete:
case ErrorCode.WRN_UnreachableExpr:
case ErrorCode.WRN_SameFullNameThisNsAgg:
case ErrorCode.WRN_SameFullNameThisAggAgg:
case ErrorCode.WRN_SameFullNameThisAggNs:
case ErrorCode.WRN_GlobalAliasDefn:
case ErrorCode.WRN_UnexpectedPredefTypeLoc:
case ErrorCode.WRN_AlwaysNull:
case ErrorCode.WRN_CmpAlwaysFalse:
case ErrorCode.WRN_FinalizeMethod:
case ErrorCode.WRN_AmbigLookupMeth:
case ErrorCode.WRN_GotoCaseShouldConvert:
case ErrorCode.WRN_NubExprIsConstBool:
case ErrorCode.WRN_ExplicitImplCollision:
case ErrorCode.WRN_FeatureDeprecated:
case ErrorCode.WRN_DeprecatedSymbol:
case ErrorCode.WRN_DeprecatedSymbolStr:
case ErrorCode.WRN_ExternMethodNoImplementation:
case ErrorCode.WRN_ProtectedInSealed:
case ErrorCode.WRN_PossibleMistakenNullStatement:
case ErrorCode.WRN_UnassignedInternalField:
case ErrorCode.WRN_VacuousIntegralComp:
case ErrorCode.WRN_AttributeLocationOnBadDeclaration:
case ErrorCode.WRN_InvalidAttributeLocation:
case ErrorCode.WRN_EqualsWithoutGetHashCode:
case ErrorCode.WRN_EqualityOpWithoutEquals:
case ErrorCode.WRN_EqualityOpWithoutGetHashCode:
case ErrorCode.WRN_IncorrectBooleanAssg:
case ErrorCode.WRN_NonObsoleteOverridingObsolete:
case ErrorCode.WRN_BitwiseOrSignExtend:
case ErrorCode.WRN_OldWarning_ProtectedInternal:
case ErrorCode.WRN_OldWarning_AccessibleReadonly:
case ErrorCode.WRN_CoClassWithoutComImport:
case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter:
case ErrorCode.WRN_AssignmentToLockOrDispose:
case ErrorCode.WRN_ObsoleteOverridingNonObsolete:
case ErrorCode.WRN_DebugFullNameTooLong:
case ErrorCode.WRN_ExternCtorNoImplementation:
case ErrorCode.WRN_WarningDirective:
case ErrorCode.WRN_UnreachableGeneralCatch:
case ErrorCode.WRN_UninitializedField:
case ErrorCode.WRN_DeprecatedCollectionInitAddStr:
case ErrorCode.WRN_DeprecatedCollectionInitAdd:
case ErrorCode.WRN_DefaultValueForUnconsumedLocation:
case ErrorCode.WRN_FeatureDeprecated2:
case ErrorCode.WRN_FeatureDeprecated3:
case ErrorCode.WRN_FeatureDeprecated4:
case ErrorCode.WRN_FeatureDeprecated5:
case ErrorCode.WRN_OldWarning_FeatureDefaultDeprecated:
case ErrorCode.WRN_EmptySwitch:
case ErrorCode.WRN_XMLParseError:
case ErrorCode.WRN_DuplicateParamTag:
case ErrorCode.WRN_UnmatchedParamTag:
case ErrorCode.WRN_MissingParamTag:
case ErrorCode.WRN_BadXMLRef:
case ErrorCode.WRN_BadXMLRefParamType:
case ErrorCode.WRN_BadXMLRefReturnType:
case ErrorCode.WRN_BadXMLRefSyntax:
case ErrorCode.WRN_UnprocessedXMLComment:
case ErrorCode.WRN_FailedInclude:
case ErrorCode.WRN_InvalidInclude:
case ErrorCode.WRN_MissingXMLComment:
case ErrorCode.WRN_XMLParseIncludeError:
case ErrorCode.WRN_OldWarning_MultipleTypeDefs:
case ErrorCode.WRN_OldWarning_DocFileGenAndIncr:
case ErrorCode.WRN_XMLParserNotFound:
case ErrorCode.WRN_ALinkWarn:
case ErrorCode.WRN_DeleteAutoResFailed:
case ErrorCode.WRN_CmdOptionConflictsSource:
case ErrorCode.WRN_IllegalPragma:
case ErrorCode.WRN_IllegalPPWarning:
case ErrorCode.WRN_BadRestoreNumber:
case ErrorCode.WRN_NonECMAFeature:
case ErrorCode.WRN_ErrorOverride:
case ErrorCode.WRN_OldWarning_ReservedIdentifier:
case ErrorCode.WRN_InvalidSearchPathDir:
case ErrorCode.WRN_MissingTypeNested:
case ErrorCode.WRN_MissingTypeInSource:
case ErrorCode.WRN_MissingTypeInAssembly:
case ErrorCode.WRN_MultiplePredefTypes:
case ErrorCode.WRN_TooManyLinesForDebugger:
case ErrorCode.WRN_CallOnNonAgileField:
case ErrorCode.WRN_BadWarningNumber:
case ErrorCode.WRN_InvalidNumber:
case ErrorCode.WRN_FileNameTooLong:
case ErrorCode.WRN_IllegalPPChecksum:
case ErrorCode.WRN_EndOfPPLineExpected:
case ErrorCode.WRN_ConflictingChecksum:
case ErrorCode.WRN_AssumedMatchThis:
case ErrorCode.WRN_UseSwitchInsteadOfAttribute:
case ErrorCode.WRN_InvalidAssemblyName:
case ErrorCode.WRN_UnifyReferenceMajMin:
case ErrorCode.WRN_UnifyReferenceBldRev:
case ErrorCode.WRN_DelegateNewMethBind:
case ErrorCode.WRN_EmptyFileName:
case ErrorCode.WRN_DuplicateTypeParamTag:
case ErrorCode.WRN_UnmatchedTypeParamTag:
case ErrorCode.WRN_MissingTypeParamTag:
case ErrorCode.WRN_AssignmentToSelf:
case ErrorCode.WRN_ComparisonToSelf:
case ErrorCode.WRN_DotOnDefault:
case ErrorCode.WRN_BadXMLRefTypeVar:
case ErrorCode.WRN_UnmatchedParamRefTag:
case ErrorCode.WRN_UnmatchedTypeParamRefTag:
case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA:
case ErrorCode.WRN_TypeNotFoundForNoPIAWarning:
case ErrorCode.WRN_CantHaveManifestForModule:
case ErrorCode.WRN_MultipleRuntimeImplementationMatches:
case ErrorCode.WRN_MultipleRuntimeOverrideMatches:
case ErrorCode.WRN_DynamicDispatchToConditionalMethod:
case ErrorCode.WRN_IsDynamicIsConfusing:
case ErrorCode.WRN_AsyncLacksAwaits:
case ErrorCode.WRN_FileAlreadyIncluded:
case ErrorCode.WRN_NoSources:
case ErrorCode.WRN_UseNewSwitch:
case ErrorCode.WRN_NoConfigNotOnCommandLine:
case ErrorCode.WRN_DefineIdentifierRequired:
case ErrorCode.WRN_BadUILang:
case ErrorCode.WRN_CLS_NoVarArgs:
case ErrorCode.WRN_CLS_BadArgType:
case ErrorCode.WRN_CLS_BadReturnType:
case ErrorCode.WRN_CLS_BadFieldPropType:
case ErrorCode.WRN_CLS_BadUnicode:
case ErrorCode.WRN_CLS_BadIdentifierCase:
case ErrorCode.WRN_CLS_OverloadRefOut:
case ErrorCode.WRN_CLS_OverloadUnnamed:
case ErrorCode.WRN_CLS_BadIdentifier:
case ErrorCode.WRN_CLS_BadBase:
case ErrorCode.WRN_CLS_BadInterfaceMember:
case ErrorCode.WRN_CLS_NoAbstractMembers:
case ErrorCode.WRN_CLS_NotOnModules:
case ErrorCode.WRN_CLS_ModuleMissingCLS:
case ErrorCode.WRN_CLS_AssemblyNotCLS:
case ErrorCode.WRN_CLS_BadAttributeType:
case ErrorCode.WRN_CLS_ArrayArgumentToAttribute:
case ErrorCode.WRN_CLS_NotOnModules2:
case ErrorCode.WRN_CLS_IllegalTrueInFalse:
case ErrorCode.WRN_CLS_MeaninglessOnPrivateType:
case ErrorCode.WRN_CLS_AssemblyNotCLS2:
case ErrorCode.WRN_CLS_MeaninglessOnParam:
case ErrorCode.WRN_CLS_MeaninglessOnReturn:
case ErrorCode.WRN_CLS_BadTypeVar:
case ErrorCode.WRN_CLS_VolatileField:
case ErrorCode.WRN_CLS_BadInterface:
case ErrorCode.WRN_UnobservedAwaitableExpression:
case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation:
case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation:
case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation:
case ErrorCode.WRN_UnknownOption:
case ErrorCode.WRN_MetadataNameTooLong:
case ErrorCode.WRN_MainIgnored:
case ErrorCode.WRN_DelaySignButNoKey:
case ErrorCode.WRN_InvalidVersionFormat:
case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath:
case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden:
case ErrorCode.WRN_UnimplementedCommandLineSwitch:
case ErrorCode.WRN_RefCultureMismatch:
case ErrorCode.WRN_ConflictingMachineAssembly:
case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope1:
case ErrorCode.WRN_CA2000_DisposeObjectsBeforeLosingScope2:
case ErrorCode.WRN_CA2202_DoNotDisposeObjectsMultipleTimes:
return true;
default:
return false;
}
}
internal enum ErrorCode
{
Void = InternalErrorCode.Void,
Unknown = InternalErrorCode.Unknown,
FTL_InternalError = 1,
//FTL_FailedToLoadResource = 2,
//FTL_NoMemory = 3,
//ERR_WarningAsError = 4,
//ERR_MissingOptionArg = 5,
ERR_NoMetadataFile = 6,
//FTL_ComPlusInit = 7,
FTL_MetadataImportFailure = 8,
FTL_MetadataCantOpenFile = 9,
//ERR_FatalError = 10,
//ERR_CantImportBase = 11,
ERR_NoTypeDef = 12,
FTL_MetadataEmitFailure = 13,
//FTL_RequiredFileNotFound = 14,
ERR_ClassNameTooLong = 15,
ERR_OutputWriteFailed = 16,
ERR_MultipleEntryPoints = 17,
//ERR_UnimplementedOp = 18,
ERR_BadBinaryOps = 19,
ERR_IntDivByZero = 20,
ERR_BadIndexLHS = 21,
ERR_BadIndexCount = 22,
ERR_BadUnaryOp = 23,
//ERR_NoStdLib = 25, not used in Roslyn
ERR_ThisInStaticMeth = 26,
ERR_ThisInBadContext = 27,
WRN_InvalidMainSig = 28,
ERR_NoImplicitConv = 29,
ERR_NoExplicitConv = 30,
ERR_ConstOutOfRange = 31,
ERR_AmbigBinaryOps = 34,
ERR_AmbigUnaryOp = 35,
ERR_InAttrOnOutParam = 36,
ERR_ValueCantBeNull = 37,
//ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired ""An object reference is required for the non-static...""
ERR_NoExplicitBuiltinConv = 39,
//FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
FTL_DebugEmitFailure = 41,
//FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info.
//FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info.
ERR_BadVisReturnType = 50,
ERR_BadVisParamType = 51,
ERR_BadVisFieldType = 52,
ERR_BadVisPropertyType = 53,
ERR_BadVisIndexerReturn = 54,
ERR_BadVisIndexerParam = 55,
ERR_BadVisOpReturn = 56,
ERR_BadVisOpParam = 57,
ERR_BadVisDelegateReturn = 58,
ERR_BadVisDelegateParam = 59,
ERR_BadVisBaseClass = 60,
ERR_BadVisBaseInterface = 61,
ERR_EventNeedsBothAccessors = 65,
ERR_EventNotDelegate = 66,
WRN_UnreferencedEvent = 67,
ERR_InterfaceEventInitializer = 68,
ERR_EventPropertyInInterface = 69,
ERR_BadEventUsage = 70,
ERR_ExplicitEventFieldImpl = 71,
ERR_CantOverrideNonEvent = 72,
ERR_AddRemoveMustHaveBody = 73,
ERR_AbstractEventInitializer = 74,
ERR_PossibleBadNegCast = 75,
ERR_ReservedEnumerator = 76,
ERR_AsMustHaveReferenceType = 77,
WRN_LowercaseEllSuffix = 78,
ERR_BadEventUsageNoField = 79,
ERR_ConstraintOnlyAllowedOnGenericDecl = 80,
ERR_TypeParamMustBeIdentifier = 81,
ERR_MemberReserved = 82,
ERR_DuplicateParamName = 100,
ERR_DuplicateNameInNS = 101,
ERR_DuplicateNameInClass = 102,
ERR_NameNotInContext = 103,
ERR_AmbigContext = 104,
WRN_DuplicateUsing = 105,
ERR_BadMemberFlag = 106,
ERR_BadMemberProtection = 107,
WRN_NewRequired = 108,
WRN_NewNotRequired = 109,
ERR_CircConstValue = 110,
ERR_MemberAlreadyExists = 111,
ERR_StaticNotVirtual = 112,
ERR_OverrideNotNew = 113,
WRN_NewOrOverrideExpected = 114,
ERR_OverrideNotExpected = 115,
ERR_NamespaceUnexpected = 116,
ERR_NoSuchMember = 117,
ERR_BadSKknown = 118,
ERR_BadSKunknown = 119,
ERR_ObjectRequired = 120,
ERR_AmbigCall = 121,
ERR_BadAccess = 122,
ERR_MethDelegateMismatch = 123,
ERR_RetObjectRequired = 126,
ERR_RetNoObjectRequired = 127,
ERR_LocalDuplicate = 128,
ERR_AssgLvalueExpected = 131,
ERR_StaticConstParam = 132,
ERR_NotConstantExpression = 133,
ERR_NotNullConstRefField = 134,
ERR_NameIllegallyOverrides = 135,
ERR_LocalIllegallyOverrides = 136,
ERR_BadUsingNamespace = 138,
ERR_NoBreakOrCont = 139,
ERR_DuplicateLabel = 140,
ERR_NoConstructors = 143,
ERR_NoNewAbstract = 144,
ERR_ConstValueRequired = 145,
ERR_CircularBase = 146,
ERR_BadDelegateConstructor = 148,
ERR_MethodNameExpected = 149,
ERR_ConstantExpected = 150,
// ERR_SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler.
// However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future
// we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used.
ERR_SwitchGoverningTypeValueExpected = 151,
ERR_DuplicateCaseLabel = 152,
ERR_InvalidGotoCase = 153,
ERR_PropertyLacksGet = 154,
ERR_BadExceptionType = 155,
ERR_BadEmptyThrow = 156,
ERR_BadFinallyLeave = 157,
ERR_LabelShadow = 158,
ERR_LabelNotFound = 159,
ERR_UnreachableCatch = 160,
ERR_ReturnExpected = 161,
WRN_UnreachableCode = 162,
ERR_SwitchFallThrough = 163,
WRN_UnreferencedLabel = 164,
ERR_UseDefViolation = 165,
//ERR_NoInvoke = 167,
WRN_UnreferencedVar = 168,
WRN_UnreferencedField = 169,
ERR_UseDefViolationField = 170,
ERR_UnassignedThis = 171,
ERR_AmbigQM = 172,
ERR_InvalidQM = 173,
ERR_NoBaseClass = 174,
ERR_BaseIllegal = 175,
ERR_ObjectProhibited = 176,
ERR_ParamUnassigned = 177,
ERR_InvalidArray = 178,
ERR_ExternHasBody = 179,
ERR_AbstractAndExtern = 180,
ERR_BadAttributeParamType = 181,
ERR_BadAttributeArgument = 182,
WRN_IsAlwaysTrue = 183,
WRN_IsAlwaysFalse = 184,
ERR_LockNeedsReference = 185,
ERR_NullNotValid = 186,
ERR_UseDefViolationThis = 188,
ERR_ArgsInvalid = 190,
ERR_AssgReadonly = 191,
ERR_RefReadonly = 192,
ERR_PtrExpected = 193,
ERR_PtrIndexSingle = 196,
WRN_ByRefNonAgileField = 197,
ERR_AssgReadonlyStatic = 198,
ERR_RefReadonlyStatic = 199,
ERR_AssgReadonlyProp = 200,
ERR_IllegalStatement = 201,
ERR_BadGetEnumerator = 202,
ERR_TooManyLocals = 204,
ERR_AbstractBaseCall = 205,
ERR_RefProperty = 206,
WRN_OldWarning_UnsafeProp = 207, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:207"" is specified on the command line.
ERR_ManagedAddr = 208,
ERR_BadFixedInitType = 209,
ERR_FixedMustInit = 210,
ERR_InvalidAddrOp = 211,
ERR_FixedNeeded = 212,
ERR_FixedNotNeeded = 213,
ERR_UnsafeNeeded = 214,
ERR_OpTFRetType = 215,
ERR_OperatorNeedsMatch = 216,
ERR_BadBoolOp = 217,
ERR_MustHaveOpTF = 218,
WRN_UnreferencedVarAssg = 219,
ERR_CheckedOverflow = 220,
ERR_ConstOutOfRangeChecked = 221,
ERR_BadVarargs = 224,
ERR_ParamsMustBeArray = 225,
ERR_IllegalArglist = 226,
ERR_IllegalUnsafe = 227,
//ERR_NoAccessibleMember = 228,
ERR_AmbigMember = 229,
ERR_BadForeachDecl = 230,
ERR_ParamsLast = 231,
ERR_SizeofUnsafe = 233,
ERR_DottedTypeNameNotFoundInNS = 234,
ERR_FieldInitRefNonstatic = 236,
ERR_SealedNonOverride = 238,
ERR_CantOverrideSealed = 239,
//ERR_NoDefaultArgs = 241,
ERR_VoidError = 242,
ERR_ConditionalOnOverride = 243,
ERR_PointerInAsOrIs = 244,
ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated
ERR_SingleTypeNameNotFound = 246,
ERR_NegativeStackAllocSize = 247,
ERR_NegativeArraySize = 248,
ERR_OverrideFinalizeDeprecated = 249,
ERR_CallingBaseFinalizeDeprecated = 250,
WRN_NegativeArrayIndex = 251,
WRN_BadRefCompareLeft = 252,
WRN_BadRefCompareRight = 253,
ERR_BadCastInFixed = 254,
ERR_StackallocInCatchFinally = 255,
ERR_VarargsLast = 257,
ERR_MissingPartial = 260,
ERR_PartialTypeKindConflict = 261,
ERR_PartialModifierConflict = 262,
ERR_PartialMultipleBases = 263,
ERR_PartialWrongTypeParams = 264,
ERR_PartialWrongConstraints = 265,
ERR_NoImplicitConvCast = 266,
ERR_PartialMisplaced = 267,
ERR_ImportedCircularBase = 268,
ERR_UseDefViolationOut = 269,
ERR_ArraySizeInDeclaration = 270,
ERR_InaccessibleGetter = 271,
ERR_InaccessibleSetter = 272,
ERR_InvalidPropertyAccessMod = 273,
ERR_DuplicatePropertyAccessMods = 274,
ERR_PropertyAccessModInInterface = 275,
ERR_AccessModMissingAccessor = 276,
ERR_UnimplementedInterfaceAccessor = 277,
WRN_PatternIsAmbiguous = 278,
WRN_PatternStaticOrInaccessible = 279,
WRN_PatternBadSignature = 280,
ERR_FriendRefNotEqualToThis = 281,
WRN_SequentialOnPartialClass = 282,
ERR_BadConstType = 283,
ERR_NoNewTyvar = 304,
ERR_BadArity = 305,
ERR_BadTypeArgument = 306,
ERR_TypeArgsNotAllowed = 307,
ERR_HasNoTypeVars = 308,
ERR_NewConstraintNotSatisfied = 310,
ERR_GenericConstraintNotSatisfiedRefType = 311,
ERR_GenericConstraintNotSatisfiedNullableEnum = 312,
ERR_GenericConstraintNotSatisfiedNullableInterface = 313,
ERR_GenericConstraintNotSatisfiedTyVar = 314,
ERR_GenericConstraintNotSatisfiedValType = 315,
ERR_DuplicateGeneratedName = 316,
ERR_GlobalSingleTypeNameNotFound = 400,
ERR_NewBoundMustBeLast = 401,
WRN_MainCantBeGeneric = 402,
ERR_TypeVarCantBeNull = 403,
ERR_AttributeCantBeGeneric = 404,
ERR_DuplicateBound = 405,
ERR_ClassBoundNotFirst = 406,
ERR_BadRetType = 407,
ERR_DuplicateConstraintClause = 409,
//ERR_WrongSignature = 410, unused in Roslyn
ERR_CantInferMethTypeArgs = 411,
ERR_LocalSameNameAsTypeParam = 412,
ERR_AsWithTypeVar = 413,
WRN_UnreferencedFieldAssg = 414,
ERR_BadIndexerNameAttr = 415,
ERR_AttrArgWithTypeVars = 416,
ERR_NewTyvarWithArgs = 417,
ERR_AbstractSealedStatic = 418,
WRN_AmbiguousXMLReference = 419,
WRN_VolatileByRef = 420,
WRN_IncrSwitchObsolete = 422, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line.
ERR_ComImportWithImpl = 423,
ERR_ComImportWithBase = 424,
ERR_ImplBadConstraints = 425,
ERR_DottedTypeNameNotFoundInAgg = 426,
ERR_MethGrpToNonDel = 428,
WRN_UnreachableExpr = 429, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line.
ERR_BadExternAlias = 430,
ERR_ColColWithTypeAlias = 431,
ERR_AliasNotFound = 432,
ERR_SameFullNameAggAgg = 433,
ERR_SameFullNameNsAgg = 434,
WRN_SameFullNameThisNsAgg = 435,
WRN_SameFullNameThisAggAgg = 436,
WRN_SameFullNameThisAggNs = 437,
ERR_SameFullNameThisAggThisNs = 438,
ERR_ExternAfterElements = 439,
WRN_GlobalAliasDefn = 440,
ERR_SealedStaticClass = 441,
ERR_PrivateAbstractAccessor = 442,
ERR_ValueExpected = 443,
WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn"" is specified on the command line.
ERR_UnboxNotLValue = 445,
ERR_AnonMethGrpInForEach = 446,
//ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error.
ERR_BadIncDecRetType = 448,
ERR_TypeConstraintsMustBeUniqueAndFirst = 449,
ERR_RefValBoundWithClass = 450,
ERR_NewBoundWithVal = 451,
ERR_RefConstraintNotSatisfied = 452,
ERR_ValConstraintNotSatisfied = 453,
ERR_CircularConstraint = 454,
ERR_BaseConstraintConflict = 455,
ERR_ConWithValCon = 456,
ERR_AmbigUDConv = 457,
WRN_AlwaysNull = 458,
ERR_AddrOnReadOnlyLocal = 459,
ERR_OverrideWithConstraints = 460,
ERR_AmbigOverride = 462,
ERR_DecConstError = 463,
WRN_CmpAlwaysFalse = 464,
WRN_FinalizeMethod = 465,
ERR_ExplicitImplParams = 466,
WRN_AmbigLookupMeth = 467,
ERR_SameFullNameThisAggThisAgg = 468,
WRN_GotoCaseShouldConvert = 469,
ERR_MethodImplementingAccessor = 470,
//ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn
WRN_NubExprIsConstBool = 472,
WRN_ExplicitImplCollision = 473,
ERR_AbstractHasBody = 500,
ERR_ConcreteMissingBody = 501,
ERR_AbstractAndSealed = 502,
ERR_AbstractNotVirtual = 503,
ERR_StaticConstant = 504,
ERR_CantOverrideNonFunction = 505,
ERR_CantOverrideNonVirtual = 506,
ERR_CantChangeAccessOnOverride = 507,
ERR_CantChangeReturnTypeOnOverride = 508,
ERR_CantDeriveFromSealedType = 509,
ERR_AbstractInConcreteClass = 513,
ERR_StaticConstructorWithExplicitConstructorCall = 514,
ERR_StaticConstructorWithAccessModifiers = 515,
ERR_RecursiveConstructorCall = 516,
ERR_ObjectCallingBaseConstructor = 517,
ERR_PredefinedTypeNotFound = 518,
//ERR_PredefinedTypeBadType = 520,
ERR_StructWithBaseConstructorCall = 522,
ERR_StructLayoutCycle = 523,
ERR_InterfacesCannotContainTypes = 524,
ERR_InterfacesCantContainFields = 525,
ERR_InterfacesCantContainConstructors = 526,
ERR_NonInterfaceInInterfaceList = 527,
ERR_DuplicateInterfaceInBaseList = 528,
ERR_CycleInInterfaceInheritance = 529,
ERR_InterfaceMemberHasBody = 531,
ERR_HidingAbstractMethod = 533,
ERR_UnimplementedAbstractMethod = 534,
ERR_UnimplementedInterfaceMember = 535,
ERR_ObjectCantHaveBases = 537,
ERR_ExplicitInterfaceImplementationNotInterface = 538,
ERR_InterfaceMemberNotFound = 539,
ERR_ClassDoesntImplementInterface = 540,
ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541,
ERR_MemberNameSameAsType = 542,
ERR_EnumeratorOverflow = 543,
ERR_CantOverrideNonProperty = 544,
ERR_NoGetToOverride = 545,
ERR_NoSetToOverride = 546,
ERR_PropertyCantHaveVoidType = 547,
ERR_PropertyWithNoAccessors = 548,
ERR_NewVirtualInSealed = 549,
ERR_ExplicitPropertyAddingAccessor = 550,
ERR_ExplicitPropertyMissingAccessor = 551,
ERR_ConversionWithInterface = 552,
ERR_ConversionWithBase = 553,
ERR_ConversionWithDerived = 554,
ERR_IdentityConversion = 555,
ERR_ConversionNotInvolvingContainedType = 556,
ERR_DuplicateConversionInClass = 557,
ERR_OperatorsMustBeStatic = 558,
ERR_BadIncDecSignature = 559,
ERR_BadUnaryOperatorSignature = 562,
ERR_BadBinaryOperatorSignature = 563,
ERR_BadShiftOperatorSignature = 564,
ERR_InterfacesCantContainOperators = 567,
ERR_StructsCantContainDefaultConstructor = 568,
ERR_CantOverrideBogusMethod = 569,
ERR_BindToBogus = 570,
ERR_CantCallSpecialMethod = 571,
ERR_BadTypeReference = 572,
ERR_FieldInitializerInStruct = 573,
ERR_BadDestructorName = 574,
ERR_OnlyClassesCanContainDestructors = 575,
ERR_ConflictAliasAndMember = 576,
ERR_ConditionalOnSpecialMethod = 577,
ERR_ConditionalMustReturnVoid = 578,
ERR_DuplicateAttribute = 579,
ERR_ConditionalOnInterfaceMethod = 582,
//ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused
//ERR_ICE_Symbol = 584,
//ERR_ICE_Node = 585,
//ERR_ICE_File = 586,
//ERR_ICE_Stage = 587,
//ERR_ICE_Lexer = 588,
//ERR_ICE_Parser = 589,
ERR_OperatorCantReturnVoid = 590,
ERR_InvalidAttributeArgument = 591,
ERR_AttributeOnBadSymbolType = 592,
ERR_FloatOverflow = 594,
ERR_ComImportWithoutUuidAttribute = 596,
ERR_InvalidNamedArgument = 599,
ERR_DllImportOnInvalidMethod = 601,
WRN_FeatureDeprecated = 602, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:602"" is specified on the command line.
// ERR_NameAttributeOnOverride = 609, // removed in Roslyn
ERR_FieldCantBeRefAny = 610,
ERR_ArrayElementCantBeRefAny = 611,
WRN_DeprecatedSymbol = 612,
ERR_NotAnAttributeClass = 616,
ERR_BadNamedAttributeArgument = 617,
WRN_DeprecatedSymbolStr = 618,
ERR_DeprecatedSymbolStr = 619,
ERR_IndexerCantHaveVoidType = 620,
ERR_VirtualPrivate = 621,
ERR_ArrayInitToNonArrayType = 622,
ERR_ArrayInitInBadPlace = 623,
ERR_MissingStructOffset = 625,
WRN_ExternMethodNoImplementation = 626,
WRN_ProtectedInSealed = 628,
ERR_InterfaceImplementedByConditional = 629,
ERR_IllegalRefParam = 631,
ERR_BadArgumentToAttribute = 633,
//ERR_MissingComTypeOrMarshaller = 635,
ERR_StructOffsetOnBadStruct = 636,
ERR_StructOffsetOnBadField = 637,
ERR_AttributeUsageOnNonAttributeClass = 641,
WRN_PossibleMistakenNullStatement = 642,
ERR_DuplicateNamedAttributeArgument = 643,
ERR_DeriveFromEnumOrValueType = 644,
ERR_DefaultMemberOnIndexedType = 646,
//ERR_CustomAttributeError = 647,
ERR_BogusType = 648,
WRN_UnassignedInternalField = 649,
ERR_CStyleArray = 650,
WRN_VacuousIntegralComp = 652,
ERR_AbstractAttributeClass = 653,
ERR_BadNamedAttributeArgumentType = 655,
ERR_MissingPredefinedMember = 656,
WRN_AttributeLocationOnBadDeclaration = 657,
WRN_InvalidAttributeLocation = 658,
WRN_EqualsWithoutGetHashCode = 659,
WRN_EqualityOpWithoutEquals = 660,
WRN_EqualityOpWithoutGetHashCode = 661,
ERR_OutAttrOnRefParam = 662,
ERR_OverloadRefKind = 663,
ERR_LiteralDoubleCast = 664,
WRN_IncorrectBooleanAssg = 665,
ERR_ProtectedInStruct = 666,
//ERR_FeatureDeprecated = 667,
ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler
ERR_ComImportWithUserCtor = 669,
ERR_FieldCantHaveVoidType = 670,
WRN_NonObsoleteOverridingObsolete = 672,
ERR_SystemVoid = 673,
ERR_ExplicitParamArray = 674,
WRN_BitwiseOrSignExtend = 675,
ERR_VolatileStruct = 677,
ERR_VolatileAndReadonly = 678,
WRN_OldWarning_ProtectedInternal = 679, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:679"" is specified on the command line.
WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:680"" is specified on the command line.
ERR_AbstractField = 681,
ERR_BogusExplicitImpl = 682,
ERR_ExplicitMethodImplAccessor = 683,
WRN_CoClassWithoutComImport = 684,
ERR_ConditionalWithOutParam = 685,
ERR_AccessorImplementingMethod = 686,
ERR_AliasQualAsExpression = 687,
ERR_DerivingFromATyVar = 689,
//FTL_MalformedMetadata = 690,
ERR_DuplicateTypeParameter = 692,
WRN_TypeParameterSameAsOuterTypeParameter = 693,
ERR_TypeVariableSameAsParent = 694,
ERR_UnifyingInterfaceInstantiations = 695,
ERR_GenericDerivingFromAttribute = 698,
ERR_TyVarNotFoundInConstraint = 699,
ERR_BadBoundType = 701,
ERR_SpecialTypeAsBound = 702,
ERR_BadVisBound = 703,
ERR_LookupInTypeVariable = 704,
ERR_BadConstraintType = 706,
ERR_InstanceMemberInStaticClass = 708,
ERR_StaticBaseClass = 709,
ERR_ConstructorInStaticClass = 710,
ERR_DestructorInStaticClass = 711,
ERR_InstantiatingStaticClass = 712,
ERR_StaticDerivedFromNonObject = 713,
ERR_StaticClassInterfaceImpl = 714,
ERR_OperatorInStaticClass = 715,
ERR_ConvertToStaticClass = 716,
ERR_ConstraintIsStaticClass = 717,
ERR_GenericArgIsStaticClass = 718,
ERR_ArrayOfStaticClass = 719,
ERR_IndexerInStaticClass = 720,
ERR_ParameterIsStaticClass = 721,
ERR_ReturnTypeIsStaticClass = 722,
ERR_VarDeclIsStaticClass = 723,
ERR_BadEmptyThrowInFinally = 724,
//ERR_InvalidDecl = 725,
//ERR_InvalidSpecifier = 726,
//ERR_InvalidSpecifierUnk = 727,
WRN_AssignmentToLockOrDispose = 728,
ERR_ForwardedTypeInThisAssembly = 729,
ERR_ForwardedTypeIsNested = 730,
ERR_CycleInTypeForwarder = 731,
//ERR_FwdedGeneric = 733,
ERR_AssemblyNameOnNonModule = 734,
ERR_InvalidFwdType = 735,
ERR_CloseUnimplementedInterfaceMemberStatic = 736,
ERR_CloseUnimplementedInterfaceMemberNotPublic = 737,
ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738,
ERR_DuplicateTypeForwarder = 739,
ERR_ExpectedSelectOrGroup = 742,
ERR_ExpectedContextualKeywordOn = 743,
ERR_ExpectedContextualKeywordEquals = 744,
ERR_ExpectedContextualKeywordBy = 745,
ERR_InvalidAnonymousTypeMemberDeclarator = 746,
ERR_InvalidInitializerElementInitializer = 747,
ERR_InconsistentLambdaParameterUsage = 748,
ERR_PartialMethodInvalidModifier = 750,
ERR_PartialMethodOnlyInPartialClass = 751,
ERR_PartialMethodCannotHaveOutParameters = 752,
ERR_PartialMethodOnlyMethods = 753,
ERR_PartialMethodNotExplicit = 754,
ERR_PartialMethodExtensionDifference = 755,
ERR_PartialMethodOnlyOneLatent = 756,
ERR_PartialMethodOnlyOneActual = 757,
ERR_PartialMethodParamsDifference = 758,
ERR_PartialMethodMustHaveLatent = 759,
ERR_PartialMethodInconsistentConstraints = 761,
ERR_PartialMethodToDelegate = 762,
ERR_PartialMethodStaticDifference = 763,
ERR_PartialMethodUnsafeDifference = 764,
ERR_PartialMethodInExpressionTree = 765,
ERR_PartialMethodMustReturnVoid = 766,
ERR_ExplicitImplCollisionOnRefOut = 767,
//ERR_NoEmptyArrayRanges = 800,
//ERR_IntegerSpecifierOnOneDimArrays = 801,
//ERR_IntegerSpecifierMustBePositive = 802,
//ERR_ArrayRangeDimensionsMustMatch = 803,
//ERR_ArrayRangeDimensionsWrong = 804,
//ERR_IntegerSpecifierValidOnlyOnArrays = 805,
//ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806,
//ERR_UseAdditionalSquareBrackets = 807,
//ERR_DotDotNotAssociative = 808,
WRN_ObsoleteOverridingNonObsolete = 809,
WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong
ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue
ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer
ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator
ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer
ERR_ImplicitlyTypedLocalCannotBeFixed = 821,
ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst
WRN_ExternCtorNoImplementation = 824,
ERR_TypeVarNotFound = 825,
ERR_ImplicitlyTypedArrayNoBestType = 826,
ERR_AnonymousTypePropertyAssignedBadValue = 828,
ERR_ExpressionTreeContainsBaseAccess = 831,
ERR_ExpressionTreeContainsAssignment = 832,
ERR_AnonymousTypeDuplicatePropertyName = 833,
ERR_StatementLambdaToExpressionTree = 834,
ERR_ExpressionTreeMustHaveDelegate = 835,
ERR_AnonymousTypeNotAvailable = 836,
ERR_LambdaInIsAs = 837,
ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838,
ERR_MissingArgument = 839,
ERR_AutoPropertiesMustHaveBothAccessors = 840,
ERR_VariableUsedBeforeDeclaration = 841,
ERR_ExplicitLayoutAndAutoImplementedProperty = 842,
ERR_UnassignedThisAutoProperty = 843,
ERR_VariableUsedBeforeDeclarationAndHidesField = 844,
ERR_ExpressionTreeContainsBadCoalesce = 845,
ERR_ArrayInitializerExpected = 846,
ERR_ArrayInitializerIncorrectLength = 847,
// ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind
ERR_ExpressionTreeContainsNamedArgument = 853,
ERR_ExpressionTreeContainsOptionalArgument = 854,
ERR_ExpressionTreeContainsIndexedProperty = 855,
ERR_IndexedPropertyRequiresParams = 856,
ERR_IndexedPropertyMustHaveAllOptionalParams = 857,
ERR_FusionConfigFileNameTooLong = 858,
ERR_IdentifierExpected = 1001,
ERR_SemicolonExpected = 1002,
ERR_SyntaxError = 1003,
ERR_DuplicateModifier = 1004,
ERR_DuplicateAccessor = 1007,
ERR_IntegralTypeExpected = 1008,
ERR_IllegalEscape = 1009,
ERR_NewlineInConst = 1010,
ERR_EmptyCharConst = 1011,
ERR_TooManyCharsInConst = 1012,
ERR_InvalidNumber = 1013,
ERR_GetOrSetExpected = 1014,
ERR_ClassTypeExpected = 1015,
ERR_NamedArgumentExpected = 1016,
ERR_TooManyCatches = 1017,
ERR_ThisOrBaseExpected = 1018,
ERR_OvlUnaryOperatorExpected = 1019,
ERR_OvlBinaryOperatorExpected = 1020,
ERR_IntOverflow = 1021,
ERR_EOFExpected = 1022,
ERR_BadEmbeddedStmt = 1023,
ERR_PPDirectiveExpected = 1024,
ERR_EndOfPPLineExpected = 1025,
ERR_CloseParenExpected = 1026,
ERR_EndifDirectiveExpected = 1027,
ERR_UnexpectedDirective = 1028,
ERR_ErrorDirective = 1029,
WRN_WarningDirective = 1030,
ERR_TypeExpected = 1031,
ERR_PPDefFollowsToken = 1032,
//ERR_TooManyLines = 1033, unused in Roslyn.
//ERR_LineTooLong = 1034, unused in Roslyn.
ERR_OpenEndedComment = 1035,
ERR_OvlOperatorExpected = 1037,
ERR_EndRegionDirectiveExpected = 1038,
ERR_UnterminatedStringLit = 1039,
ERR_BadDirectivePlacement = 1040,
ERR_IdentifierExpectedKW = 1041,
ERR_SemiOrLBraceExpected = 1043,
ERR_MultiTypeInDeclaration = 1044,
ERR_AddOrRemoveExpected = 1055,
ERR_UnexpectedCharacter = 1056,
ERR_ProtectedInStatic = 1057,
WRN_UnreachableGeneralCatch = 1058,
ERR_IncrementLvalueExpected = 1059,
WRN_UninitializedField = 1060, //unused in Roslyn but preserving for the purposes of not breaking users' /nowarn settings
ERR_NoSuchMemberOrExtension = 1061,
WRN_DeprecatedCollectionInitAddStr = 1062,
ERR_DeprecatedCollectionInitAddStr = 1063,
WRN_DeprecatedCollectionInitAdd = 1064,
ERR_DefaultValueNotAllowed = 1065,
WRN_DefaultValueForUnconsumedLocation = 1066,
ERR_PartialWrongTypeParamsVariance = 1067,
ERR_GlobalSingleTypeNameNotFoundFwd = 1068,
ERR_DottedTypeNameNotFoundInNSFwd = 1069,
ERR_SingleTypeNameNotFoundFwd = 1070,
//ERR_NoSuchMemberOnNoPIAType = 1071, //EE
// ERR_EOLExpected = 1099, // EE
// ERR_NotSupportedinEE = 1100, // EE
ERR_BadThisParam = 1100,
ERR_BadRefWithThis = 1101,
ERR_BadOutWithThis = 1102,
ERR_BadTypeforThis = 1103,
ERR_BadParamModThis = 1104,
ERR_BadExtensionMeth = 1105,
ERR_BadExtensionAgg = 1106,
ERR_DupParamMod = 1107,
ERR_MultiParamMod = 1108,
ERR_ExtensionMethodsDecl = 1109,
ERR_ExtensionAttrNotFound = 1110,
//ERR_ExtensionTypeParam = 1111,
ERR_ExplicitExtension = 1112,
ERR_ValueTypeExtDelegate = 1113,
// Below five error codes are unused, but we still need to retain them to suppress CS1691 when ""/nowarn:1200,1201,1202,1203,1204"" is specified on the command line.
WRN_FeatureDeprecated2 = 1200,
WRN_FeatureDeprecated3 = 1201,
WRN_FeatureDeprecated4 = 1202,
WRN_FeatureDeprecated5 = 1203,
WRN_OldWarning_FeatureDefaultDeprecated = 1204,
ERR_BadArgCount = 1501,
//ERR_BadArgTypes = 1502,
ERR_BadArgType = 1503,
ERR_NoSourceFile = 1504,
ERR_CantRefResource = 1507,
ERR_ResourceNotUnique = 1508,
ERR_ImportNonAssembly = 1509,
ERR_RefLvalueExpected = 1510,
ERR_BaseInStaticMeth = 1511,
ERR_BaseInBadContext = 1512,
ERR_RbraceExpected = 1513,
ERR_LbraceExpected = 1514,
ERR_InExpected = 1515,
ERR_InvalidPreprocExpr = 1517,
//ERR_BadTokenInType = 1518, unused in Roslyn
ERR_InvalidMemberDecl = 1519,
ERR_MemberNeedsType = 1520,
ERR_BadBaseType = 1521,
WRN_EmptySwitch = 1522,
ERR_ExpectedEndTry = 1524,
ERR_InvalidExprTerm = 1525,
ERR_BadNewExpr = 1526,
ERR_NoNamespacePrivate = 1527,
ERR_BadVarDecl = 1528,
ERR_UsingAfterElements = 1529,
//ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this.
//ERR_DontUseInvoke = 1533,
ERR_BadBinOpArgs = 1534,
ERR_BadUnOpArgs = 1535,
ERR_NoVoidParameter = 1536,
ERR_DuplicateAlias = 1537,
ERR_BadProtectedAccess = 1540,
//ERR_CantIncludeDirectory = 1541,
ERR_AddModuleAssembly = 1542,
ERR_BindToBogusProp2 = 1545,
ERR_BindToBogusProp1 = 1546,
ERR_NoVoidHere = 1547,
//ERR_CryptoFailed = 1548,
//ERR_CryptoNotFound = 1549,
ERR_IndexerNeedsParam = 1551,
ERR_BadArraySyntax = 1552,
ERR_BadOperatorSyntax = 1553,
ERR_BadOperatorSyntax2 = 1554,
ERR_MainClassNotFound = 1555,
ERR_MainClassNotClass = 1556,
ERR_MainClassWrongFile = 1557,
ERR_NoMainInClass = 1558,
ERR_MainClassIsImport = 1559,
//ERR_FileNameTooLong = 1560,
ERR_OutputFileNameTooLong = 1561,
ERR_OutputNeedsName = 1562,
//ERR_OutputNeedsInput = 1563,
ERR_CantHaveWin32ResAndManifest = 1564,
ERR_CantHaveWin32ResAndIcon = 1565,
ERR_CantReadResource = 1566,
//ERR_AutoResGen = 1567,
//ERR_DocFileGen = 1569,
WRN_XMLParseError = 1570,
WRN_DuplicateParamTag = 1571,
WRN_UnmatchedParamTag = 1572,
WRN_MissingParamTag = 1573,
WRN_BadXMLRef = 1574,
ERR_BadStackAllocExpr = 1575,
ERR_InvalidLineNumber = 1576,
//ERR_ALinkFailed = 1577, No alink usage in Roslyn
ERR_MissingPPFile = 1578,
ERR_ForEachMissingMember = 1579,
WRN_BadXMLRefParamType = 1580,
WRN_BadXMLRefReturnType = 1581,
ERR_BadWin32Res = 1583,
WRN_BadXMLRefSyntax = 1584,
ERR_BadModifierLocation = 1585,
ERR_MissingArraySize = 1586,
WRN_UnprocessedXMLComment = 1587,
//ERR_CantGetCORSystemDir = 1588,
WRN_FailedInclude = 1589,
WRN_InvalidInclude = 1590,
WRN_MissingXMLComment = 1591,
WRN_XMLParseIncludeError = 1592,
ERR_BadDelArgCount = 1593,
//ERR_BadDelArgTypes = 1594,
WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1595"" is specified on the command line.
WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1596"" is specified on the command line.
ERR_UnexpectedSemicolon = 1597,
WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time).
ERR_MethodReturnCantBeRefAny = 1599,
ERR_CompileCancelled = 1600,
ERR_MethodArgCantBeRefAny = 1601,
ERR_AssgReadonlyLocal = 1604,
ERR_RefReadonlyLocal = 1605,
//ERR_ALinkCloseFailed = 1606,
WRN_ALinkWarn = 1607, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1607"" is specified on the command line.
ERR_CantUseRequiredAttribute = 1608,
ERR_NoModifiersOnAccessor = 1609,
WRN_DeleteAutoResFailed = 1610, // Unused but preserving for /nowarn
ERR_ParamsCantBeRefOut = 1611,
ERR_ReturnNotLValue = 1612,
ERR_MissingCoClass = 1613,
ERR_AmbiguousAttribute = 1614,
ERR_BadArgExtraRef = 1615,
WRN_CmdOptionConflictsSource = 1616,
ERR_BadCompatMode = 1617,
ERR_DelegateOnConditional = 1618,
//ERR_CantMakeTempFile = 1619,
ERR_BadArgRef = 1620,
ERR_YieldInAnonMeth = 1621,
ERR_ReturnInIterator = 1622,
ERR_BadIteratorArgType = 1623,
ERR_BadIteratorReturn = 1624,
ERR_BadYieldInFinally = 1625,
ERR_BadYieldInTryOfCatch = 1626,
ERR_EmptyYield = 1627,
ERR_AnonDelegateCantUse = 1628,
ERR_IllegalInnerUnsafe = 1629,
//ERR_BadWatsonMode = 1630,
ERR_BadYieldInCatch = 1631,
ERR_BadDelegateLeave = 1632,
WRN_IllegalPragma = 1633,
WRN_IllegalPPWarning = 1634,
WRN_BadRestoreNumber = 1635,
ERR_VarargsIterator = 1636,
ERR_UnsafeIteratorArgType = 1637,
//ERR_ReservedIdentifier = 1638,
ERR_BadCoClassSig = 1639,
ERR_MultipleIEnumOfT = 1640,
ERR_FixedDimsRequired = 1641,
ERR_FixedNotInStruct = 1642,
ERR_AnonymousReturnExpected = 1643,
ERR_NonECMAFeature = 1644,
WRN_NonECMAFeature = 1645,
ERR_ExpectedVerbatimLiteral = 1646,
//FTL_StackOverflow = 1647,
ERR_AssgReadonly2 = 1648,
ERR_RefReadonly2 = 1649,
ERR_AssgReadonlyStatic2 = 1650,
ERR_RefReadonlyStatic2 = 1651,
ERR_AssgReadonlyLocal2Cause = 1654,
ERR_RefReadonlyLocal2Cause = 1655,
ERR_AssgReadonlyLocalCause = 1656,
ERR_RefReadonlyLocalCause = 1657,
WRN_ErrorOverride = 1658,
WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1659"" is specified on the command line.
ERR_AnonMethToNonDel = 1660,
ERR_CantConvAnonMethParams = 1661,
ERR_CantConvAnonMethReturns = 1662,
ERR_IllegalFixedType = 1663,
ERR_FixedOverflow = 1664,
ERR_InvalidFixedArraySize = 1665,
ERR_FixedBufferNotFixed = 1666,
ERR_AttributeNotOnAccessor = 1667,
WRN_InvalidSearchPathDir = 1668,
ERR_IllegalVarArgs = 1669,
ERR_IllegalParams = 1670,
ERR_BadModifiersOnNamespace = 1671,
ERR_BadPlatformType = 1672,
ERR_ThisStructNotInAnonMeth = 1673,
ERR_NoConvToIDisp = 1674,
// ERR_InvalidGenericEnum = 1675, replaced with 7002
ERR_BadParamRef = 1676,
ERR_BadParamExtraRef = 1677,
ERR_BadParamType = 1678,
ERR_BadExternIdentifier = 1679,
ERR_AliasMissingFile = 1680,
ERR_GlobalExternAlias = 1681,
WRN_MissingTypeNested = 1682, //unused in Roslyn.
// 1683 and 1684 are unused warning codes, but we still need to retain them to suppress CS1691 when ""/nowarn:1683"" is specified on the command line.
// In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively.
WRN_MissingTypeInSource = 1683,
WRN_MissingTypeInAssembly = 1684,
WRN_MultiplePredefTypes = 1685,
ERR_LocalCantBeFixedAndHoisted = 1686,
WRN_TooManyLinesForDebugger = 1687,
ERR_CantConvAnonMethNoParams = 1688,
ERR_ConditionalOnNonAttributeClass = 1689,
WRN_CallOnNonAgileField = 1690,
WRN_BadWarningNumber = 1691,
WRN_InvalidNumber = 1692,
WRN_FileNameTooLong = 1694, //unused but preserving for the sake of existing code using /nowarn:1694
WRN_IllegalPPChecksum = 1695,
WRN_EndOfPPLineExpected = 1696,
WRN_ConflictingChecksum = 1697,
WRN_AssumedMatchThis = 1698,
WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1699"" is specified.
WRN_InvalidAssemblyName = 1700, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1700"" is specified.
WRN_UnifyReferenceMajMin = 1701,
WRN_UnifyReferenceBldRev = 1702,
ERR_DuplicateImport = 1703,
ERR_DuplicateImportSimple = 1704,
ERR_AssemblyMatchBadVersion = 1705,
ERR_AnonMethNotAllowed = 1706,
WRN_DelegateNewMethBind = 1707, // This error code is unused, but we still need to retain it to suppress CS1691 when ""/nowarn:1707"" is specified.
ERR_FixedNeedsLvalue = 1708,
WRN_EmptyFileName = 1709,
WRN_DuplicateTypeParamTag = 1710,
WRN_UnmatchedTypeParamTag = 1711,
WRN_MissingTypeParamTag = 1712,
//FTL_TypeNameBuilderError = 1713,
ERR_ImportBadBase = 1714,
ERR_CantChangeTypeOnOverride = 1715,
ERR_DoNotUseFixedBufferAttr = 1716,
WRN_AssignmentToSelf = 1717,
WRN_ComparisonToSelf = 1718,
ERR_CantOpenWin32Res = 1719,
WRN_DotOnDefault = 1720,
ERR_NoMultipleInheritance = 1721,
ERR_BaseClassMustBeFirst = 1722,
WRN_BadXMLRefTypeVar = 1723,
//ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn.
ERR_FriendAssemblyBadArgs = 1725,
ERR_FriendAssemblySNReq = 1726,
//ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings.
ERR_DelegateOnNullable = 1728,
ERR_BadCtorArgCount = 1729,
ERR_GlobalAttributesNotFirst = 1730,
ERR_CantConvAnonMethReturnsNoDelegate = 1731,
//ERR_ParameterExpected = 1732, Not used in Roslyn.
ERR_ExpressionExpected = 1733,
WRN_UnmatchedParamRefTag = 1734,
WRN_UnmatchedTypeParamRefTag = 1735,
ERR_DefaultValueMustBeConstant = 1736,
ERR_DefaultValueBeforeRequiredValue = 1737,
ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738,
ERR_BadNamedArgument = 1739,
ERR_DuplicateNamedArgument = 1740,
ERR_RefOutDefaultValue = 1741,
ERR_NamedArgumentForArray = 1742,
ERR_DefaultValueForExtensionParameter = 1743,
ERR_NamedArgumentUsedInPositional = 1744,
ERR_DefaultValueUsedWithAttributes = 1745,
ERR_BadNamedArgumentForDelegateInvoke = 1746,
ERR_NoPIAAssemblyMissingAttribute = 1747,
ERR_NoCanonicalView = 1748,
//ERR_TypeNotFoundForNoPIA = 1749,
ERR_NoConversionForDefaultParam = 1750,
ERR_DefaultValueForParamsParameter = 1751,
ERR_NewCoClassOnLink = 1752,
ERR_NoPIANestedType = 1754,
//ERR_InvalidTypeIdentifierConstructor = 1755,
ERR_InteropTypeMissingAttribute = 1756,
ERR_InteropStructContainsMethods = 1757,
ERR_InteropTypesWithSameNameAndGuid = 1758,
ERR_NoPIAAssemblyMissingAttributes = 1759,
ERR_AssemblySpecifiedForLinkAndRef = 1760,
ERR_LocalTypeNameClash = 1761,
WRN_ReferencedAssemblyReferencesLinkedPIA = 1762,
ERR_NotNullRefDefaultParameter = 1763,
ERR_FixedLocalInLambda = 1764,
WRN_TypeNotFoundForNoPIAWarning = 1765,
ERR_MissingMethodOnSourceInterface = 1766,
ERR_MissingSourceInterface = 1767,
ERR_GenericsUsedInNoPIAType = 1768,
ERR_GenericsUsedAcrossAssemblies = 1769,
ERR_NoConversionForNubDefaultParam = 1770,
//ERR_MemberWithGenericsUsedAcrossAssemblies = 1771,
//ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772,
ERR_BadSubsystemVersion = 1773,
ERR_InteropMethodWithBody = 1774,
ERR_BadWarningLevel = 1900,
ERR_BadDebugType = 1902,
//ERR_UnknownTestSwitch = 1903,
ERR_BadResourceVis = 1906,
ERR_DefaultValueTypeMustMatch = 1908,
//ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn.
ERR_DefaultValueBadValueType = 1910,
ERR_MemberAlreadyInitialized = 1912,
ERR_MemberCannotBeInitialized = 1913,
ERR_StaticMemberInObjectInitializer = 1914,
ERR_ReadonlyValueTypeInObjectInitializer = 1917,
ERR_ValueTypePropertyInObjectInitializer = 1918,
ERR_UnsafeTypeInObjectCreation = 1919,
ERR_EmptyElementInitializer = 1920,
ERR_InitializerAddHasWrongSignature = 1921,
ERR_CollectionInitRequiresIEnumerable = 1922,
ERR_InvalidCollectionInitializerType = 1925,
ERR_CantOpenWin32Manifest = 1926,
WRN_CantHaveManifestForModule = 1927,
ERR_BadExtensionArgTypes = 1928,
ERR_BadInstanceArgType = 1929,
ERR_QueryDuplicateRangeVariable = 1930,
ERR_QueryRangeVariableOverrides = 1931,
ERR_QueryRangeVariableAssignedBadValue = 1932,
ERR_QueryNotAllowed = 1933,
ERR_QueryNoProviderCastable = 1934,
ERR_QueryNoProviderStandard = 1935,
ERR_QueryNoProvider = 1936,
ERR_QueryOuterKey = 1937,
ERR_QueryInnerKey = 1938,
ERR_QueryOutRefRangeVariable = 1939,
ERR_QueryMultipleProviders = 1940,
ERR_QueryTypeInferenceFailedMulti = 1941,
ERR_QueryTypeInferenceFailed = 1942,
ERR_QueryTypeInferenceFailedSelectMany = 1943,
ERR_ExpressionTreeContainsPointerOp = 1944,
ERR_ExpressionTreeContainsAnonymousMethod = 1945,
ERR_AnonymousMethodToExpressionTree = 1946,
ERR_QueryRangeVariableReadOnly = 1947,
ERR_QueryRangeVariableSameAsTypeParam = 1948,
ERR_TypeVarNotFoundRangeVariable = 1949,
ERR_BadArgTypesForCollectionAdd = 1950,
ERR_ByRefParameterInExpressionTree = 1951,
ERR_VarArgsInExpressionTree = 1952,
ERR_MemGroupInExpressionTree = 1953,
ERR_InitializerAddHasParamModifiers = 1954,
ERR_NonInvocableMemberCalled = 1955,
WRN_MultipleRuntimeImplementationMatches = 1956,
WRN_MultipleRuntimeOverrideMatches = 1957,
ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958,
ERR_InvalidConstantDeclarationType = 1959,
ERR_IllegalVarianceSyntax = 1960,
ERR_UnexpectedVariance = 1961,
ERR_BadDynamicTypeof = 1962,
ERR_ExpressionTreeContainsDynamicOperation = 1963,
ERR_BadDynamicConversion = 1964,
ERR_DeriveFromDynamic = 1965,
ERR_DeriveFromConstructedDynamic = 1966,
ERR_DynamicTypeAsBound = 1967,
ERR_ConstructedDynamicTypeAsBound = 1968,
ERR_DynamicRequiredTypesMissing = 1969,
ERR_ExplicitDynamicAttr = 1970,
ERR_NoDynamicPhantomOnBase = 1971,
ERR_NoDynamicPhantomOnBaseIndexer = 1972,
ERR_BadArgTypeDynamicExtension = 1973,
WRN_DynamicDispatchToConditionalMethod = 1974,
ERR_NoDynamicPhantomOnBaseCtor = 1975,
ERR_BadDynamicMethodArgMemgrp = 1976,
ERR_BadDynamicMethodArgLambda = 1977,
ERR_BadDynamicMethodArg = 1978,
ERR_BadDynamicQuery = 1979,
ERR_DynamicAttributeMissing = 1980,
WRN_IsDynamicIsConfusing = 1981,
ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn.
ERR_BadAsyncReturn = 1983,
ERR_BadAwaitInFinally = 1984,
ERR_BadAwaitInCatch = 1985,
ERR_BadAwaitArg = 1986,
ERR_BadAsyncArgType = 1988,
ERR_BadAsyncExpressionTree = 1989,
ERR_WindowsRuntimeTypesMissing = 1990,
ERR_MixingWinRTEventWithRegular = 1991,
ERR_BadAwaitWithoutAsync = 1992,
ERR_MissingAsyncTypes = 1993,
ERR_BadAsyncLacksBody = 1994,
ERR_BadAwaitInQuery = 1995,
ERR_BadAwaitInLock = 1996,
ERR_TaskRetNoObjectRequired = 1997,
WRN_AsyncLacksAwaits = 1998,
ERR_FileNotFound = 2001,
WRN_FileAlreadyIncluded = 2002,
ERR_DuplicateResponseFile = 2003,
ERR_NoFileSpec = 2005,
ERR_SwitchNeedsString = 2006,
ERR_BadSwitch = 2007,
WRN_NoSources = 2008,
ERR_OpenResponseFile = 2011,
ERR_CantOpenFileWrite = 2012,
ERR_BadBaseNumber = 2013,
WRN_UseNewSwitch = 2014, //unused but preserved to keep compat with /nowarn:2014
ERR_BinaryFile = 2015,
FTL_BadCodepage = 2016,
ERR_NoMainOnDLL = 2017,
//FTL_NoMessagesDLL = 2018,
FTL_InvalidTarget = 2019,
//ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once!
FTL_InvalidInputFileName = 2021,
//ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once!
WRN_NoConfigNotOnCommandLine = 2023,
ERR_BadFileAlignment = 2024,
//ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn.
//ERR_SourceMapFileBinary = 2027,
WRN_DefineIdentifierRequired = 2029,
//ERR_InvalidSourceMap = 2030,
//ERR_NoSourceMapFile = 2031,
ERR_IllegalOptionChar = 2032,
FTL_OutputFileExists = 2033,
ERR_OneAliasPerReference = 2034,
ERR_SwitchNeedsNumber = 2035,
ERR_MissingDebugSwitch = 2036,
ERR_ComRefCallInExpressionTree = 2037,
WRN_BadUILang = 2038,
WRN_CLS_NoVarArgs = 3000,
WRN_CLS_BadArgType = 3001,
WRN_CLS_BadReturnType = 3002,
WRN_CLS_BadFieldPropType = 3003,
WRN_CLS_BadUnicode = 3004, //unused but preserved to keep compat with /nowarn:3004
WRN_CLS_BadIdentifierCase = 3005,
WRN_CLS_OverloadRefOut = 3006,
WRN_CLS_OverloadUnnamed = 3007,
WRN_CLS_BadIdentifier = 3008,
WRN_CLS_BadBase = 3009,
WRN_CLS_BadInterfaceMember = 3010,
WRN_CLS_NoAbstractMembers = 3011,
WRN_CLS_NotOnModules = 3012,
WRN_CLS_ModuleMissingCLS = 3013,
WRN_CLS_AssemblyNotCLS = 3014,
WRN_CLS_BadAttributeType = 3015,
WRN_CLS_ArrayArgumentToAttribute = 3016,
WRN_CLS_NotOnModules2 = 3017,
WRN_CLS_IllegalTrueInFalse = 3018,
WRN_CLS_MeaninglessOnPrivateType = 3019,
WRN_CLS_AssemblyNotCLS2 = 3021,
WRN_CLS_MeaninglessOnParam = 3022,
WRN_CLS_MeaninglessOnReturn = 3023,
WRN_CLS_BadTypeVar = 3024,
WRN_CLS_VolatileField = 3026,
WRN_CLS_BadInterface = 3027,
// Errors introduced in C# 5 are in the range 4000-4999
// 4000 unused
ERR_BadAwaitArgIntrinsic = 4001,
// 4002 unused
ERR_BadAwaitAsIdentifier = 4003,
ERR_AwaitInUnsafeContext = 4004,
ERR_UnsafeAsyncArgType = 4005,
ERR_VarargsAsync = 4006,
ERR_ByRefTypeAndAwait = 4007,
ERR_BadAwaitArgVoidCall = 4008,
ERR_MainCantBeAsync = 4009,
ERR_CantConvAsyncAnonFuncReturns = 4010,
ERR_BadAwaiterPattern = 4011,
ERR_BadSpecialByRefLocal = 4012,
ERR_SpecialByRefInLambda = 4013,
WRN_UnobservedAwaitableExpression = 4014,
ERR_SynchronizedAsyncMethod = 4015,
ERR_BadAsyncReturnExpression = 4016,
ERR_NoConversionForCallerLineNumberParam = 4017,
ERR_NoConversionForCallerFilePathParam = 4018,
ERR_NoConversionForCallerMemberNameParam = 4019,
ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020,
ERR_BadCallerFilePathParamWithoutDefaultValue = 4021,
ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022,
ERR_BadPrefer32OnLib = 4023,
WRN_CallerLineNumberParamForUnconsumedLocation = 4024,
WRN_CallerFilePathParamForUnconsumedLocation = 4025,
WRN_CallerMemberNameParamForUnconsumedLocation = 4026,
ERR_DoesntImplementAwaitInterface = 4027,
ERR_BadAwaitArg_NeedSystem = 4028,
ERR_CantReturnVoid = 4029,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030,
ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031,
ERR_BadAwaitWithoutAsyncMethod = 4032,
ERR_BadAwaitWithoutVoidAsyncMethod = 4033,
ERR_BadAwaitWithoutAsyncLambda = 4034,
// ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn
ERR_NoSuchMemberOrExtensionNeedUsing = 4036,
WRN_UnknownOption = 5000, //unused in Roslyn
ERR_NoEntryPoint = 5001,
// There is space in the range of error codes from 7000-8999 that
// we can use for new errors in post-Dev10.
ERR_UnexpectedAliasedName = 7000,
ERR_UnexpectedGenericName = 7002,
ERR_UnexpectedUnboundGenericName = 7003,
ERR_GlobalStatement = 7006,
ERR_BadUsingType = 7007,
ERR_ReservedAssemblyName = 7008,
ERR_PPReferenceFollowsToken = 7009,
ERR_ExpectedPPFile = 7010,
ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011,
ERR_NameNotInContextPossibleMissingReference = 7012,
WRN_MetadataNameTooLong = 7013,
ERR_AttributesNotAllowed = 7014,
ERR_ExternAliasNotAllowed = 7015,
ERR_ConflictingAliasAndDefinition = 7016,
ERR_GlobalDefinitionOrStatementExpected = 7017,
ERR_ExpectedSingleScript = 7018,
ERR_RecursivelyTypedVariable = 7019,
ERR_ReturnNotAllowedInScript = 7020,
ERR_NamespaceNotAllowedInScript = 7021,
WRN_MainIgnored = 7022,
ERR_StaticInAsOrIs = 7023,
ERR_InvalidDelegateType = 7024,
ERR_BadVisEventType = 7025,
ERR_GlobalAttributesNotAllowed = 7026,
ERR_PublicKeyFileFailure = 7027,
ERR_PublicKeyContainerFailure = 7028,
ERR_FriendRefSigningMismatch = 7029,
ERR_CannotPassNullForFriendAssembly = 7030,
ERR_SignButNoPrivateKey = 7032,
WRN_DelaySignButNoKey = 7033,
ERR_InvalidVersionFormat = 7034,
WRN_InvalidVersionFormat = 7035,
ERR_NoCorrespondingArgument = 7036,
// Moot: WRN_DestructorIsNotFinalizer = 7037,
ERR_ModuleEmitFailure = 7038,
ERR_NameIllegallyOverrides2 = 7039,
ERR_NameIllegallyOverrides3 = 7040,
ERR_ResourceFileNameNotUnique = 7041,
ERR_DllImportOnGenericMethod = 7042,
ERR_LibraryMethodNotFound = 7043,
ERR_LibraryMethodNotUnique = 7044,
ERR_ParameterNotValidForType = 7045,
ERR_AttributeParameterRequired1 = 7046,
ERR_AttributeParameterRequired2 = 7047,
ERR_SecurityAttributeMissingAction = 7048,
ERR_SecurityAttributeInvalidAction = 7049,
ERR_SecurityAttributeInvalidActionAssembly = 7050,
ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051,
ERR_PrincipalPermissionInvalidAction = 7052,
ERR_FeatureNotValidInExpressionTree = 7053,
ERR_MarshalUnmanagedTypeNotValidForFields = 7054,
ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055,
ERR_PermissionSetAttributeInvalidFile = 7056,
ERR_PermissionSetAttributeFileReadError = 7057,
ERR_InvalidVersionFormat2 = 7058,
ERR_InvalidAssemblyCultureForExe = 7059,
ERR_AsyncBeforeVersionFive = 7060,
ERR_DuplicateAttributeInNetModule = 7061,
//WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning
ERR_CantOpenIcon = 7064,
ERR_ErrorBuildingWin32Resources = 7065,
ERR_IteratorInInteractive = 7066,
ERR_BadAttributeParamDefaultArgument = 7067,
ERR_MissingTypeInSource = 7068,
ERR_MissingTypeInAssembly = 7069,
ERR_SecurityAttributeInvalidTarget = 7070,
ERR_InvalidAssemblyName = 7071,
ERR_PartialTypesBeforeVersionTwo = 7072,
ERR_PartialMethodsBeforeVersionThree = 7073,
ERR_QueryBeforeVersionThree = 7074,
ERR_AnonymousTypeBeforeVersionThree = 7075,
ERR_ImplicitArrayBeforeVersionThree = 7076,
ERR_ObjectInitializerBeforeVersionThree = 7077,
ERR_LambdaBeforeVersionThree = 7078,
ERR_NoTypeDefFromModule = 7079,
WRN_CallerFilePathPreferredOverCallerMemberName = 7080,
WRN_CallerLineNumberPreferredOverCallerMemberName = 7081,
WRN_CallerLineNumberPreferredOverCallerFilePath = 7082,
ERR_InvalidDynamicCondition = 7083,
ERR_WinRtEventPassedByRef = 7084,
ERR_ByRefReturnUnsupported = 7085,
ERR_NetModuleNameMismatch = 7086,
ERR_BadCompilationOption = 7087,
ERR_BadCompilationOptionValue = 7088,
ERR_BadAppConfigPath = 7089,
WRN_AssemblyAttributeFromModuleIsOverridden = 7090,
ERR_CmdOptionConflictsSource = 7091,
ERR_FixedBufferTooManyDimensions = 7092,
ERR_CantReadConfigFile = 7093,
ERR_NotYetImplementedInRoslyn = 8000,
WRN_UnimplementedCommandLineSwitch = 8001,
ERR_ReferencedAssemblyDoesNotHaveStrongName = 8002,
ERR_InvalidSignaturePublicKey = 8003,
ERR_ExportedTypeConflictsWithDeclaration = 8004,
ERR_ExportedTypesConflict = 8005,
ERR_ForwardedTypeConflictsWithDeclaration = 8006,
ERR_ForwardedTypesConflict = 8007,
ERR_ForwardedTypeConflictsWithExportedType = 8008,
WRN_RefCultureMismatch = 8009,
ERR_AgnosticToMachineModule = 8010,
ERR_ConflictingMachineModule = 8011,
WRN_ConflictingMachineAssembly = 8012,
ERR_CryptoHashFailed = 8013,
ERR_MissingNetModuleReference = 8014,
// Values in the range 10000-14000 are used for ""Code Analysis"" issues previously reported by FXCop
WRN_CA2000_DisposeObjectsBeforeLosingScope1 = 10000,
WRN_CA2000_DisposeObjectsBeforeLosingScope2 = 10001,
WRN_CA2202_DoNotDisposeObjectsMultipleTimes = 10002
}
/// <summary>
/// Values for ErrorCode/ERRID that are used internally by the compiler but are not exposed.
/// </summary>
internal static class InternalErrorCode
{
/// <summary>
/// The code has yet to be determined.
/// </summary>
public const int Unknown = -1;
/// <summary>
/// The code was lazily determined and does not need to be reported.
/// </summary>
public const int Void = -2;
}
}
}
";
var compVerifier = CompileAndVerify(text);
compVerifier.VerifyIL("ConsoleApplication24.Program.IsWarning", @"
{
// Code size 1889 (0x761)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x32b
IL_0006: bgt IL_0300
IL_000b: ldarg.0
IL_000c: ldc.i4 0x1ad
IL_0011: bgt IL_0154
IL_0016: ldarg.0
IL_0017: ldc.i4 0xb8
IL_001c: bgt IL_00a9
IL_0021: ldarg.0
IL_0022: ldc.i4.s 109
IL_0024: bgt.s IL_005f
IL_0026: ldarg.0
IL_0027: ldc.i4.s 67
IL_0029: bgt.s IL_0040
IL_002b: ldarg.0
IL_002c: ldc.i4.s 28
IL_002e: beq IL_075d
IL_0033: ldarg.0
IL_0034: ldc.i4.s 67
IL_0036: beq IL_075d
IL_003b: br IL_075f
IL_0040: ldarg.0
IL_0041: ldc.i4.s 78
IL_0043: beq IL_075d
IL_0048: ldarg.0
IL_0049: ldc.i4.s 105
IL_004b: beq IL_075d
IL_0050: ldarg.0
IL_0051: ldc.i4.s 108
IL_0053: sub
IL_0054: ldc.i4.1
IL_0055: ble.un IL_075d
IL_005a: br IL_075f
IL_005f: ldarg.0
IL_0060: ldc.i4 0xa2
IL_0065: bgt.s IL_007f
IL_0067: ldarg.0
IL_0068: ldc.i4.s 114
IL_006a: beq IL_075d
IL_006f: ldarg.0
IL_0070: ldc.i4 0xa2
IL_0075: beq IL_075d
IL_007a: br IL_075f
IL_007f: ldarg.0
IL_0080: ldc.i4 0xa4
IL_0085: beq IL_075d
IL_008a: ldarg.0
IL_008b: ldc.i4 0xa8
IL_0090: sub
IL_0091: ldc.i4.1
IL_0092: ble.un IL_075d
IL_0097: ldarg.0
IL_0098: ldc.i4 0xb7
IL_009d: sub
IL_009e: ldc.i4.1
IL_009f: ble.un IL_075d
IL_00a4: br IL_075f
IL_00a9: ldarg.0
IL_00aa: ldc.i4 0x118
IL_00af: bgt.s IL_00fe
IL_00b1: ldarg.0
IL_00b2: ldc.i4 0xcf
IL_00b7: bgt.s IL_00d4
IL_00b9: ldarg.0
IL_00ba: ldc.i4 0xc5
IL_00bf: beq IL_075d
IL_00c4: ldarg.0
IL_00c5: ldc.i4 0xcf
IL_00ca: beq IL_075d
IL_00cf: br IL_075f
IL_00d4: ldarg.0
IL_00d5: ldc.i4 0xdb
IL_00da: beq IL_075d
IL_00df: ldarg.0
IL_00e0: ldc.i4 0xfb
IL_00e5: sub
IL_00e6: ldc.i4.2
IL_00e7: ble.un IL_075d
IL_00ec: ldarg.0
IL_00ed: ldc.i4 0x116
IL_00f2: sub
IL_00f3: ldc.i4.2
IL_00f4: ble.un IL_075d
IL_00f9: br IL_075f
IL_00fe: ldarg.0
IL_00ff: ldc.i4 0x19e
IL_0104: bgt.s IL_012c
IL_0106: ldarg.0
IL_0107: ldc.i4 0x11a
IL_010c: beq IL_075d
IL_0111: ldarg.0
IL_0112: ldc.i4 0x192
IL_0117: beq IL_075d
IL_011c: ldarg.0
IL_011d: ldc.i4 0x19e
IL_0122: beq IL_075d
IL_0127: br IL_075f
IL_012c: ldarg.0
IL_012d: ldc.i4 0x1a3
IL_0132: sub
IL_0133: ldc.i4.1
IL_0134: ble.un IL_075d
IL_0139: ldarg.0
IL_013a: ldc.i4 0x1a6
IL_013f: beq IL_075d
IL_0144: ldarg.0
IL_0145: ldc.i4 0x1ad
IL_014a: beq IL_075d
IL_014f: br IL_075f
IL_0154: ldarg.0
IL_0155: ldc.i4 0x274
IL_015a: bgt IL_0224
IL_015f: ldarg.0
IL_0160: ldc.i4 0x1d9
IL_0165: bgt.s IL_01db
IL_0167: ldarg.0
IL_0168: ldc.i4 0x1b8
IL_016d: bgt.s IL_018c
IL_016f: ldarg.0
IL_0170: ldc.i4 0x1b3
IL_0175: sub
IL_0176: ldc.i4.2
IL_0177: ble.un IL_075d
IL_017c: ldarg.0
IL_017d: ldc.i4 0x1b8
IL_0182: beq IL_075d
IL_0187: br IL_075f
IL_018c: ldarg.0
IL_018d: ldc.i4 0x1bc
IL_0192: beq IL_075d
IL_0197: ldarg.0
IL_0198: ldc.i4 0x1ca
IL_019d: beq IL_075d
IL_01a2: ldarg.0
IL_01a3: ldc.i4 0x1d0
IL_01a8: sub
IL_01a9: switch (
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075d)
IL_01d6: br IL_075f
IL_01db: ldarg.0
IL_01dc: ldc.i4 0x264
IL_01e1: bgt.s IL_01fe
IL_01e3: ldarg.0
IL_01e4: ldc.i4 0x25a
IL_01e9: beq IL_075d
IL_01ee: ldarg.0
IL_01ef: ldc.i4 0x264
IL_01f4: beq IL_075d
IL_01f9: br IL_075f
IL_01fe: ldarg.0
IL_01ff: ldc.i4 0x26a
IL_0204: beq IL_075d
IL_0209: ldarg.0
IL_020a: ldc.i4 0x272
IL_020f: beq IL_075d
IL_0214: ldarg.0
IL_0215: ldc.i4 0x274
IL_021a: beq IL_075d
IL_021f: br IL_075f
IL_0224: ldarg.0
IL_0225: ldc.i4 0x2a3
IL_022a: bgt.s IL_02aa
IL_022c: ldarg.0
IL_022d: ldc.i4 0x295
IL_0232: bgt.s IL_0284
IL_0234: ldarg.0
IL_0235: ldc.i4 0x282
IL_023a: beq IL_075d
IL_023f: ldarg.0
IL_0240: ldc.i4 0x289
IL_0245: sub
IL_0246: switch (
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d)
IL_027f: br IL_075f
IL_0284: ldarg.0
IL_0285: ldc.i4 0x299
IL_028a: beq IL_075d
IL_028f: ldarg.0
IL_0290: ldc.i4 0x2a0
IL_0295: beq IL_075d
IL_029a: ldarg.0
IL_029b: ldc.i4 0x2a3
IL_02a0: beq IL_075d
IL_02a5: br IL_075f
IL_02aa: ldarg.0
IL_02ab: ldc.i4 0x2b5
IL_02b0: bgt.s IL_02da
IL_02b2: ldarg.0
IL_02b3: ldc.i4 0x2a7
IL_02b8: sub
IL_02b9: ldc.i4.1
IL_02ba: ble.un IL_075d
IL_02bf: ldarg.0
IL_02c0: ldc.i4 0x2ac
IL_02c5: beq IL_075d
IL_02ca: ldarg.0
IL_02cb: ldc.i4 0x2b5
IL_02d0: beq IL_075d
IL_02d5: br IL_075f
IL_02da: ldarg.0
IL_02db: ldc.i4 0x2d8
IL_02e0: beq IL_075d
IL_02e5: ldarg.0
IL_02e6: ldc.i4 0x329
IL_02eb: beq IL_075d
IL_02f0: ldarg.0
IL_02f1: ldc.i4 0x32b
IL_02f6: beq IL_075d
IL_02fb: br IL_075f
IL_0300: ldarg.0
IL_0301: ldc.i4 0x7bd
IL_0306: bgt IL_05d1
IL_030b: ldarg.0
IL_030c: ldc.i4 0x663
IL_0311: bgt IL_0451
IL_0316: ldarg.0
IL_0317: ldc.i4 0x5f2
IL_031c: bgt.s IL_038e
IL_031e: ldarg.0
IL_031f: ldc.i4 0x406
IL_0324: bgt.s IL_0341
IL_0326: ldarg.0
IL_0327: ldc.i4 0x338
IL_032c: beq IL_075d
IL_0331: ldarg.0
IL_0332: ldc.i4 0x406
IL_0337: beq IL_075d
IL_033c: br IL_075f
IL_0341: ldarg.0
IL_0342: ldc.i4 0x422
IL_0347: sub
IL_0348: switch (
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075d)
IL_0371: ldarg.0
IL_0372: ldc.i4 0x4b0
IL_0377: sub
IL_0378: ldc.i4.4
IL_0379: ble.un IL_075d
IL_037e: ldarg.0
IL_037f: ldc.i4 0x5f2
IL_0384: beq IL_075d
IL_0389: br IL_075f
IL_038e: ldarg.0
IL_038f: ldc.i4 0x647
IL_0394: bgt IL_0429
IL_0399: ldarg.0
IL_039a: ldc.i4 0x622
IL_039f: sub
IL_03a0: switch (
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075f,
IL_075d)
IL_0419: ldarg.0
IL_041a: ldc.i4 0x647
IL_041f: beq IL_075d
IL_0424: br IL_075f
IL_0429: ldarg.0
IL_042a: ldc.i4 0x64a
IL_042f: beq IL_075d
IL_0434: ldarg.0
IL_0435: ldc.i4 0x650
IL_043a: beq IL_075d
IL_043f: ldarg.0
IL_0440: ldc.i4 0x661
IL_0445: sub
IL_0446: ldc.i4.2
IL_0447: ble.un IL_075d
IL_044c: br IL_075f
IL_0451: ldarg.0
IL_0452: ldc.i4 0x6c7
IL_0457: bgt IL_057b
IL_045c: ldarg.0
IL_045d: ldc.i4 0x67b
IL_0462: bgt.s IL_0481
IL_0464: ldarg.0
IL_0465: ldc.i4 0x66d
IL_046a: beq IL_075d
IL_046f: ldarg.0
IL_0470: ldc.i4 0x67a
IL_0475: sub
IL_0476: ldc.i4.1
IL_0477: ble.un IL_075d
IL_047c: br IL_075f
IL_0481: ldarg.0
IL_0482: ldc.i4 0x684
IL_0487: sub
IL_0488: switch (
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075f,
IL_075f,
IL_075f,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d)
IL_0541: ldarg.0
IL_0542: ldc.i4 0x6b5
IL_0547: sub
IL_0548: switch (
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075f,
IL_075f,
IL_075d)
IL_0569: ldarg.0
IL_056a: ldc.i4 0x6c6
IL_056f: sub
IL_0570: ldc.i4.1
IL_0571: ble.un IL_075d
IL_0576: br IL_075f
IL_057b: ldarg.0
IL_057c: ldc.i4 0x787
IL_0581: bgt.s IL_05a9
IL_0583: ldarg.0
IL_0584: ldc.i4 0x6e2
IL_0589: beq IL_075d
IL_058e: ldarg.0
IL_058f: ldc.i4 0x6e5
IL_0594: beq IL_075d
IL_0599: ldarg.0
IL_059a: ldc.i4 0x787
IL_059f: beq IL_075d
IL_05a4: br IL_075f
IL_05a9: ldarg.0
IL_05aa: ldc.i4 0x7a4
IL_05af: sub
IL_05b0: ldc.i4.1
IL_05b1: ble.un IL_075d
IL_05b6: ldarg.0
IL_05b7: ldc.i4 0x7b6
IL_05bc: beq IL_075d
IL_05c1: ldarg.0
IL_05c2: ldc.i4 0x7bd
IL_05c7: beq IL_075d
IL_05cc: br IL_075f
IL_05d1: ldarg.0
IL_05d2: ldc.i4 0xfba
IL_05d7: bgt IL_06e3
IL_05dc: ldarg.0
IL_05dd: ldc.i4 0x7e7
IL_05e2: bgt.s IL_062d
IL_05e4: ldarg.0
IL_05e5: ldc.i4 0x7d2
IL_05ea: bgt.s IL_0607
IL_05ec: ldarg.0
IL_05ed: ldc.i4 0x7ce
IL_05f2: beq IL_075d
IL_05f7: ldarg.0
IL_05f8: ldc.i4 0x7d2
IL_05fd: beq IL_075d
IL_0602: br IL_075f
IL_0607: ldarg.0
IL_0608: ldc.i4 0x7d8
IL_060d: beq IL_075d
IL_0612: ldarg.0
IL_0613: ldc.i4 0x7de
IL_0618: beq IL_075d
IL_061d: ldarg.0
IL_061e: ldc.i4 0x7e7
IL_0623: beq IL_075d
IL_0628: br IL_075f
IL_062d: ldarg.0
IL_062e: ldc.i4 0x7f6
IL_0633: bgt.s IL_0650
IL_0635: ldarg.0
IL_0636: ldc.i4 0x7ed
IL_063b: beq IL_075d
IL_0640: ldarg.0
IL_0641: ldc.i4 0x7f6
IL_0646: beq IL_075d
IL_064b: br IL_075f
IL_0650: ldarg.0
IL_0651: ldc.i4 0xbb8
IL_0656: sub
IL_0657: switch (
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075d,
IL_075d,
IL_075d,
IL_075f,
IL_075d,
IL_075d)
IL_06cc: ldarg.0
IL_06cd: ldc.i4 0xfae
IL_06d2: beq IL_075d
IL_06d7: ldarg.0
IL_06d8: ldc.i4 0xfb8
IL_06dd: sub
IL_06de: ldc.i4.2
IL_06df: ble.un.s IL_075d
IL_06e1: br.s IL_075f
IL_06e3: ldarg.0
IL_06e4: ldc.i4 0x1b7b
IL_06e9: bgt.s IL_071f
IL_06eb: ldarg.0
IL_06ec: ldc.i4 0x1b65
IL_06f1: bgt.s IL_0705
IL_06f3: ldarg.0
IL_06f4: ldc.i4 0x1388
IL_06f9: beq.s IL_075d
IL_06fb: ldarg.0
IL_06fc: ldc.i4 0x1b65
IL_0701: beq.s IL_075d
IL_0703: br.s IL_075f
IL_0705: ldarg.0
IL_0706: ldc.i4 0x1b6e
IL_070b: beq.s IL_075d
IL_070d: ldarg.0
IL_070e: ldc.i4 0x1b79
IL_0713: beq.s IL_075d
IL_0715: ldarg.0
IL_0716: ldc.i4 0x1b7b
IL_071b: beq.s IL_075d
IL_071d: br.s IL_075f
IL_071f: ldarg.0
IL_0720: ldc.i4 0x1f41
IL_0725: bgt.s IL_0743
IL_0727: ldarg.0
IL_0728: ldc.i4 0x1ba8
IL_072d: sub
IL_072e: ldc.i4.2
IL_072f: ble.un.s IL_075d
IL_0731: ldarg.0
IL_0732: ldc.i4 0x1bb2
IL_0737: beq.s IL_075d
IL_0739: ldarg.0
IL_073a: ldc.i4 0x1f41
IL_073f: beq.s IL_075d
IL_0741: br.s IL_075f
IL_0743: ldarg.0
IL_0744: ldc.i4 0x1f49
IL_0749: beq.s IL_075d
IL_074b: ldarg.0
IL_074c: ldc.i4 0x1f4c
IL_0751: beq.s IL_075d
IL_0753: ldarg.0
IL_0754: ldc.i4 0x2710
IL_0759: sub
IL_075a: ldc.i4.2
IL_075b: bgt.un.s IL_075f
IL_075d: ldc.i4.1
IL_075e: ret
IL_075f: ldc.i4.0
IL_0760: ret
}");
}
[Fact]
public void StringSwitch()
{
var text = @"using System;
public class Test
{
public static void Main()
{
Console.WriteLine(M(""Orange""));
}
public static int M(string s)
{
switch (s)
{
case ""Black"": return 0;
case ""Brown"": return 1;
case ""Red"": return 2;
case ""Orange"": return 3;
case ""Yellow"": return 4;
case ""Green"": return 5;
case ""Blue"": return 6;
case ""Violet"": return 7;
case ""Grey"": case ""Gray"": return 8;
case ""White"": return 9;
default: throw new ArgumentException(s);
}
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "3");
compVerifier.VerifyIL("Test.M", @"
{
// Code size 368 (0x170)
.maxstack 2
.locals init (uint V_0)
IL_0000: ldarg.0
IL_0001: call ""ComputeStringHash""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x6ceb2d06
IL_000d: bgt.un.s IL_0055
IL_000f: ldloc.0
IL_0010: ldc.i4 0x2b043744
IL_0015: bgt.un.s IL_002f
IL_0017: ldloc.0
IL_0018: ldc.i4 0x2b8b9cf
IL_001d: beq IL_00b2
IL_0022: ldloc.0
IL_0023: ldc.i4 0x2b043744
IL_0028: beq.s IL_009d
IL_002a: br IL_0169
IL_002f: ldloc.0
IL_0030: ldc.i4 0x32bdf8c6
IL_0035: beq IL_0127
IL_003a: ldloc.0
IL_003b: ldc.i4 0x3ac6ffba
IL_0040: beq IL_0136
IL_0045: ldloc.0
IL_0046: ldc.i4 0x6ceb2d06
IL_004b: beq IL_0145
IL_0050: br IL_0169
IL_0055: ldloc.0
IL_0056: ldc.i4 0xa953c75c
IL_005b: bgt.un.s IL_007d
IL_005d: ldloc.0
IL_005e: ldc.i4 0x727b390b
IL_0063: beq.s IL_00dc
IL_0065: ldloc.0
IL_0066: ldc.i4 0xa37f187c
IL_006b: beq.s IL_00c7
IL_006d: ldloc.0
IL_006e: ldc.i4 0xa953c75c
IL_0073: beq IL_00fa
IL_0078: br IL_0169
IL_007d: ldloc.0
IL_007e: ldc.i4 0xd9cdec69
IL_0083: beq.s IL_00eb
IL_0085: ldloc.0
IL_0086: ldc.i4 0xe9dd1fed
IL_008b: beq.s IL_0109
IL_008d: ldloc.0
IL_008e: ldc.i4 0xf03bdf12
IL_0093: beq IL_0118
IL_0098: br IL_0169
IL_009d: ldarg.0
IL_009e: ldstr ""Black""
IL_00a3: call ""bool string.op_Equality(string, string)""
IL_00a8: brtrue IL_0154
IL_00ad: br IL_0169
IL_00b2: ldarg.0
IL_00b3: ldstr ""Brown""
IL_00b8: call ""bool string.op_Equality(string, string)""
IL_00bd: brtrue IL_0156
IL_00c2: br IL_0169
IL_00c7: ldarg.0
IL_00c8: ldstr ""Red""
IL_00cd: call ""bool string.op_Equality(string, string)""
IL_00d2: brtrue IL_0158
IL_00d7: br IL_0169
IL_00dc: ldarg.0
IL_00dd: ldstr ""Orange""
IL_00e2: call ""bool string.op_Equality(string, string)""
IL_00e7: brtrue.s IL_015a
IL_00e9: br.s IL_0169
IL_00eb: ldarg.0
IL_00ec: ldstr ""Yellow""
IL_00f1: call ""bool string.op_Equality(string, string)""
IL_00f6: brtrue.s IL_015c
IL_00f8: br.s IL_0169
IL_00fa: ldarg.0
IL_00fb: ldstr ""Green""
IL_0100: call ""bool string.op_Equality(string, string)""
IL_0105: brtrue.s IL_015e
IL_0107: br.s IL_0169
IL_0109: ldarg.0
IL_010a: ldstr ""Blue""
IL_010f: call ""bool string.op_Equality(string, string)""
IL_0114: brtrue.s IL_0160
IL_0116: br.s IL_0169
IL_0118: ldarg.0
IL_0119: ldstr ""Violet""
IL_011e: call ""bool string.op_Equality(string, string)""
IL_0123: brtrue.s IL_0162
IL_0125: br.s IL_0169
IL_0127: ldarg.0
IL_0128: ldstr ""Grey""
IL_012d: call ""bool string.op_Equality(string, string)""
IL_0132: brtrue.s IL_0164
IL_0134: br.s IL_0169
IL_0136: ldarg.0
IL_0137: ldstr ""Gray""
IL_013c: call ""bool string.op_Equality(string, string)""
IL_0141: brtrue.s IL_0164
IL_0143: br.s IL_0169
IL_0145: ldarg.0
IL_0146: ldstr ""White""
IL_014b: call ""bool string.op_Equality(string, string)""
IL_0150: brtrue.s IL_0166
IL_0152: br.s IL_0169
IL_0154: ldc.i4.0
IL_0155: ret
IL_0156: ldc.i4.1
IL_0157: ret
IL_0158: ldc.i4.2
IL_0159: ret
IL_015a: ldc.i4.3
IL_015b: ret
IL_015c: ldc.i4.4
IL_015d: ret
IL_015e: ldc.i4.5
IL_015f: ret
IL_0160: ldc.i4.6
IL_0161: ret
IL_0162: ldc.i4.7
IL_0163: ret
IL_0164: ldc.i4.8
IL_0165: ret
IL_0166: ldc.i4.s 9
IL_0168: ret
IL_0169: ldarg.0
IL_016a: newobj ""System.ArgumentException..ctor(string)""
IL_016f: throw
}");
}
#endregion
# region "Data flow analysis tests"
[Fact]
public void DefiniteAssignmentOnAllControlPaths()
{
var text = @"using System;
class SwitchTest
{
public static int Main()
{
int n = 3;
int goo; // unassigned goo
switch (n)
{
case 1:
case 2:
goo = n;
break;
case 3:
default:
goo = 0;
break;
}
Console.Write(goo); // goo must be definitely assigned here
return goo;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("SwitchTest.Main", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (int V_0, //n
int V_1) //goo
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.1
IL_0004: sub
IL_0005: ldc.i4.1
IL_0006: ble.un.s IL_000e
IL_0008: ldloc.0
IL_0009: ldc.i4.3
IL_000a: beq.s IL_0012
IL_000c: br.s IL_0012
IL_000e: ldloc.0
IL_000f: stloc.1
IL_0010: br.s IL_0014
IL_0012: ldc.i4.0
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: call ""void System.Console.Write(int)""
IL_001a: ldloc.1
IL_001b: ret
}"
);
}
[Fact]
public void ComplexControlFlow_DefiniteAssignmentOnAllControlPaths()
{
var text = @"using System;
class SwitchTest
{
public static int Main()
{
int n = 3;
int cost = 0;
int goo; // unassigned goo
switch (n)
{
case 1:
cost = 1;
goo = n;
break;
case 2:
cost = 2;
goto case 1;
case 3:
cost = 3;
if(cost > n)
{
goo = n - 1;
}
else
{
goto case 2;
}
break;
default:
cost = 4;
goo = n - 1;
break;
}
if (goo != n) // goo must be reported as definitely assigned
{
Console.Write(goo);
}
else
{
--cost;
}
Console.Write(cost); // should output 0
return cost;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyIL("SwitchTest.Main",
@"{
// Code size 78 (0x4e)
.maxstack 2
.locals init (int V_0, //n
int V_1, //cost
int V_2) //goo
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: ldc.i4.1
IL_0006: sub
IL_0007: switch (
IL_001a,
IL_0020,
IL_0024)
IL_0018: br.s IL_0030
IL_001a: ldc.i4.1
IL_001b: stloc.1
IL_001c: ldloc.0
IL_001d: stloc.2
IL_001e: br.s IL_0036
IL_0020: ldc.i4.2
IL_0021: stloc.1
IL_0022: br.s IL_001a
IL_0024: ldc.i4.3
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldloc.0
IL_0028: ble.s IL_0020
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: sub
IL_002d: stloc.2
IL_002e: br.s IL_0036
IL_0030: ldc.i4.4
IL_0031: stloc.1
IL_0032: ldloc.0
IL_0033: ldc.i4.1
IL_0034: sub
IL_0035: stloc.2
IL_0036: ldloc.2
IL_0037: ldloc.0
IL_0038: beq.s IL_0042
IL_003a: ldloc.2
IL_003b: call ""void System.Console.Write(int)""
IL_0040: br.s IL_0046
IL_0042: ldloc.1
IL_0043: ldc.i4.1
IL_0044: sub
IL_0045: stloc.1
IL_0046: ldloc.1
IL_0047: call ""void System.Console.Write(int)""
IL_004c: ldloc.1
IL_004d: ret
}"
);
}
[Fact]
public void ComplexControlFlow_NoAssignmentOnlyOnUnreachableControlPaths()
{
var text = @"using System;
class SwitchTest
{
public static int Main()
{
int goo; // unassigned goo
switch (3)
{
case 1:
mylabel:
try
{
throw new System.ApplicationException();
}
catch(Exception)
{
goo = 0;
}
break;
case 2:
goto mylabel;
case 3:
if (true)
{
goto case 2;
}
break;
case 4:
break;
}
Console.Write(goo); // goo should be definitely assigned here
return goo;
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (27,17): warning CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break"),
// (29,17): warning CS0162: Unreachable code detected
// break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "break"));
compVerifier.VerifyIL("SwitchTest.Main", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int V_0) //goo
IL_0000: nop
.try
{
IL_0001: newobj ""System.ApplicationException..ctor()""
IL_0006: throw
}
catch System.Exception
{
IL_0007: pop
IL_0008: ldc.i4.0
IL_0009: stloc.0
IL_000a: leave.s IL_000c
}
IL_000c: ldloc.0
IL_000d: call ""void System.Console.Write(int)""
IL_0012: ldloc.0
IL_0013: ret
}"
);
}
#endregion
#region "Control flow analysis and warning tests"
[Fact]
public void CS0469_NoImplicitConversionWarning()
{
var text = @"using System;
class A
{
static void Goo(DayOfWeek x)
{
switch (x)
{
case DayOfWeek.Monday:
goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek'
}
}
static void Main() {}
}
";
var compVerifier = CompileAndVerify(text);
compVerifier.VerifyDiagnostics(
// (10,17): warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek'
// goto case 1; // warning CS0469: The 'goto case' value is not implicitly convertible to type 'System.DayOfWeek'
Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 1;").WithArguments("System.DayOfWeek"));
compVerifier.VerifyIL("A.Goo", @"
{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: bne.un.s IL_0006
IL_0004: br.s IL_0004
IL_0006: ret
}"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_01()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 2;
switch (true)
{
case true:
ret = 0;
break;
case false: // unreachable case label
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (14,8): warning CS0162: Unreachable code detected
// ret = 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "ret"));
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //ret
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call ""void System.Console.Write(int)""
IL_000a: ldloc.0
IL_000b: ret
}
"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_02()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 1;
switch (true)
{
default: // unreachable default label
ret = 1;
break;
case true:
ret = 0;
break;
}
Console.Write(ret);
return(ret);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (11,17): warning CS0162: Unreachable code detected
// ret = 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 17)
);
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //ret
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call ""void System.Console.Write(int)""
IL_000a: ldloc.0
IL_000b: ret
}"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_03()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = M();
Console.Write(ret);
return(ret);
}
public static int M()
{
switch (1)
{
case 1:
return 0;
}
return 1; // unreachable code
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (19,5): warning CS0162: Unreachable code detected
// return 1; // unreachable code
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(19, 5));
compVerifier.VerifyIL("Test.M", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}"
);
}
[Fact]
public void CS0162_UnreachableCodeInSwitchCase_04()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
switch (1) // no matching case/default label
{
case 2: // unreachable code
ret = 1;
break;
}
Console.Write(ret);
return(ret);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (11,9): warning CS0162: Unreachable code detected
// ret = 1;
Diagnostic(ErrorCode.WRN_UnreachableCode, "ret").WithLocation(11, 9)
);
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0) //ret
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: call ""void System.Console.Write(int)""
IL_0008: ldloc.0
IL_0009: ret
}"
);
}
[Fact]
public void CS1522_EmptySwitch()
{
var text = @"using System;
public class Test
{
public static int Main(string [] args)
{
int ret = 0;
switch (true) {
}
Console.Write(ret);
return(0);
}
}";
var compVerifier = CompileAndVerify(text, expectedOutput: "0");
compVerifier.VerifyDiagnostics(
// (7,23): warning CS1522: Empty switch block
// switch (true) {
Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 23)
);
compVerifier.VerifyIL("Test.Main", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ldc.i4.0
IL_0007: ret
}"
);
}
[WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")]
[Fact]
public void DifferentStrategiesForDifferentSwitches()
{
var text = @"
using System;
public class Test
{
public static void Main(string [] args)
{
switch(args[0])
{
case ""A"": Console.Write(1); break;
}
switch(args[1])
{
case ""B"": Console.Write(2); break;
case ""C"": Console.Write(3); break;
case ""D"": Console.Write(4); break;
case ""E"": Console.Write(5); break;
case ""F"": Console.Write(6); break;
case ""G"": Console.Write(7); break;
case ""H"": Console.Write(8); break;
case ""I"": Console.Write(9); break;
case ""J"": Console.Write(10); break;
}
}
}";
var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
CompileAndVerify(comp).VerifyIL("Test.Main", @"
{
// Code size 326 (0x146)
.maxstack 2
.locals init (string V_0,
uint V_1)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: ldstr ""A""
IL_0008: call ""bool string.op_Equality(string, string)""
IL_000d: brfalse.s IL_0015
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ldarg.0
IL_0016: ldc.i4.1
IL_0017: ldelem.ref
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: call ""ComputeStringHash""
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldc.i4 0xc30bf539
IL_0026: bgt.un.s IL_0055
IL_0028: ldloc.1
IL_0029: ldc.i4 0xc10bf213
IL_002e: bgt.un.s IL_0041
IL_0030: ldloc.1
IL_0031: ldc.i4 0xc00bf080
IL_0036: beq.s IL_00b1
IL_0038: ldloc.1
IL_0039: ldc.i4 0xc10bf213
IL_003e: beq.s IL_00a3
IL_0040: ret
IL_0041: ldloc.1
IL_0042: ldc.i4 0xc20bf3a6
IL_0047: beq IL_00cd
IL_004c: ldloc.1
IL_004d: ldc.i4 0xc30bf539
IL_0052: beq.s IL_00bf
IL_0054: ret
IL_0055: ldloc.1
IL_0056: ldc.i4 0xc70bfb85
IL_005b: bgt.un.s IL_006e
IL_005d: ldloc.1
IL_005e: ldc.i4 0xc60bf9f2
IL_0063: beq.s IL_0095
IL_0065: ldloc.1
IL_0066: ldc.i4 0xc70bfb85
IL_006b: beq.s IL_0087
IL_006d: ret
IL_006e: ldloc.1
IL_006f: ldc.i4 0xcc0c0364
IL_0074: beq.s IL_00e9
IL_0076: ldloc.1
IL_0077: ldc.i4 0xcd0c04f7
IL_007c: beq.s IL_00db
IL_007e: ldloc.1
IL_007f: ldc.i4 0xcf0c081d
IL_0084: beq.s IL_00f7
IL_0086: ret
IL_0087: ldloc.0
IL_0088: ldstr ""B""
IL_008d: call ""bool string.op_Equality(string, string)""
IL_0092: brtrue.s IL_0105
IL_0094: ret
IL_0095: ldloc.0
IL_0096: ldstr ""C""
IL_009b: call ""bool string.op_Equality(string, string)""
IL_00a0: brtrue.s IL_010c
IL_00a2: ret
IL_00a3: ldloc.0
IL_00a4: ldstr ""D""
IL_00a9: call ""bool string.op_Equality(string, string)""
IL_00ae: brtrue.s IL_0113
IL_00b0: ret
IL_00b1: ldloc.0
IL_00b2: ldstr ""E""
IL_00b7: call ""bool string.op_Equality(string, string)""
IL_00bc: brtrue.s IL_011a
IL_00be: ret
IL_00bf: ldloc.0
IL_00c0: ldstr ""F""
IL_00c5: call ""bool string.op_Equality(string, string)""
IL_00ca: brtrue.s IL_0121
IL_00cc: ret
IL_00cd: ldloc.0
IL_00ce: ldstr ""G""
IL_00d3: call ""bool string.op_Equality(string, string)""
IL_00d8: brtrue.s IL_0128
IL_00da: ret
IL_00db: ldloc.0
IL_00dc: ldstr ""H""
IL_00e1: call ""bool string.op_Equality(string, string)""
IL_00e6: brtrue.s IL_012f
IL_00e8: ret
IL_00e9: ldloc.0
IL_00ea: ldstr ""I""
IL_00ef: call ""bool string.op_Equality(string, string)""
IL_00f4: brtrue.s IL_0136
IL_00f6: ret
IL_00f7: ldloc.0
IL_00f8: ldstr ""J""
IL_00fd: call ""bool string.op_Equality(string, string)""
IL_0102: brtrue.s IL_013e
IL_0104: ret
IL_0105: ldc.i4.2
IL_0106: call ""void System.Console.Write(int)""
IL_010b: ret
IL_010c: ldc.i4.3
IL_010d: call ""void System.Console.Write(int)""
IL_0112: ret
IL_0113: ldc.i4.4
IL_0114: call ""void System.Console.Write(int)""
IL_0119: ret
IL_011a: ldc.i4.5
IL_011b: call ""void System.Console.Write(int)""
IL_0120: ret
IL_0121: ldc.i4.6
IL_0122: call ""void System.Console.Write(int)""
IL_0127: ret
IL_0128: ldc.i4.7
IL_0129: call ""void System.Console.Write(int)""
IL_012e: ret
IL_012f: ldc.i4.8
IL_0130: call ""void System.Console.Write(int)""
IL_0135: ret
IL_0136: ldc.i4.s 9
IL_0138: call ""void System.Console.Write(int)""
IL_013d: ret
IL_013e: ldc.i4.s 10
IL_0140: call ""void System.Console.Write(int)""
IL_0145: ret
}");
}
[WorkItem(634404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634404")]
[WorkItem(913556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913556")]
[Fact]
public void LargeStringSwitchWithoutStringChars()
{
var text = @"
using System;
public class Test
{
public static void Main(string [] args)
{
switch(args[0])
{
case ""A"": Console.Write(1); break;
case ""B"": Console.Write(2); break;
case ""C"": Console.Write(3); break;
case ""D"": Console.Write(4); break;
case ""E"": Console.Write(5); break;
case ""F"": Console.Write(6); break;
case ""G"": Console.Write(7); break;
case ""H"": Console.Write(8); break;
case ""I"": Console.Write(9); break;
}
}
}";
var comp = CreateCompilation(text, options: TestOptions.ReleaseExe.WithModuleName("MODULE"));
// With special members available, we use a hashtable approach.
CompileAndVerify(comp).VerifyIL("Test.Main", @"
{
// Code size 307 (0x133)
.maxstack 2
.locals init (string V_0,
uint V_1)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: call ""ComputeStringHash""
IL_000a: stloc.1
IL_000b: ldloc.1
IL_000c: ldc.i4 0xc30bf539
IL_0011: bgt.un.s IL_0043
IL_0013: ldloc.1
IL_0014: ldc.i4 0xc10bf213
IL_0019: bgt.un.s IL_002f
IL_001b: ldloc.1
IL_001c: ldc.i4 0xc00bf080
IL_0021: beq IL_00ad
IL_0026: ldloc.1
IL_0027: ldc.i4 0xc10bf213
IL_002c: beq.s IL_009f
IL_002e: ret
IL_002f: ldloc.1
IL_0030: ldc.i4 0xc20bf3a6
IL_0035: beq IL_00c9
IL_003a: ldloc.1
IL_003b: ldc.i4 0xc30bf539
IL_0040: beq.s IL_00bb
IL_0042: ret
IL_0043: ldloc.1
IL_0044: ldc.i4 0xc60bf9f2
IL_0049: bgt.un.s IL_005c
IL_004b: ldloc.1
IL_004c: ldc.i4 0xc40bf6cc
IL_0051: beq.s IL_0075
IL_0053: ldloc.1
IL_0054: ldc.i4 0xc60bf9f2
IL_0059: beq.s IL_0091
IL_005b: ret
IL_005c: ldloc.1
IL_005d: ldc.i4 0xc70bfb85
IL_0062: beq.s IL_0083
IL_0064: ldloc.1
IL_0065: ldc.i4 0xcc0c0364
IL_006a: beq.s IL_00e5
IL_006c: ldloc.1
IL_006d: ldc.i4 0xcd0c04f7
IL_0072: beq.s IL_00d7
IL_0074: ret
IL_0075: ldloc.0
IL_0076: ldstr ""A""
IL_007b: call ""bool string.op_Equality(string, string)""
IL_0080: brtrue.s IL_00f3
IL_0082: ret
IL_0083: ldloc.0
IL_0084: ldstr ""B""
IL_0089: call ""bool string.op_Equality(string, string)""
IL_008e: brtrue.s IL_00fa
IL_0090: ret
IL_0091: ldloc.0
IL_0092: ldstr ""C""
IL_0097: call ""bool string.op_Equality(string, string)""
IL_009c: brtrue.s IL_0101
IL_009e: ret
IL_009f: ldloc.0
IL_00a0: ldstr ""D""
IL_00a5: call ""bool string.op_Equality(string, string)""
IL_00aa: brtrue.s IL_0108
IL_00ac: ret
IL_00ad: ldloc.0
IL_00ae: ldstr ""E""
IL_00b3: call ""bool string.op_Equality(string, string)""
IL_00b8: brtrue.s IL_010f
IL_00ba: ret
IL_00bb: ldloc.0
IL_00bc: ldstr ""F""
IL_00c1: call ""bool string.op_Equality(string, string)""
IL_00c6: brtrue.s IL_0116
IL_00c8: ret
IL_00c9: ldloc.0
IL_00ca: ldstr ""G""
IL_00cf: call ""bool string.op_Equality(string, string)""
IL_00d4: brtrue.s IL_011d
IL_00d6: ret
IL_00d7: ldloc.0
IL_00d8: ldstr ""H""
IL_00dd: call ""bool string.op_Equality(string, string)""
IL_00e2: brtrue.s IL_0124
IL_00e4: ret
IL_00e5: ldloc.0
IL_00e6: ldstr ""I""
IL_00eb: call ""bool string.op_Equality(string, string)""
IL_00f0: brtrue.s IL_012b
IL_00f2: ret
IL_00f3: ldc.i4.1
IL_00f4: call ""void System.Console.Write(int)""
IL_00f9: ret
IL_00fa: ldc.i4.2
IL_00fb: call ""void System.Console.Write(int)""
IL_0100: ret
IL_0101: ldc.i4.3
IL_0102: call ""void System.Console.Write(int)""
IL_0107: ret
IL_0108: ldc.i4.4
IL_0109: call ""void System.Console.Write(int)""
IL_010e: ret
IL_010f: ldc.i4.5
IL_0110: call ""void System.Console.Write(int)""
IL_0115: ret
IL_0116: ldc.i4.6
IL_0117: call ""void System.Console.Write(int)""
IL_011c: ret
IL_011d: ldc.i4.7
IL_011e: call ""void System.Console.Write(int)""
IL_0123: ret
IL_0124: ldc.i4.8
IL_0125: call ""void System.Console.Write(int)""
IL_012a: ret
IL_012b: ldc.i4.s 9
IL_012d: call ""void System.Console.Write(int)""
IL_0132: ret
}");
comp = CreateCompilation(text);
comp.MakeMemberMissing(SpecialMember.System_String__Chars);
// Can't use the hash version when String.Chars is unavailable.
CompileAndVerify(comp).VerifyIL("Test.Main", @"
{
// Code size 186 (0xba)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: ldelem.ref
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: ldstr ""A""
IL_000a: call ""bool string.op_Equality(string, string)""
IL_000f: brtrue.s IL_007a
IL_0011: ldloc.0
IL_0012: ldstr ""B""
IL_0017: call ""bool string.op_Equality(string, string)""
IL_001c: brtrue.s IL_0081
IL_001e: ldloc.0
IL_001f: ldstr ""C""
IL_0024: call ""bool string.op_Equality(string, string)""
IL_0029: brtrue.s IL_0088
IL_002b: ldloc.0
IL_002c: ldstr ""D""
IL_0031: call ""bool string.op_Equality(string, string)""
IL_0036: brtrue.s IL_008f
IL_0038: ldloc.0
IL_0039: ldstr ""E""
IL_003e: call ""bool string.op_Equality(string, string)""
IL_0043: brtrue.s IL_0096
IL_0045: ldloc.0
IL_0046: ldstr ""F""
IL_004b: call ""bool string.op_Equality(string, string)""
IL_0050: brtrue.s IL_009d
IL_0052: ldloc.0
IL_0053: ldstr ""G""
IL_0058: call ""bool string.op_Equality(string, string)""
IL_005d: brtrue.s IL_00a4
IL_005f: ldloc.0
IL_0060: ldstr ""H""
IL_0065: call ""bool string.op_Equality(string, string)""
IL_006a: brtrue.s IL_00ab
IL_006c: ldloc.0
IL_006d: ldstr ""I""
IL_0072: call ""bool string.op_Equality(string, string)""
IL_0077: brtrue.s IL_00b2
IL_0079: ret
IL_007a: ldc.i4.1
IL_007b: call ""void System.Console.Write(int)""
IL_0080: ret
IL_0081: ldc.i4.2
IL_0082: call ""void System.Console.Write(int)""
IL_0087: ret
IL_0088: ldc.i4.3
IL_0089: call ""void System.Console.Write(int)""
IL_008e: ret
IL_008f: ldc.i4.4
IL_0090: call ""void System.Console.Write(int)""
IL_0095: ret
IL_0096: ldc.i4.5
IL_0097: call ""void System.Console.Write(int)""
IL_009c: ret
IL_009d: ldc.i4.6
IL_009e: call ""void System.Console.Write(int)""
IL_00a3: ret
IL_00a4: ldc.i4.7
IL_00a5: call ""void System.Console.Write(int)""
IL_00aa: ret
IL_00ab: ldc.i4.8
IL_00ac: call ""void System.Console.Write(int)""
IL_00b1: ret
IL_00b2: ldc.i4.s 9
IL_00b4: call ""void System.Console.Write(int)""
IL_00b9: ret
}");
}
[WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")]
[Fact]
public void Regress947580()
{
var text = @"
using System;
class Program {
static string boo(int i) {
switch (i) {
case 42:
var x = ""goo"";
if (x != ""bar"")
break;
return x;
}
return null;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 28 (0x1c)
.maxstack 2
.locals init (string V_0) //x
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: bne.un.s IL_001a
IL_0005: ldstr ""goo""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""bar""
IL_0011: call ""bool string.op_Inequality(string, string)""
IL_0016: brtrue.s IL_001a
IL_0018: ldloc.0
IL_0019: ret
IL_001a: ldnull
IL_001b: ret
}"
);
}
[WorkItem(947580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947580")]
[Fact]
public void Regress947580a()
{
var text = @"
using System;
class Program {
static string boo(int i) {
switch (i) {
case 42:
var x = ""goo"";
if (x != ""bar"")
break;
break;
}
return null;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 23 (0x17)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: bne.un.s IL_0015
IL_0005: ldstr ""goo""
IL_000a: ldstr ""bar""
IL_000f: call ""bool string.op_Inequality(string, string)""
IL_0014: pop
IL_0015: ldnull
IL_0016: ret
}"
);
}
[WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")]
[Fact]
public void Regress1035228()
{
var text = @"
using System;
class Program {
static bool boo(int i) {
var ii = i;
switch (++ii) {
case 42:
var x = ""goo"";
if (x != ""bar"")
{
return false;
}
break;
}
return true;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ldc.i4.s 42
IL_0005: bne.un.s IL_001a
IL_0007: ldstr ""goo""
IL_000c: ldstr ""bar""
IL_0011: call ""bool string.op_Inequality(string, string)""
IL_0016: brfalse.s IL_001a
IL_0018: ldc.i4.0
IL_0019: ret
IL_001a: ldc.i4.1
IL_001b: ret
}"
);
}
[WorkItem(1035228, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1035228")]
[Fact]
public void Regress1035228a()
{
var text = @"
using System;
class Program {
static bool boo(int i) {
var ii = i;
switch (ii++) {
case 42:
var x = ""goo"";
if (x != ""bar"")
{
return false;
}
break;
}
return true;
}
static void Main()
{
boo(42);
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "");
compVerifier.VerifyIL("Program.boo",
@"{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: bne.un.s IL_0018
IL_0005: ldstr ""goo""
IL_000a: ldstr ""bar""
IL_000f: call ""bool string.op_Inequality(string, string)""
IL_0014: brfalse.s IL_0018
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldc.i4.1
IL_0019: ret
}"
);
}
[WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")]
[Fact]
public void Regress4701()
{
var text = @"
using System;
namespace ConsoleApplication1
{
class Program
{
private void SwtchTest()
{
int? i;
i = 1;
switch (i)
{
case null:
Console.WriteLine(""In Null case"");
i = 1;
break;
default:
Console.WriteLine(""In DEFAULT case"");
i = i + 2;
break;
}
}
static void Main(string[] args)
{
var p = new Program();
p.SwtchTest();
}
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case");
compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest",
@"
{
// Code size 84 (0x54)
.maxstack 2
.locals init (int? V_0, //i
int? V_1,
int? V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""int?..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""bool int?.HasValue.get""
IL_000f: brtrue.s IL_0024
IL_0011: ldstr ""In Null case""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: ldloca.s V_0
IL_001d: ldc.i4.1
IL_001e: call ""int?..ctor(int)""
IL_0023: ret
IL_0024: ldstr ""In DEFAULT case""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ldloc.0
IL_002f: stloc.1
IL_0030: ldloca.s V_1
IL_0032: call ""bool int?.HasValue.get""
IL_0037: brtrue.s IL_0044
IL_0039: ldloca.s V_2
IL_003b: initobj ""int?""
IL_0041: ldloc.2
IL_0042: br.s IL_0052
IL_0044: ldloca.s V_1
IL_0046: call ""int int?.GetValueOrDefault()""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: newobj ""int?..ctor(int)""
IL_0052: stloc.0
IL_0053: ret
}"
);
}
[WorkItem(4701, "https://github.com/dotnet/roslyn/issues/4701")]
[Fact]
public void Regress4701a()
{
var text = @"
using System;
namespace ConsoleApplication1
{
class Program
{
private void SwtchTest()
{
string i = null;
i = ""1"";
switch (i)
{
case null:
Console.WriteLine(""In Null case"");
break;
default:
Console.WriteLine(""In DEFAULT case"");
break;
}
}
static void Main(string[] args)
{
var p = new Program();
p.SwtchTest();
}
}
}
";
var compVerifier = CompileAndVerify(text, expectedOutput: "In DEFAULT case");
compVerifier.VerifyIL("ConsoleApplication1.Program.SwtchTest",
@"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldstr ""1""
IL_0005: brtrue.s IL_0012
IL_0007: ldstr ""In Null case""
IL_000c: call ""void System.Console.WriteLine(string)""
IL_0011: ret
IL_0012: ldstr ""In DEFAULT case""
IL_0017: call ""void System.Console.WriteLine(string)""
IL_001c: ret
}"
);
}
#endregion
#region regression tests
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternSwitch_01()
{
var source = @"using System;
public class Program
{
public static void Main()
{
switch (StringSplitOptions.RemoveEmptyEntries)
{
case object o:
Console.WriteLine(o);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: box ""System.StringSplitOptions""
IL_0006: call ""void System.Console.WriteLine(object)""
IL_000b: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 26 (0x1a)
.maxstack 1
.locals init (object V_0, //o
System.StringSplitOptions V_1,
System.StringSplitOptions V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldc.i4.1
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""System.StringSplitOptions""
IL_000b: stloc.0
IL_000c: br.s IL_000e
IL_000e: br.s IL_0010
IL_0010: ldloc.0
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: nop
IL_0017: br.s IL_0019
IL_0019: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void ExplicitNullablePatternSwitch_02()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(null);
M(1);
}
public static void M(int? x)
{
switch (x)
{
case int i: // explicit nullable conversion
Console.Write(i);
break;
case null:
Console.Write(""null"");
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "null1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 33 (0x21)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldstr ""null""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "null1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 49 (0x31)
.maxstack 1
.locals init (int V_0, //i
int? V_1,
int? V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloca.s V_1
IL_0007: call ""bool int?.HasValue.get""
IL_000c: brfalse.s IL_0023
IL_000e: ldloca.s V_1
IL_0010: call ""int int?.GetValueOrDefault()""
IL_0015: stloc.0
IL_0016: br.s IL_0018
IL_0018: br.s IL_001a
IL_001a: ldloc.0
IL_001b: call ""void System.Console.Write(int)""
IL_0020: nop
IL_0021: br.s IL_0030
IL_0023: ldstr ""null""
IL_0028: call ""void System.Console.Write(string)""
IL_002d: nop
IL_002e: br.s IL_0030
IL_0030: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternSwitch_04()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(1);
}
public static void M(int x)
{
switch (x)
{
case System.IComparable i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""int""
IL_0006: call ""void System.Console.Write(object)""
IL_000b: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
.locals init (System.IComparable V_0, //i
int V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""int""
IL_000b: stloc.0
IL_000c: br.s IL_000e
IL_000e: br.s IL_0010
IL_0010: ldloc.0
IL_0011: call ""void System.Console.Write(object)""
IL_0016: nop
IL_0017: br.s IL_0019
IL_0019: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternSwitch_05()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(1);
M(null);
}
public static void M(int? x)
{
switch (x)
{
case System.IComparable i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init (System.IComparable V_0) //i
IL_0000: ldarg.0
IL_0001: box ""int?""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: call ""void System.Console.Write(object)""
IL_0010: ret
}
"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (System.IComparable V_0, //i
int? V_1,
int? V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""int?""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0011
IL_000f: br.s IL_001c
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: call ""void System.Console.Write(object)""
IL_0019: nop
IL_001a: br.s IL_001c
IL_001c: ret
}
"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnboxInPatternSwitch_06()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M(1);
M(null);
M(nameof(Main));
}
public static void M(object x)
{
switch (x)
{
case int i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 20 (0x14)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brfalse.s IL_0013
IL_0008: ldarg.0
IL_0009: unbox.any ""int""
IL_000e: call ""void System.Console.Write(int)""
IL_0013: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M",
@"{
// Code size 34 (0x22)
.maxstack 1
.locals init (int V_0, //i
object V_1,
object V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0021
IL_000d: ldloc.1
IL_000e: unbox.any ""int""
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: br.s IL_0018
IL_0018: ldloc.0
IL_0019: call ""void System.Console.Write(int)""
IL_001e: nop
IL_001f: br.s IL_0021
IL_0021: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnboxInPatternSwitch_07()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M<int>(1);
M<int>(null);
M<int>(10.5);
}
public static void M<T>(object x)
{
// when T is not known to be a reference type, there is an unboxing conversion from
// the effective base class C of T to T and from any base class of C to T.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""T""
IL_0006: brfalse.s IL_0018
IL_0008: ldarg.0
IL_0009: unbox.any ""T""
IL_000e: box ""T""
IL_0013: call ""void System.Console.Write(object)""
IL_0018: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (T V_0, //i
object V_1,
object V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0026
IL_000d: ldloc.1
IL_000e: unbox.any ""T""
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: br.s IL_0018
IL_0018: ldloc.0
IL_0019: box ""T""
IL_001e: call ""void System.Console.Write(object)""
IL_0023: nop
IL_0024: br.s IL_0026
IL_0026: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnboxInPatternSwitch_08()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M<int>(1);
M<int>(null);
M<int>(10.5);
}
public static void M<T>(IComparable x)
{
// when T is not known to be a reference type, there is an unboxing conversion from
// any interface type to T.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 25 (0x19)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""T""
IL_0006: brfalse.s IL_0018
IL_0008: ldarg.0
IL_0009: unbox.any ""T""
IL_000e: box ""T""
IL_0013: call ""void System.Console.Write(object)""
IL_0018: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T>",
@"{
// Code size 39 (0x27)
.maxstack 1
.locals init (T V_0, //i
System.IComparable V_1,
System.IComparable V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0026
IL_000d: ldloc.1
IL_000e: unbox.any ""T""
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: br.s IL_0018
IL_0018: ldloc.0
IL_0019: box ""T""
IL_001e: call ""void System.Console.Write(object)""
IL_0023: nop
IL_0024: br.s IL_0026
IL_0026: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void UnoxInPatternSwitch_09()
{
var source = @"using System;
public class Program
{
public static void Main()
{
M<int, object>(1);
M<int, object>(null);
M<int, object>(10.5);
}
public static void M<T, U>(U x) where T : U
{
// when T is not known to be a reference type, there is an unboxing conversion from
// a type parameter U to T, provided T depends on U.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T, U>",
@"{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""U""
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0022
IL_000d: ldarg.0
IL_000e: box ""U""
IL_0013: unbox.any ""T""
IL_0018: box ""T""
IL_001d: call ""void System.Console.Write(object)""
IL_0022: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "1");
compVerifier.VerifyIL("Program.M<T, U>",
@"{
// Code size 49 (0x31)
.maxstack 1
.locals init (T V_0, //i
U V_1,
U V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""U""
IL_000b: isinst ""T""
IL_0010: brfalse.s IL_0030
IL_0012: ldloc.1
IL_0013: box ""U""
IL_0018: unbox.any ""T""
IL_001d: stloc.0
IL_001e: br.s IL_0020
IL_0020: br.s IL_0022
IL_0022: ldloc.0
IL_0023: box ""T""
IL_0028: call ""void System.Console.Write(object)""
IL_002d: nop
IL_002e: br.s IL_0030
IL_0030: ret
}"
);
}
[Fact, WorkItem(18859, "https://github.com/dotnet/roslyn/issues/18859")]
public void BoxInPatternIf_02()
{
var source = @"using System;
public class Program
{
public static void Main()
{
if (StringSplitOptions.RemoveEmptyEntries is object o)
{
Console.WriteLine(o);
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 14 (0xe)
.maxstack 1
.locals init (object V_0) //o
IL_0000: ldc.i4.1
IL_0001: box ""System.StringSplitOptions""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void System.Console.WriteLine(object)""
IL_000d: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "RemoveEmptyEntries");
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (object V_0, //o
bool V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""System.StringSplitOptions""
IL_0007: stloc.0
IL_0008: ldc.i4.1
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: brfalse.s IL_0016
IL_000d: nop
IL_000e: ldloc.0
IL_000f: call ""void System.Console.WriteLine(object)""
IL_0014: nop
IL_0015: nop
IL_0016: ret
}"
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_01()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<int>(2));
Console.Write(M2<int>(3));
Console.Write(M1<int>(1.1));
Console.Write(M2<int>(1.1));
}
public static T M1<T>(ValueType o)
{
return o is T t ? t : default(T);
}
public static T M2<T>(ValueType o)
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t ? t : default(T);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'ValueType' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("System.ValueType", "T", "7.0", "7.1").WithLocation(19, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 34 (0x22)
.maxstack 1
.locals init (T V_0, //t
T V_1)
IL_0000: ldarg.0
IL_0001: isinst ""T""
IL_0006: brfalse.s IL_0016
IL_0008: ldarg.0
IL_0009: isinst ""T""
IL_000e: unbox.any ""T""
IL_0013: stloc.0
IL_0014: br.s IL_0020
IL_0016: ldloca.s V_1
IL_0018: initobj ""T""
IL_001e: ldloc.1
IL_001f: ret
IL_0020: ldloc.0
IL_0021: ret
}"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 40 (0x28)
.maxstack 1
.locals init (T V_0, //t
T V_1,
T V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""T""
IL_0007: brfalse.s IL_0017
IL_0009: ldarg.0
IL_000a: isinst ""T""
IL_000f: unbox.any ""T""
IL_0014: stloc.0
IL_0015: br.s IL_0022
IL_0017: ldloca.s V_1
IL_0019: initobj ""T""
IL_001f: ldloc.1
IL_0020: br.s IL_0023
IL_0022: ldloc.0
IL_0023: stloc.2
IL_0024: br.s IL_0026
IL_0026: ldloc.2
IL_0027: ret
}"
);
compVerifier.VerifyIL("Program.M2<T>",
@"{
// Code size 48 (0x30)
.maxstack 1
.locals init (T V_0, //t
System.ValueType V_1,
System.ValueType V_2,
T V_3,
T V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0021
IL_000d: ldloc.1
IL_000e: isinst ""T""
IL_0013: unbox.any ""T""
IL_0018: stloc.0
IL_0019: br.s IL_001b
IL_001b: br.s IL_001d
IL_001d: ldloc.0
IL_001e: stloc.3
IL_001f: br.s IL_002e
IL_0021: ldloca.s V_4
IL_0023: initobj ""T""
IL_0029: ldloc.s V_4
IL_002b: stloc.3
IL_002c: br.s IL_002e
IL_002e: ldloc.3
IL_002f: ret
}"
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_02()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1(2));
Console.Write(M2(3));
Console.Write(M1(1.1));
Console.Write(M2(1.1));
}
public static int M1<T>(T o)
{
return o is int t ? t : default(int);
}
public static int M2<T>(T o)
{
switch (o)
{
case int t:
return t;
default:
return default(int);
}
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater.
// return o is int t ? t : default(int);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'int' in C# 7.0. Please use language version 7.1 or greater.
// case int t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "int").WithArguments("T", "int", "7.0", "7.1").WithLocation(19, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 36 (0x24)
.maxstack 1
.locals init (int V_0) //t
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0020
IL_000d: ldarg.0
IL_000e: box ""T""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: stloc.0
IL_001e: br.s IL_0022
IL_0020: ldc.i4.0
IL_0021: ret
IL_0022: ldloc.0
IL_0023: ret
}
"
);
compVerifier.VerifyIL("Program.M2<T>",
@"{
// Code size 32 (0x20)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_001e
IL_000d: ldarg.0
IL_000e: box ""T""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: ret
IL_001e: ldc.i4.0
IL_001f: ret
}
"
);
compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "2300");
compVerifier.VerifyIL("Program.M1<T>",
@"{
// Code size 42 (0x2a)
.maxstack 1
.locals init (int V_0, //t
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: isinst ""int""
IL_000c: brfalse.s IL_0021
IL_000e: ldarg.0
IL_000f: box ""T""
IL_0014: isinst ""int""
IL_0019: unbox.any ""int""
IL_001e: stloc.0
IL_001f: br.s IL_0024
IL_0021: ldc.i4.0
IL_0022: br.s IL_0025
IL_0024: ldloc.0
IL_0025: stloc.1
IL_0026: br.s IL_0028
IL_0028: ldloc.1
IL_0029: ret
}
"
);
compVerifier.VerifyIL("Program.M2<T>",
@"{
// Code size 49 (0x31)
.maxstack 1
.locals init (int V_0, //t
T V_1,
T V_2,
int V_3)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.2
IL_0003: ldloc.2
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: box ""T""
IL_000b: isinst ""int""
IL_0010: brfalse.s IL_002b
IL_0012: ldloc.1
IL_0013: box ""T""
IL_0018: isinst ""int""
IL_001d: unbox.any ""int""
IL_0022: stloc.0
IL_0023: br.s IL_0025
IL_0025: br.s IL_0027
IL_0027: ldloc.0
IL_0028: stloc.3
IL_0029: br.s IL_002f
IL_002b: ldc.i4.0
IL_002c: stloc.3
IL_002d: br.s IL_002f
IL_002f: ldloc.3
IL_0030: ret
}
"
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_03()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<int>(2));
Console.Write(M2<int>(3));
Console.Write(M1<int>(1.1));
Console.Write(M2<int>(1.1));
}
public static T M1<T>(ValueType o) where T : struct
{
return o is T t ? t : default(T);
}
public static T M2<T>(ValueType o) where T : struct
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "2300");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_04()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var x = new X();
Console.Write(M1<B>(new A()) ?? x);
Console.Write(M2<B>(new A()) ?? x);
Console.Write(M1<B>(new B()) ?? x);
Console.Write(M2<B>(new B()) ?? x);
}
public static T M1<T>(A o) where T : class
{
return o is T t ? t : default(T);
}
public static T M2<T>(A o) where T : class
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
class A
{
}
class B : A
{
}
class X : B { }
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t ? t : default(T);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21),
// (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "XXBB");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_05()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var x = new X();
Console.Write(M1<B>(new A()) ?? x);
Console.Write(M2<B>(new A()) ?? x);
Console.Write(M1<B>(new B()) ?? x);
Console.Write(M2<B>(new B()) ?? x);
}
public static T M1<T>(A o) where T : I1
{
return o is T t ? t : default(T);
}
public static T M2<T>(A o) where T : I1
{
switch (o)
{
case T t:
return t;
default:
return default(T);
}
}
}
interface I1
{
}
class A : I1
{
}
class B : A
{
}
class X : B { }
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (14,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t ? t : default(T);
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(14, 21),
// (20,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(20, 18)
);
var compVerifier = CompileAndVerify(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1,
expectedOutput: "XXBB");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_06()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<B>(new A()));
Console.Write(M2<B>(new A()));
Console.Write(M1<A>(new A()));
Console.Write(M2<A>(new A()));
}
public static bool M1<T>(A o) where T : I1
{
return o is T t;
}
public static bool M2<T>(A o) where T : I1
{
switch (o)
{
case T t:
return true;
default:
return false;
}
}
}
interface I1
{
}
struct A : I1
{
}
struct B : I1
{
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t;
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18)
);
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: "FalseFalseTrueTrue");
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestMatchWithTypeParameter_07()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
Console.Write(M1<B>(new A()));
Console.Write(M2<B>(new A()));
Console.Write(M1<A>(new A()));
Console.Write(M2<A>(new A()));
}
public static bool M1<T>(A o) where T : new()
{
return o is T t;
}
public static bool M2<T>(A o) where T : new()
{
switch (o)
{
case T t:
return true;
default:
return false;
}
}
}
struct A
{
}
struct B
{
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics(
// (13,21): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// return o is T t;
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(13, 21),
// (19,18): error CS8413: An expression of type 'A' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater.
// case T t:
Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("A", "T", "7.0", "7.1").WithLocation(19, 18)
);
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.Regular7_1)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: "FalseFalseTrueTrue");
compVerifier.VerifyDiagnostics();
}
[Fact]
[WorkItem(16195, "https://github.com/dotnet/roslyn/issues/31269")]
public void TestIgnoreDynamicVsObjectAndTupleElementNames_01()
{
var source =
@"public class Generic<T>
{
public enum Color { Red=1, Blue=2 }
}
class Program
{
public static void Main(string[] args)
{
}
public static void M2(object o)
{
switch (o)
{
case Generic<long>.Color c:
case Generic<object>.Color.Red:
case Generic<(int x, int y)>.Color.Blue:
case Generic<string>.Color.Red:
case Generic<dynamic>.Color.Red: // error: duplicate case
case Generic<(int z, int w)>.Color.Blue: // error: duplicate case
case Generic<(int z, long w)>.Color.Blue:
default:
break;
}
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (18,13): error CS0152: The switch statement contains multiple cases with the label value '1'
// case Generic<dynamic>.Color.Red: // error: duplicate case
Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<dynamic>.Color.Red:").WithArguments("1").WithLocation(18, 13),
// (19,13): error CS0152: The switch statement contains multiple cases with the label value '2'
// case Generic<(int z, int w)>.Color.Blue: // error: duplicate case
Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case Generic<(int z, int w)>.Color.Blue:").WithArguments("2").WithLocation(19, 13)
);
}
[Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")]
public void TestIgnoreDynamicVsObjectAndTupleElementNames_02()
{
var source =
@"using System;
public class Generic<T>
{
public enum Color { X0, X1, X2, Green, Blue, Red }
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(M1<Generic<int>.Color>(Generic<long>.Color.Red)); // False
Console.WriteLine(M1<Generic<string>.Color>(Generic<object>.Color.Red)); // False
Console.WriteLine(M1<Generic<(int x, int y)>.Color>(Generic<(int z, int w)>.Color.Red)); // True
Console.WriteLine(M1<Generic<object>.Color>(Generic<dynamic>.Color.Blue)); // True
Console.WriteLine(M2(Generic<long>.Color.Red)); // Generic<long>.Color.Red
Console.WriteLine(M2(Generic<object>.Color.Blue)); // Generic<dynamic>.Color.Blue
Console.WriteLine(M2(Generic<int>.Color.Red)); // None
Console.WriteLine(M2(Generic<dynamic>.Color.Red)); // Generic<object>.Color.Red
}
public static bool M1<T>(object o)
{
return o is T t;
}
public static string M2(object o)
{
switch (o)
{
case Generic<long>.Color c:
return ""Generic<long>.Color."" + c;
case Generic<object>.Color.Red:
return ""Generic<object>.Color.Red"";
case Generic<dynamic>.Color.Blue:
return ""Generic<dynamic>.Color.Blue"";
default:
return ""None"";
}
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication))
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: @"False
False
True
True
Generic<long>.Color.Red
Generic<dynamic>.Color.Blue
None
Generic<object>.Color.Red");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 108 (0x6c)
.maxstack 2
.locals init (Generic<long>.Color V_0, //c
object V_1,
Generic<object>.Color V_2,
object V_3,
string V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: isinst ""Generic<long>.Color""
IL_000b: brfalse.s IL_0016
IL_000d: ldloc.1
IL_000e: unbox.any ""Generic<long>.Color""
IL_0013: stloc.0
IL_0014: br.s IL_0031
IL_0016: ldloc.1
IL_0017: isinst ""Generic<object>.Color""
IL_001c: brfalse.s IL_0060
IL_001e: ldloc.1
IL_001f: unbox.any ""Generic<object>.Color""
IL_0024: stloc.2
IL_0025: ldloc.2
IL_0026: ldc.i4.4
IL_0027: beq.s IL_0057
IL_0029: br.s IL_002b
IL_002b: ldloc.2
IL_002c: ldc.i4.5
IL_002d: beq.s IL_004e
IL_002f: br.s IL_0060
IL_0031: br.s IL_0033
IL_0033: ldstr ""Generic<long>.Color.""
IL_0038: ldloca.s V_0
IL_003a: constrained. ""Generic<long>.Color""
IL_0040: callvirt ""string object.ToString()""
IL_0045: call ""string string.Concat(string, string)""
IL_004a: stloc.s V_4
IL_004c: br.s IL_0069
IL_004e: ldstr ""Generic<object>.Color.Red""
IL_0053: stloc.s V_4
IL_0055: br.s IL_0069
IL_0057: ldstr ""Generic<dynamic>.Color.Blue""
IL_005c: stloc.s V_4
IL_005e: br.s IL_0069
IL_0060: ldstr ""None""
IL_0065: stloc.s V_4
IL_0067: br.s IL_0069
IL_0069: ldloc.s V_4
IL_006b: ret
}
"
);
}
[Fact, WorkItem(16129, "https://github.com/dotnet/roslyn/issues/16129")]
public void ExactPatternMatch()
{
var source =
@"using System;
class C
{
static void Main()
{
if (TrySomething() is ValueTuple<string, bool> v && v.Item2)
{
System.Console.Write(v.Item1 == null);
}
}
static (string Value, bool Success) TrySomething()
{
return (null, true);
}
}";
var compilation = CreateCompilation(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication))
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation,
expectedOutput: @"True");
compVerifier.VerifyIL("C.Main",
@"{
// Code size 29 (0x1d)
.maxstack 2
.locals init (System.ValueTuple<string, bool> V_0) //v
IL_0000: call ""System.ValueTuple<string, bool> C.TrySomething()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldfld ""bool System.ValueTuple<string, bool>.Item2""
IL_000c: brfalse.s IL_001c
IL_000e: ldloc.0
IL_000f: ldfld ""string System.ValueTuple<string, bool>.Item1""
IL_0014: ldnull
IL_0015: ceq
IL_0017: call ""void System.Console.Write(bool)""
IL_001c: ret
}"
);
}
[WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void ShareLikeKindedTemps_01()
{
var source = @"using System;
public class Program
{
public static void Main()
{
}
static bool b = false;
public static void M(object o)
{
switch (o)
{
case int i when b: break;
case var _ when b: break;
case int i when b: break;
case var _ when b: break;
case int i when b: break;
case var _ when b: break;
case int i when b: break;
case var _ when b: break;
}
}
}";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.ConsoleApplication),
expectedOutput: "");
compVerifier.VerifyIL("Program.M", @"
{
// Code size 120 (0x78)
.maxstack 2
.locals init (int V_0,
int V_1, //i
object V_2)
IL_0000: ldarg.0
IL_0001: stloc.2
IL_0002: ldloc.2
IL_0003: isinst ""int""
IL_0008: brfalse.s IL_001c
IL_000a: ldloc.2
IL_000b: unbox.any ""int""
IL_0010: stloc.1
IL_0011: ldsfld ""bool Program.b""
IL_0016: brtrue.s IL_0077
IL_0018: ldc.i4.1
IL_0019: stloc.0
IL_001a: br.s IL_001e
IL_001c: ldc.i4.7
IL_001d: stloc.0
IL_001e: ldsfld ""bool Program.b""
IL_0023: brtrue.s IL_0077
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: beq.s IL_002e
IL_0029: ldloc.0
IL_002a: ldc.i4.7
IL_002b: beq.s IL_0039
IL_002d: ret
IL_002e: ldsfld ""bool Program.b""
IL_0033: brtrue.s IL_0077
IL_0035: ldc.i4.3
IL_0036: stloc.0
IL_0037: br.s IL_003b
IL_0039: ldc.i4.8
IL_003a: stloc.0
IL_003b: ldsfld ""bool Program.b""
IL_0040: brtrue.s IL_0077
IL_0042: ldloc.0
IL_0043: ldc.i4.3
IL_0044: beq.s IL_004b
IL_0046: ldloc.0
IL_0047: ldc.i4.8
IL_0048: beq.s IL_0056
IL_004a: ret
IL_004b: ldsfld ""bool Program.b""
IL_0050: brtrue.s IL_0077
IL_0052: ldc.i4.5
IL_0053: stloc.0
IL_0054: br.s IL_0059
IL_0056: ldc.i4.s 9
IL_0058: stloc.0
IL_0059: ldsfld ""bool Program.b""
IL_005e: brtrue.s IL_0077
IL_0060: ldloc.0
IL_0061: ldc.i4.5
IL_0062: beq.s IL_006a
IL_0064: ldloc.0
IL_0065: ldc.i4.s 9
IL_0067: beq.s IL_0071
IL_0069: ret
IL_006a: ldsfld ""bool Program.b""
IL_006f: brtrue.s IL_0077
IL_0071: ldsfld ""bool Program.b""
IL_0076: pop
IL_0077: ret
}"
);
compVerifier = CompileAndVerify(source,
expectedOutput: "",
symbolValidator: validator,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication).WithMetadataImportOptions(MetadataImportOptions.All));
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Program");
Assert.Null(type.GetMember(".cctor"));
}
compVerifier.VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source,
expectedIL: @"{
// Code size 194 (0xc2)
.maxstack 2
.locals init (int V_0,
int V_1, //i
int V_2, //i
int V_3, //i
int V_4, //i
object V_5,
object V_6)
// sequence point: {
IL_0000: nop
// sequence point: switch (o)
IL_0001: ldarg.0
IL_0002: stloc.s V_6
// sequence point: <hidden>
IL_0004: ldloc.s V_6
IL_0006: stloc.s V_5
// sequence point: <hidden>
IL_0008: ldloc.s V_5
IL_000a: isinst ""int""
IL_000f: brfalse.s IL_002d
IL_0011: ldloc.s V_5
IL_0013: unbox.any ""int""
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: br.s IL_001b
// sequence point: when b
IL_001b: ldsfld ""bool Program.b""
IL_0020: brtrue.s IL_0024
// sequence point: <hidden>
IL_0022: br.s IL_0029
// sequence point: break;
IL_0024: br IL_00c1
// sequence point: <hidden>
IL_0029: ldc.i4.1
IL_002a: stloc.0
IL_002b: br.s IL_0031
IL_002d: ldc.i4.7
IL_002e: stloc.0
IL_002f: br.s IL_0031
// sequence point: when b
IL_0031: ldsfld ""bool Program.b""
IL_0036: brtrue.s IL_0048
// sequence point: <hidden>
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: beq.s IL_0044
IL_003c: br.s IL_003e
IL_003e: ldloc.0
IL_003f: ldc.i4.7
IL_0040: beq.s IL_0046
IL_0042: br.s IL_0048
IL_0044: br.s IL_004a
IL_0046: br.s IL_005b
// sequence point: break;
IL_0048: br.s IL_00c1
// sequence point: <hidden>
IL_004a: ldloc.1
IL_004b: stloc.2
// sequence point: when b
IL_004c: ldsfld ""bool Program.b""
IL_0051: brtrue.s IL_0055
// sequence point: <hidden>
IL_0053: br.s IL_0057
// sequence point: break;
IL_0055: br.s IL_00c1
// sequence point: <hidden>
IL_0057: ldc.i4.3
IL_0058: stloc.0
IL_0059: br.s IL_005f
IL_005b: ldc.i4.8
IL_005c: stloc.0
IL_005d: br.s IL_005f
// sequence point: when b
IL_005f: ldsfld ""bool Program.b""
IL_0064: brtrue.s IL_0076
// sequence point: <hidden>
IL_0066: ldloc.0
IL_0067: ldc.i4.3
IL_0068: beq.s IL_0072
IL_006a: br.s IL_006c
IL_006c: ldloc.0
IL_006d: ldc.i4.8
IL_006e: beq.s IL_0074
IL_0070: br.s IL_0076
IL_0072: br.s IL_0078
IL_0074: br.s IL_0089
// sequence point: break;
IL_0076: br.s IL_00c1
// sequence point: <hidden>
IL_0078: ldloc.1
IL_0079: stloc.3
// sequence point: when b
IL_007a: ldsfld ""bool Program.b""
IL_007f: brtrue.s IL_0083
// sequence point: <hidden>
IL_0081: br.s IL_0085
// sequence point: break;
IL_0083: br.s IL_00c1
// sequence point: <hidden>
IL_0085: ldc.i4.5
IL_0086: stloc.0
IL_0087: br.s IL_008e
IL_0089: ldc.i4.s 9
IL_008b: stloc.0
IL_008c: br.s IL_008e
// sequence point: when b
IL_008e: ldsfld ""bool Program.b""
IL_0093: brtrue.s IL_00a6
// sequence point: <hidden>
IL_0095: ldloc.0
IL_0096: ldc.i4.5
IL_0097: beq.s IL_00a2
IL_0099: br.s IL_009b
IL_009b: ldloc.0
IL_009c: ldc.i4.s 9
IL_009e: beq.s IL_00a4
IL_00a0: br.s IL_00a6
IL_00a2: br.s IL_00a8
IL_00a4: br.s IL_00b6
// sequence point: break;
IL_00a6: br.s IL_00c1
// sequence point: <hidden>
IL_00a8: ldloc.1
IL_00a9: stloc.s V_4
// sequence point: when b
IL_00ab: ldsfld ""bool Program.b""
IL_00b0: brtrue.s IL_00b4
// sequence point: <hidden>
IL_00b2: br.s IL_00b6
// sequence point: break;
IL_00b4: br.s IL_00c1
// sequence point: when b
IL_00b6: ldsfld ""bool Program.b""
IL_00bb: brtrue.s IL_00bf
// sequence point: <hidden>
IL_00bd: br.s IL_00c1
// sequence point: break;
IL_00bf: br.s IL_00c1
// sequence point: }
IL_00c1: ret
}"
);
compVerifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""Program"" methodName=""Main"" />
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Program"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""0"" offset=""55"" />
<slot kind=""0"" offset=""133"" />
<slot kind=""0"" offset=""211"" />
<slot kind=""0"" offset=""289"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""38"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x31"" startLine=""13"" startColumn=""24"" endLine=""13"" endColumn=""30"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x48"" startLine=""13"" startColumn=""32"" endLine=""13"" endColumn=""38"" document=""1"" />
<entry offset=""0x4a"" hidden=""true"" document=""1"" />
<entry offset=""0x4c"" startLine=""14"" startColumn=""24"" endLine=""14"" endColumn=""30"" document=""1"" />
<entry offset=""0x53"" hidden=""true"" document=""1"" />
<entry offset=""0x55"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""38"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x5f"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""30"" document=""1"" />
<entry offset=""0x66"" hidden=""true"" document=""1"" />
<entry offset=""0x76"" startLine=""15"" startColumn=""32"" endLine=""15"" endColumn=""38"" document=""1"" />
<entry offset=""0x78"" hidden=""true"" document=""1"" />
<entry offset=""0x7a"" startLine=""16"" startColumn=""24"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x81"" hidden=""true"" document=""1"" />
<entry offset=""0x83"" startLine=""16"" startColumn=""32"" endLine=""16"" endColumn=""38"" document=""1"" />
<entry offset=""0x85"" hidden=""true"" document=""1"" />
<entry offset=""0x8e"" startLine=""17"" startColumn=""24"" endLine=""17"" endColumn=""30"" document=""1"" />
<entry offset=""0x95"" hidden=""true"" document=""1"" />
<entry offset=""0xa6"" startLine=""17"" startColumn=""32"" endLine=""17"" endColumn=""38"" document=""1"" />
<entry offset=""0xa8"" hidden=""true"" document=""1"" />
<entry offset=""0xab"" startLine=""18"" startColumn=""24"" endLine=""18"" endColumn=""30"" document=""1"" />
<entry offset=""0xb2"" hidden=""true"" document=""1"" />
<entry offset=""0xb4"" startLine=""18"" startColumn=""32"" endLine=""18"" endColumn=""38"" document=""1"" />
<entry offset=""0xb6"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""30"" document=""1"" />
<entry offset=""0xbd"" hidden=""true"" document=""1"" />
<entry offset=""0xbf"" startLine=""19"" startColumn=""32"" endLine=""19"" endColumn=""38"" document=""1"" />
<entry offset=""0xc1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xc2"">
<scope startOffset=""0x1b"" endOffset=""0x29"">
<local name=""i"" il_index=""1"" il_start=""0x1b"" il_end=""0x29"" attributes=""0"" />
</scope>
<scope startOffset=""0x4a"" endOffset=""0x57"">
<local name=""i"" il_index=""2"" il_start=""0x4a"" il_end=""0x57"" attributes=""0"" />
</scope>
<scope startOffset=""0x78"" endOffset=""0x85"">
<local name=""i"" il_index=""3"" il_start=""0x78"" il_end=""0x85"" attributes=""0"" />
</scope>
<scope startOffset=""0xa8"" endOffset=""0xb6"">
<local name=""i"" il_index=""4"" il_start=""0xa8"" il_end=""0xb6"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(19280, "https://github.com/dotnet/roslyn/issues/19280")]
public void TestSignificanceOfDynamicVersusObjectAndTupleNamesInUniquenessOfPatternMatchingTemps()
{
var source =
@"using System;
public class Generic<T,U>
{
}
class Program
{
public static void Main(string[] args)
{
var g = new Generic<object, (int, int)>();
M2(g, true, false, false);
M2(g, false, true, false);
M2(g, false, false, true);
}
public static void M2(object o, bool b1, bool b2, bool b3)
{
switch (o)
{
case Generic<object, (int a, int b)> g when b1: Console.Write(""a""); break;
case var _ when b2: Console.Write(""b""); break;
case Generic<dynamic, (int x, int y)> g when b3: Console.Write(""c""); break;
}
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.ConsoleApplication))
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "abc");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 98 (0x62)
.maxstack 2
.locals init (int V_0,
Generic<object, System.ValueTuple<int, int>> V_1, //g
Generic<dynamic, System.ValueTuple<int, int>> V_2, //g
object V_3,
object V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.s V_4
IL_0004: ldloc.s V_4
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: isinst ""Generic<object, System.ValueTuple<int, int>>""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0013
IL_0011: br.s IL_0029
IL_0013: ldarg.1
IL_0014: brtrue.s IL_0018
IL_0016: br.s IL_0025
IL_0018: ldstr ""a""
IL_001d: call ""void System.Console.Write(string)""
IL_0022: nop
IL_0023: br.s IL_0061
IL_0025: ldc.i4.1
IL_0026: stloc.0
IL_0027: br.s IL_002d
IL_0029: ldc.i4.3
IL_002a: stloc.0
IL_002b: br.s IL_002d
IL_002d: ldarg.2
IL_002e: brtrue.s IL_0040
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: beq.s IL_003c
IL_0034: br.s IL_0036
IL_0036: ldloc.0
IL_0037: ldc.i4.3
IL_0038: beq.s IL_003e
IL_003a: br.s IL_0040
IL_003c: br.s IL_004d
IL_003e: br.s IL_0061
IL_0040: ldstr ""b""
IL_0045: call ""void System.Console.Write(string)""
IL_004a: nop
IL_004b: br.s IL_0061
IL_004d: ldloc.1
IL_004e: stloc.2
IL_004f: ldarg.3
IL_0050: brtrue.s IL_0054
IL_0052: br.s IL_0061
IL_0054: ldstr ""c""
IL_0059: call ""void System.Console.Write(string)""
IL_005e: nop
IL_005f: br.s IL_0061
IL_0061: ret
}
"
);
}
[Fact]
[WorkItem(39564, "https://github.com/dotnet/roslyn/issues/39564")]
public void OrderOfEvaluationOfTupleAsSwitchExpressionArgument()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
using var sr = new System.IO.StringReader(""fiz\nbar"");
var r = (sr.ReadLine(), sr.ReadLine()) switch
{
(""fiz"", ""bar"") => ""Yep, all good!"",
var (a, b) => $""Wait, what? I got ({a}, {b})!"",
};
Console.WriteLine(r);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!");
compVerifier.VerifyIL("Program.Main", @"
{
// Code size 144 (0x90)
.maxstack 4
.locals init (System.IO.StringReader V_0, //sr
string V_1, //r
string V_2, //a
string V_3, //b
string V_4)
IL_0000: nop
IL_0001: ldstr ""fiz
bar""
IL_0006: newobj ""System.IO.StringReader..ctor(string)""
IL_000b: stloc.0
.try
{
IL_000c: ldloc.0
IL_000d: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0012: stloc.2
IL_0013: ldloc.0
IL_0014: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0019: stloc.3
IL_001a: ldc.i4.1
IL_001b: brtrue.s IL_001e
IL_001d: nop
IL_001e: ldloc.2
IL_001f: ldstr ""fiz""
IL_0024: call ""bool string.op_Equality(string, string)""
IL_0029: brfalse.s IL_0043
IL_002b: ldloc.3
IL_002c: ldstr ""bar""
IL_0031: call ""bool string.op_Equality(string, string)""
IL_0036: brtrue.s IL_003a
IL_0038: br.s IL_0043
IL_003a: ldstr ""Yep, all good!""
IL_003f: stloc.s V_4
IL_0041: br.s IL_0074
IL_0043: br.s IL_0045
IL_0045: ldc.i4.5
IL_0046: newarr ""string""
IL_004b: dup
IL_004c: ldc.i4.0
IL_004d: ldstr ""Wait, what? I got (""
IL_0052: stelem.ref
IL_0053: dup
IL_0054: ldc.i4.1
IL_0055: ldloc.2
IL_0056: stelem.ref
IL_0057: dup
IL_0058: ldc.i4.2
IL_0059: ldstr "", ""
IL_005e: stelem.ref
IL_005f: dup
IL_0060: ldc.i4.3
IL_0061: ldloc.3
IL_0062: stelem.ref
IL_0063: dup
IL_0064: ldc.i4.4
IL_0065: ldstr "")!""
IL_006a: stelem.ref
IL_006b: call ""string string.Concat(params string[])""
IL_0070: stloc.s V_4
IL_0072: br.s IL_0074
IL_0074: ldc.i4.1
IL_0075: brtrue.s IL_0078
IL_0077: nop
IL_0078: ldloc.s V_4
IL_007a: stloc.1
IL_007b: ldloc.1
IL_007c: call ""void System.Console.WriteLine(string)""
IL_0081: nop
IL_0082: leave.s IL_008f
}
finally
{
IL_0084: ldloc.0
IL_0085: brfalse.s IL_008e
IL_0087: ldloc.0
IL_0088: callvirt ""void System.IDisposable.Dispose()""
IL_008d: nop
IL_008e: endfinally
}
IL_008f: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe)
.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: "Yep, all good!");
compVerifier.VerifyIL("Program.Main", @"
{
// Code size 122 (0x7a)
.maxstack 4
.locals init (System.IO.StringReader V_0, //sr
string V_1, //a
string V_2, //b
string V_3)
IL_0000: ldstr ""fiz
bar""
IL_0005: newobj ""System.IO.StringReader..ctor(string)""
IL_000a: stloc.0
.try
{
IL_000b: ldloc.0
IL_000c: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: callvirt ""string System.IO.TextReader.ReadLine()""
IL_0018: stloc.2
IL_0019: ldloc.1
IL_001a: ldstr ""fiz""
IL_001f: call ""bool string.op_Equality(string, string)""
IL_0024: brfalse.s IL_003b
IL_0026: ldloc.2
IL_0027: ldstr ""bar""
IL_002c: call ""bool string.op_Equality(string, string)""
IL_0031: brfalse.s IL_003b
IL_0033: ldstr ""Yep, all good!""
IL_0038: stloc.3
IL_0039: br.s IL_0067
IL_003b: ldc.i4.5
IL_003c: newarr ""string""
IL_0041: dup
IL_0042: ldc.i4.0
IL_0043: ldstr ""Wait, what? I got (""
IL_0048: stelem.ref
IL_0049: dup
IL_004a: ldc.i4.1
IL_004b: ldloc.1
IL_004c: stelem.ref
IL_004d: dup
IL_004e: ldc.i4.2
IL_004f: ldstr "", ""
IL_0054: stelem.ref
IL_0055: dup
IL_0056: ldc.i4.3
IL_0057: ldloc.2
IL_0058: stelem.ref
IL_0059: dup
IL_005a: ldc.i4.4
IL_005b: ldstr "")!""
IL_0060: stelem.ref
IL_0061: call ""string string.Concat(params string[])""
IL_0066: stloc.3
IL_0067: ldloc.3
IL_0068: call ""void System.Console.WriteLine(string)""
IL_006d: leave.s IL_0079
}
finally
{
IL_006f: ldloc.0
IL_0070: brfalse.s IL_0078
IL_0072: ldloc.0
IL_0073: callvirt ""void System.IDisposable.Dispose()""
IL_0078: endfinally
}
IL_0079: ret
}
");
}
[Fact]
[WorkItem(41502, "https://github.com/dotnet/roslyn/issues/41502")]
public void PatternSwitchDagReduction_01()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
M(1, 1, 6); // 1
M(1, 2, 6); // 2
M(1, 1, 3); // 3
M(1, 2, 3); // 3
M(1, 5, 3); // 3
M(2, 5, 3); // 3
M(1, 3, 4); // 4
M(2, 1, 4); // 5
M(2, 2, 2); // 6
}
public static void M(int a, int b, int c) => Console.Write(M2(a, b, c));
public static int M2(int a, int b, int c) => (a, b, c) switch
{
(1, 1, 6) => 1,
(1, 2, 6) => 2,
(_, _, 3) => 3,
(1, _, _) => 4,
(_, 1, _) => 5,
(_, _, _) => 6,
};
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9)
.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456");
compVerifier.VerifyIL("Program.M2", @"
{
// Code size 76 (0x4c)
.maxstack 2
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.0
IL_0005: ldc.i4.1
IL_0006: bne.un.s IL_0024
IL_0008: ldarg.1
IL_0009: ldc.i4.1
IL_000a: beq.s IL_0014
IL_000c: br.s IL_000e
IL_000e: ldarg.1
IL_000f: ldc.i4.2
IL_0010: beq.s IL_001a
IL_0012: br.s IL_001e
IL_0014: ldarg.2
IL_0015: ldc.i4.6
IL_0016: beq.s IL_002e
IL_0018: br.s IL_001e
IL_001a: ldarg.2
IL_001b: ldc.i4.6
IL_001c: beq.s IL_0032
IL_001e: ldarg.2
IL_001f: ldc.i4.3
IL_0020: beq.s IL_0036
IL_0022: br.s IL_003a
IL_0024: ldarg.2
IL_0025: ldc.i4.3
IL_0026: beq.s IL_0036
IL_0028: ldarg.1
IL_0029: ldc.i4.1
IL_002a: beq.s IL_003e
IL_002c: br.s IL_0042
IL_002e: ldc.i4.1
IL_002f: stloc.0
IL_0030: br.s IL_0046
IL_0032: ldc.i4.2
IL_0033: stloc.0
IL_0034: br.s IL_0046
IL_0036: ldc.i4.3
IL_0037: stloc.0
IL_0038: br.s IL_0046
IL_003a: ldc.i4.4
IL_003b: stloc.0
IL_003c: br.s IL_0046
IL_003e: ldc.i4.5
IL_003f: stloc.0
IL_0040: br.s IL_0046
IL_0042: ldc.i4.6
IL_0043: stloc.0
IL_0044: br.s IL_0046
IL_0046: ldc.i4.1
IL_0047: brtrue.s IL_004a
IL_0049: nop
IL_004a: ldloc.0
IL_004b: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9)
.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: "123333456");
compVerifier.VerifyIL("Program.M2", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: bne.un.s IL_001e
IL_0004: ldarg.1
IL_0005: ldc.i4.1
IL_0006: beq.s IL_000e
IL_0008: ldarg.1
IL_0009: ldc.i4.2
IL_000a: beq.s IL_0014
IL_000c: br.s IL_0018
IL_000e: ldarg.2
IL_000f: ldc.i4.6
IL_0010: beq.s IL_0028
IL_0012: br.s IL_0018
IL_0014: ldarg.2
IL_0015: ldc.i4.6
IL_0016: beq.s IL_002c
IL_0018: ldarg.2
IL_0019: ldc.i4.3
IL_001a: beq.s IL_0030
IL_001c: br.s IL_0034
IL_001e: ldarg.2
IL_001f: ldc.i4.3
IL_0020: beq.s IL_0030
IL_0022: ldarg.1
IL_0023: ldc.i4.1
IL_0024: beq.s IL_0038
IL_0026: br.s IL_003c
IL_0028: ldc.i4.1
IL_0029: stloc.0
IL_002a: br.s IL_003e
IL_002c: ldc.i4.2
IL_002d: stloc.0
IL_002e: br.s IL_003e
IL_0030: ldc.i4.3
IL_0031: stloc.0
IL_0032: br.s IL_003e
IL_0034: ldc.i4.4
IL_0035: stloc.0
IL_0036: br.s IL_003e
IL_0038: ldc.i4.5
IL_0039: stloc.0
IL_003a: br.s IL_003e
IL_003c: ldc.i4.6
IL_003d: stloc.0
IL_003e: ldloc.0
IL_003f: ret
}
");
}
#endregion "regression tests"
#region Code Quality tests
[Fact]
public void BalancedSwitchDispatch_Double()
{
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2.1D));
Console.WriteLine(M(3.1D));
Console.WriteLine(M(4.1D));
Console.WriteLine(M(5.1D));
Console.WriteLine(M(6.1D));
Console.WriteLine(M(7.1D));
Console.WriteLine(M(8.1D));
Console.WriteLine(M(9.1D));
Console.WriteLine(M(10.1D));
Console.WriteLine(M(11.1D));
Console.WriteLine(M(12.1D));
Console.WriteLine(M(13.1D));
Console.WriteLine(M(14.1D));
Console.WriteLine(M(15.1D));
Console.WriteLine(M(16.1D));
Console.WriteLine(M(17.1D));
Console.WriteLine(M(18.1D));
Console.WriteLine(M(19.1D));
Console.WriteLine(M(20.1D));
Console.WriteLine(M(21.1D));
Console.WriteLine(M(22.1D));
Console.WriteLine(M(23.1D));
Console.WriteLine(M(24.1D));
Console.WriteLine(M(25.1D));
Console.WriteLine(M(26.1D));
Console.WriteLine(M(27.1D));
Console.WriteLine(M(28.1D));
Console.WriteLine(M(29.1D));
}
static int M(double d)
{
return d switch
{
>= 27.1D and < 29.1D => 19,
26.1D => 18,
9.1D => 5,
>= 2.1D and < 4.1D => 1,
12.1D => 8,
>= 21.1D and < 23.1D => 15,
19.1D => 13,
29.1D => 20,
>= 13.1D and < 15.1D => 9,
10.1D => 6,
15.1D => 10,
11.1D => 7,
4.1D => 2,
>= 16.1D and < 18.1D => 11,
>= 23.1D and < 25.1D => 16,
18.1D => 12,
>= 7.1D and < 9.1D => 4,
25.1D => 17,
20.1D => 14,
>= 5.1D and < 7.1D => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 499 (0x1f3)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.r8 13.1
IL_000a: blt.un IL_00fb
IL_000f: ldarg.0
IL_0010: ldc.r8 21.1
IL_0019: blt.un.s IL_008b
IL_001b: ldarg.0
IL_001c: ldc.r8 27.1
IL_0025: blt.un.s IL_004a
IL_0027: ldarg.0
IL_0028: ldc.r8 29.1
IL_0031: blt IL_0193
IL_0036: ldarg.0
IL_0037: ldc.r8 29.1
IL_0040: beq IL_01b3
IL_0045: br IL_01ef
IL_004a: ldarg.0
IL_004b: ldc.r8 23.1
IL_0054: blt IL_01a9
IL_0059: ldarg.0
IL_005a: ldc.r8 25.1
IL_0063: blt IL_01d3
IL_0068: ldarg.0
IL_0069: ldc.r8 25.1
IL_0072: beq IL_01e1
IL_0077: ldarg.0
IL_0078: ldc.r8 26.1
IL_0081: beq IL_0198
IL_0086: br IL_01ef
IL_008b: ldarg.0
IL_008c: ldc.r8 16.1
IL_0095: blt.un.s IL_00d8
IL_0097: ldarg.0
IL_0098: ldc.r8 18.1
IL_00a1: blt IL_01ce
IL_00a6: ldarg.0
IL_00a7: ldc.r8 18.1
IL_00b0: beq IL_01d8
IL_00b5: ldarg.0
IL_00b6: ldc.r8 19.1
IL_00bf: beq IL_01ae
IL_00c4: ldarg.0
IL_00c5: ldc.r8 20.1
IL_00ce: beq IL_01e6
IL_00d3: br IL_01ef
IL_00d8: ldarg.0
IL_00d9: ldc.r8 15.1
IL_00e2: blt IL_01b8
IL_00e7: ldarg.0
IL_00e8: ldc.r8 15.1
IL_00f1: beq IL_01c1
IL_00f6: br IL_01ef
IL_00fb: ldarg.0
IL_00fc: ldc.r8 7.1
IL_0105: blt.un.s IL_015f
IL_0107: ldarg.0
IL_0108: ldc.r8 9.1
IL_0111: blt IL_01dd
IL_0116: ldarg.0
IL_0117: ldc.r8 10.1
IL_0120: bgt.un.s IL_0142
IL_0122: ldarg.0
IL_0123: ldc.r8 9.1
IL_012c: beq.s IL_019d
IL_012e: ldarg.0
IL_012f: ldc.r8 10.1
IL_0138: beq IL_01bd
IL_013d: br IL_01ef
IL_0142: ldarg.0
IL_0143: ldc.r8 11.1
IL_014c: beq.s IL_01c6
IL_014e: ldarg.0
IL_014f: ldc.r8 12.1
IL_0158: beq.s IL_01a5
IL_015a: br IL_01ef
IL_015f: ldarg.0
IL_0160: ldc.r8 4.1
IL_0169: bge.un.s IL_0179
IL_016b: ldarg.0
IL_016c: ldc.r8 2.1
IL_0175: bge.s IL_01a1
IL_0177: br.s IL_01ef
IL_0179: ldarg.0
IL_017a: ldc.r8 5.1
IL_0183: bge.s IL_01eb
IL_0185: ldarg.0
IL_0186: ldc.r8 4.1
IL_018f: beq.s IL_01ca
IL_0191: br.s IL_01ef
IL_0193: ldc.i4.s 19
IL_0195: stloc.0
IL_0196: br.s IL_01f1
IL_0198: ldc.i4.s 18
IL_019a: stloc.0
IL_019b: br.s IL_01f1
IL_019d: ldc.i4.5
IL_019e: stloc.0
IL_019f: br.s IL_01f1
IL_01a1: ldc.i4.1
IL_01a2: stloc.0
IL_01a3: br.s IL_01f1
IL_01a5: ldc.i4.8
IL_01a6: stloc.0
IL_01a7: br.s IL_01f1
IL_01a9: ldc.i4.s 15
IL_01ab: stloc.0
IL_01ac: br.s IL_01f1
IL_01ae: ldc.i4.s 13
IL_01b0: stloc.0
IL_01b1: br.s IL_01f1
IL_01b3: ldc.i4.s 20
IL_01b5: stloc.0
IL_01b6: br.s IL_01f1
IL_01b8: ldc.i4.s 9
IL_01ba: stloc.0
IL_01bb: br.s IL_01f1
IL_01bd: ldc.i4.6
IL_01be: stloc.0
IL_01bf: br.s IL_01f1
IL_01c1: ldc.i4.s 10
IL_01c3: stloc.0
IL_01c4: br.s IL_01f1
IL_01c6: ldc.i4.7
IL_01c7: stloc.0
IL_01c8: br.s IL_01f1
IL_01ca: ldc.i4.2
IL_01cb: stloc.0
IL_01cc: br.s IL_01f1
IL_01ce: ldc.i4.s 11
IL_01d0: stloc.0
IL_01d1: br.s IL_01f1
IL_01d3: ldc.i4.s 16
IL_01d5: stloc.0
IL_01d6: br.s IL_01f1
IL_01d8: ldc.i4.s 12
IL_01da: stloc.0
IL_01db: br.s IL_01f1
IL_01dd: ldc.i4.4
IL_01de: stloc.0
IL_01df: br.s IL_01f1
IL_01e1: ldc.i4.s 17
IL_01e3: stloc.0
IL_01e4: br.s IL_01f1
IL_01e6: ldc.i4.s 14
IL_01e8: stloc.0
IL_01e9: br.s IL_01f1
IL_01eb: ldc.i4.3
IL_01ec: stloc.0
IL_01ed: br.s IL_01f1
IL_01ef: ldc.i4.0
IL_01f0: stloc.0
IL_01f1: ldloc.0
IL_01f2: ret
}
"
);
}
[Fact]
public void BalancedSwitchDispatch_Float()
{
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2.1F));
Console.WriteLine(M(3.1F));
Console.WriteLine(M(4.1F));
Console.WriteLine(M(5.1F));
Console.WriteLine(M(6.1F));
Console.WriteLine(M(7.1F));
Console.WriteLine(M(8.1F));
Console.WriteLine(M(9.1F));
Console.WriteLine(M(10.1F));
Console.WriteLine(M(11.1F));
Console.WriteLine(M(12.1F));
Console.WriteLine(M(13.1F));
Console.WriteLine(M(14.1F));
Console.WriteLine(M(15.1F));
Console.WriteLine(M(16.1F));
Console.WriteLine(M(17.1F));
Console.WriteLine(M(18.1F));
Console.WriteLine(M(19.1F));
Console.WriteLine(M(20.1F));
Console.WriteLine(M(21.1F));
Console.WriteLine(M(22.1F));
Console.WriteLine(M(23.1F));
Console.WriteLine(M(24.1F));
Console.WriteLine(M(25.1F));
Console.WriteLine(M(26.1F));
Console.WriteLine(M(27.1F));
Console.WriteLine(M(28.1F));
Console.WriteLine(M(29.1F));
}
static int M(float d)
{
return d switch
{
>= 27.1F and < 29.1F => 19,
26.1F => 18,
9.1F => 5,
>= 2.1F and < 4.1F => 1,
12.1F => 8,
>= 21.1F and < 23.1F => 15,
19.1F => 13,
29.1F => 20,
>= 13.1F and < 15.1F => 9,
10.1F => 6,
15.1F => 10,
11.1F => 7,
4.1F => 2,
>= 16.1F and < 18.1F => 11,
>= 23.1F and < 25.1F => 16,
18.1F => 12,
>= 7.1F and < 9.1F => 4,
25.1F => 17,
20.1F => 14,
>= 5.1F and < 7.1F => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 388 (0x184)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.r4 13.1
IL_0006: blt.un IL_00bb
IL_000b: ldarg.0
IL_000c: ldc.r4 21.1
IL_0011: blt.un.s IL_0067
IL_0013: ldarg.0
IL_0014: ldc.r4 27.1
IL_0019: blt.un.s IL_0036
IL_001b: ldarg.0
IL_001c: ldc.r4 29.1
IL_0021: blt IL_0124
IL_0026: ldarg.0
IL_0027: ldc.r4 29.1
IL_002c: beq IL_0144
IL_0031: br IL_0180
IL_0036: ldarg.0
IL_0037: ldc.r4 23.1
IL_003c: blt IL_013a
IL_0041: ldarg.0
IL_0042: ldc.r4 25.1
IL_0047: blt IL_0164
IL_004c: ldarg.0
IL_004d: ldc.r4 25.1
IL_0052: beq IL_0172
IL_0057: ldarg.0
IL_0058: ldc.r4 26.1
IL_005d: beq IL_0129
IL_0062: br IL_0180
IL_0067: ldarg.0
IL_0068: ldc.r4 16.1
IL_006d: blt.un.s IL_00a0
IL_006f: ldarg.0
IL_0070: ldc.r4 18.1
IL_0075: blt IL_015f
IL_007a: ldarg.0
IL_007b: ldc.r4 18.1
IL_0080: beq IL_0169
IL_0085: ldarg.0
IL_0086: ldc.r4 19.1
IL_008b: beq IL_013f
IL_0090: ldarg.0
IL_0091: ldc.r4 20.1
IL_0096: beq IL_0177
IL_009b: br IL_0180
IL_00a0: ldarg.0
IL_00a1: ldc.r4 15.1
IL_00a6: blt IL_0149
IL_00ab: ldarg.0
IL_00ac: ldc.r4 15.1
IL_00b1: beq IL_0152
IL_00b6: br IL_0180
IL_00bb: ldarg.0
IL_00bc: ldc.r4 7.1
IL_00c1: blt.un.s IL_0100
IL_00c3: ldarg.0
IL_00c4: ldc.r4 9.1
IL_00c9: blt IL_016e
IL_00ce: ldarg.0
IL_00cf: ldc.r4 10.1
IL_00d4: bgt.un.s IL_00eb
IL_00d6: ldarg.0
IL_00d7: ldc.r4 9.1
IL_00dc: beq.s IL_012e
IL_00de: ldarg.0
IL_00df: ldc.r4 10.1
IL_00e4: beq.s IL_014e
IL_00e6: br IL_0180
IL_00eb: ldarg.0
IL_00ec: ldc.r4 11.1
IL_00f1: beq.s IL_0157
IL_00f3: ldarg.0
IL_00f4: ldc.r4 12.1
IL_00f9: beq.s IL_0136
IL_00fb: br IL_0180
IL_0100: ldarg.0
IL_0101: ldc.r4 4.1
IL_0106: bge.un.s IL_0112
IL_0108: ldarg.0
IL_0109: ldc.r4 2.1
IL_010e: bge.s IL_0132
IL_0110: br.s IL_0180
IL_0112: ldarg.0
IL_0113: ldc.r4 5.1
IL_0118: bge.s IL_017c
IL_011a: ldarg.0
IL_011b: ldc.r4 4.1
IL_0120: beq.s IL_015b
IL_0122: br.s IL_0180
IL_0124: ldc.i4.s 19
IL_0126: stloc.0
IL_0127: br.s IL_0182
IL_0129: ldc.i4.s 18
IL_012b: stloc.0
IL_012c: br.s IL_0182
IL_012e: ldc.i4.5
IL_012f: stloc.0
IL_0130: br.s IL_0182
IL_0132: ldc.i4.1
IL_0133: stloc.0
IL_0134: br.s IL_0182
IL_0136: ldc.i4.8
IL_0137: stloc.0
IL_0138: br.s IL_0182
IL_013a: ldc.i4.s 15
IL_013c: stloc.0
IL_013d: br.s IL_0182
IL_013f: ldc.i4.s 13
IL_0141: stloc.0
IL_0142: br.s IL_0182
IL_0144: ldc.i4.s 20
IL_0146: stloc.0
IL_0147: br.s IL_0182
IL_0149: ldc.i4.s 9
IL_014b: stloc.0
IL_014c: br.s IL_0182
IL_014e: ldc.i4.6
IL_014f: stloc.0
IL_0150: br.s IL_0182
IL_0152: ldc.i4.s 10
IL_0154: stloc.0
IL_0155: br.s IL_0182
IL_0157: ldc.i4.7
IL_0158: stloc.0
IL_0159: br.s IL_0182
IL_015b: ldc.i4.2
IL_015c: stloc.0
IL_015d: br.s IL_0182
IL_015f: ldc.i4.s 11
IL_0161: stloc.0
IL_0162: br.s IL_0182
IL_0164: ldc.i4.s 16
IL_0166: stloc.0
IL_0167: br.s IL_0182
IL_0169: ldc.i4.s 12
IL_016b: stloc.0
IL_016c: br.s IL_0182
IL_016e: ldc.i4.4
IL_016f: stloc.0
IL_0170: br.s IL_0182
IL_0172: ldc.i4.s 17
IL_0174: stloc.0
IL_0175: br.s IL_0182
IL_0177: ldc.i4.s 14
IL_0179: stloc.0
IL_017a: br.s IL_0182
IL_017c: ldc.i4.3
IL_017d: stloc.0
IL_017e: br.s IL_0182
IL_0180: ldc.i4.0
IL_0181: stloc.0
IL_0182: ldloc.0
IL_0183: ret
}
"
);
}
[Fact]
public void BalancedSwitchDispatch_Decimal()
{
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2.1M));
Console.WriteLine(M(3.1M));
Console.WriteLine(M(4.1M));
Console.WriteLine(M(5.1M));
Console.WriteLine(M(6.1M));
Console.WriteLine(M(7.1M));
Console.WriteLine(M(8.1M));
Console.WriteLine(M(9.1M));
Console.WriteLine(M(10.1M));
Console.WriteLine(M(11.1M));
Console.WriteLine(M(12.1M));
Console.WriteLine(M(13.1M));
Console.WriteLine(M(14.1M));
Console.WriteLine(M(15.1M));
Console.WriteLine(M(16.1M));
Console.WriteLine(M(17.1M));
Console.WriteLine(M(18.1M));
Console.WriteLine(M(19.1M));
Console.WriteLine(M(20.1M));
Console.WriteLine(M(21.1M));
Console.WriteLine(M(22.1M));
Console.WriteLine(M(23.1M));
Console.WriteLine(M(24.1M));
Console.WriteLine(M(25.1M));
Console.WriteLine(M(26.1M));
Console.WriteLine(M(27.1M));
Console.WriteLine(M(28.1M));
Console.WriteLine(M(29.1M));
}
static int M(decimal d)
{
return d switch
{
>= 27.1M and < 29.1M => 19,
26.1M => 18,
9.1M => 5,
>= 2.1M and < 4.1M => 1,
12.1M => 8,
>= 21.1M and < 23.1M => 15,
19.1M => 13,
29.1M => 20,
>= 13.1M and < 15.1M => 9,
10.1M => 6,
15.1M => 10,
11.1M => 7,
4.1M => 2,
>= 16.1M and < 18.1M => 11,
>= 23.1M and < 25.1M => 16,
18.1M => 12,
>= 7.1M and < 9.1M => 4,
25.1M => 17,
20.1M => 14,
>= 5.1M and < 7.1M => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 751 (0x2ef)
.maxstack 6
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4 0x83
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000f: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0014: brfalse IL_019e
IL_0019: ldarg.0
IL_001a: ldc.i4 0xd3
IL_001f: ldc.i4.0
IL_0020: ldc.i4.0
IL_0021: ldc.i4.0
IL_0022: ldc.i4.1
IL_0023: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0028: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_002d: brfalse IL_00e8
IL_0032: ldarg.0
IL_0033: ldc.i4 0x10f
IL_0038: ldc.i4.0
IL_0039: ldc.i4.0
IL_003a: ldc.i4.0
IL_003b: ldc.i4.1
IL_003c: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0041: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0046: brfalse.s IL_007f
IL_0048: ldarg.0
IL_0049: ldc.i4 0x123
IL_004e: ldc.i4.0
IL_004f: ldc.i4.0
IL_0050: ldc.i4.0
IL_0051: ldc.i4.1
IL_0052: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0057: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_005c: brtrue IL_028f
IL_0061: ldarg.0
IL_0062: ldc.i4 0x123
IL_0067: ldc.i4.0
IL_0068: ldc.i4.0
IL_0069: ldc.i4.0
IL_006a: ldc.i4.1
IL_006b: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0070: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0075: brtrue IL_02af
IL_007a: br IL_02eb
IL_007f: ldarg.0
IL_0080: ldc.i4 0xe7
IL_0085: ldc.i4.0
IL_0086: ldc.i4.0
IL_0087: ldc.i4.0
IL_0088: ldc.i4.1
IL_0089: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_008e: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_0093: brtrue IL_02a5
IL_0098: ldarg.0
IL_0099: ldc.i4 0xfb
IL_009e: ldc.i4.0
IL_009f: ldc.i4.0
IL_00a0: ldc.i4.0
IL_00a1: ldc.i4.1
IL_00a2: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00a7: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_00ac: brtrue IL_02cf
IL_00b1: ldarg.0
IL_00b2: ldc.i4 0xfb
IL_00b7: ldc.i4.0
IL_00b8: ldc.i4.0
IL_00b9: ldc.i4.0
IL_00ba: ldc.i4.1
IL_00bb: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00c0: call ""bool decimal.op_Equality(decimal, decimal)""
IL_00c5: brtrue IL_02dd
IL_00ca: ldarg.0
IL_00cb: ldc.i4 0x105
IL_00d0: ldc.i4.0
IL_00d1: ldc.i4.0
IL_00d2: ldc.i4.0
IL_00d3: ldc.i4.1
IL_00d4: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00d9: call ""bool decimal.op_Equality(decimal, decimal)""
IL_00de: brtrue IL_0294
IL_00e3: br IL_02eb
IL_00e8: ldarg.0
IL_00e9: ldc.i4 0xa1
IL_00ee: ldc.i4.0
IL_00ef: ldc.i4.0
IL_00f0: ldc.i4.0
IL_00f1: ldc.i4.1
IL_00f2: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_00f7: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_00fc: brfalse.s IL_0167
IL_00fe: ldarg.0
IL_00ff: ldc.i4 0xb5
IL_0104: ldc.i4.0
IL_0105: ldc.i4.0
IL_0106: ldc.i4.0
IL_0107: ldc.i4.1
IL_0108: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_010d: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_0112: brtrue IL_02ca
IL_0117: ldarg.0
IL_0118: ldc.i4 0xb5
IL_011d: ldc.i4.0
IL_011e: ldc.i4.0
IL_011f: ldc.i4.0
IL_0120: ldc.i4.1
IL_0121: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0126: call ""bool decimal.op_Equality(decimal, decimal)""
IL_012b: brtrue IL_02d4
IL_0130: ldarg.0
IL_0131: ldc.i4 0xbf
IL_0136: ldc.i4.0
IL_0137: ldc.i4.0
IL_0138: ldc.i4.0
IL_0139: ldc.i4.1
IL_013a: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_013f: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0144: brtrue IL_02aa
IL_0149: ldarg.0
IL_014a: ldc.i4 0xc9
IL_014f: ldc.i4.0
IL_0150: ldc.i4.0
IL_0151: ldc.i4.0
IL_0152: ldc.i4.1
IL_0153: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0158: call ""bool decimal.op_Equality(decimal, decimal)""
IL_015d: brtrue IL_02e2
IL_0162: br IL_02eb
IL_0167: ldarg.0
IL_0168: ldc.i4 0x97
IL_016d: ldc.i4.0
IL_016e: ldc.i4.0
IL_016f: ldc.i4.0
IL_0170: ldc.i4.1
IL_0171: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0176: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_017b: brtrue IL_02b4
IL_0180: ldarg.0
IL_0181: ldc.i4 0x97
IL_0186: ldc.i4.0
IL_0187: ldc.i4.0
IL_0188: ldc.i4.0
IL_0189: ldc.i4.1
IL_018a: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_018f: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0194: brtrue IL_02bd
IL_0199: br IL_02eb
IL_019e: ldarg.0
IL_019f: ldc.i4.s 71
IL_01a1: ldc.i4.0
IL_01a2: ldc.i4.0
IL_01a3: ldc.i4.0
IL_01a4: ldc.i4.1
IL_01a5: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01aa: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_01af: brfalse IL_023c
IL_01b4: ldarg.0
IL_01b5: ldc.i4.s 91
IL_01b7: ldc.i4.0
IL_01b8: ldc.i4.0
IL_01b9: ldc.i4.0
IL_01ba: ldc.i4.1
IL_01bb: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01c0: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_01c5: brtrue IL_02d9
IL_01ca: ldarg.0
IL_01cb: ldc.i4.s 101
IL_01cd: ldc.i4.0
IL_01ce: ldc.i4.0
IL_01cf: ldc.i4.0
IL_01d0: ldc.i4.1
IL_01d1: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01d6: call ""bool decimal.op_LessThanOrEqual(decimal, decimal)""
IL_01db: brfalse.s IL_020e
IL_01dd: ldarg.0
IL_01de: ldc.i4.s 91
IL_01e0: ldc.i4.0
IL_01e1: ldc.i4.0
IL_01e2: ldc.i4.0
IL_01e3: ldc.i4.1
IL_01e4: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01e9: call ""bool decimal.op_Equality(decimal, decimal)""
IL_01ee: brtrue IL_0299
IL_01f3: ldarg.0
IL_01f4: ldc.i4.s 101
IL_01f6: ldc.i4.0
IL_01f7: ldc.i4.0
IL_01f8: ldc.i4.0
IL_01f9: ldc.i4.1
IL_01fa: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_01ff: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0204: brtrue IL_02b9
IL_0209: br IL_02eb
IL_020e: ldarg.0
IL_020f: ldc.i4.s 111
IL_0211: ldc.i4.0
IL_0212: ldc.i4.0
IL_0213: ldc.i4.0
IL_0214: ldc.i4.1
IL_0215: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_021a: call ""bool decimal.op_Equality(decimal, decimal)""
IL_021f: brtrue IL_02c2
IL_0224: ldarg.0
IL_0225: ldc.i4.s 121
IL_0227: ldc.i4.0
IL_0228: ldc.i4.0
IL_0229: ldc.i4.0
IL_022a: ldc.i4.1
IL_022b: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0230: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0235: brtrue.s IL_02a1
IL_0237: br IL_02eb
IL_023c: ldarg.0
IL_023d: ldc.i4.s 41
IL_023f: ldc.i4.0
IL_0240: ldc.i4.0
IL_0241: ldc.i4.0
IL_0242: ldc.i4.1
IL_0243: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0248: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_024d: brfalse.s IL_0267
IL_024f: ldarg.0
IL_0250: ldc.i4.s 21
IL_0252: ldc.i4.0
IL_0253: ldc.i4.0
IL_0254: ldc.i4.0
IL_0255: ldc.i4.1
IL_0256: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_025b: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0260: brtrue.s IL_029d
IL_0262: br IL_02eb
IL_0267: ldarg.0
IL_0268: ldc.i4.s 51
IL_026a: ldc.i4.0
IL_026b: ldc.i4.0
IL_026c: ldc.i4.0
IL_026d: ldc.i4.1
IL_026e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0273: call ""bool decimal.op_GreaterThanOrEqual(decimal, decimal)""
IL_0278: brtrue.s IL_02e7
IL_027a: ldarg.0
IL_027b: ldc.i4.s 41
IL_027d: ldc.i4.0
IL_027e: ldc.i4.0
IL_027f: ldc.i4.0
IL_0280: ldc.i4.1
IL_0281: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0286: call ""bool decimal.op_Equality(decimal, decimal)""
IL_028b: brtrue.s IL_02c6
IL_028d: br.s IL_02eb
IL_028f: ldc.i4.s 19
IL_0291: stloc.0
IL_0292: br.s IL_02ed
IL_0294: ldc.i4.s 18
IL_0296: stloc.0
IL_0297: br.s IL_02ed
IL_0299: ldc.i4.5
IL_029a: stloc.0
IL_029b: br.s IL_02ed
IL_029d: ldc.i4.1
IL_029e: stloc.0
IL_029f: br.s IL_02ed
IL_02a1: ldc.i4.8
IL_02a2: stloc.0
IL_02a3: br.s IL_02ed
IL_02a5: ldc.i4.s 15
IL_02a7: stloc.0
IL_02a8: br.s IL_02ed
IL_02aa: ldc.i4.s 13
IL_02ac: stloc.0
IL_02ad: br.s IL_02ed
IL_02af: ldc.i4.s 20
IL_02b1: stloc.0
IL_02b2: br.s IL_02ed
IL_02b4: ldc.i4.s 9
IL_02b6: stloc.0
IL_02b7: br.s IL_02ed
IL_02b9: ldc.i4.6
IL_02ba: stloc.0
IL_02bb: br.s IL_02ed
IL_02bd: ldc.i4.s 10
IL_02bf: stloc.0
IL_02c0: br.s IL_02ed
IL_02c2: ldc.i4.7
IL_02c3: stloc.0
IL_02c4: br.s IL_02ed
IL_02c6: ldc.i4.2
IL_02c7: stloc.0
IL_02c8: br.s IL_02ed
IL_02ca: ldc.i4.s 11
IL_02cc: stloc.0
IL_02cd: br.s IL_02ed
IL_02cf: ldc.i4.s 16
IL_02d1: stloc.0
IL_02d2: br.s IL_02ed
IL_02d4: ldc.i4.s 12
IL_02d6: stloc.0
IL_02d7: br.s IL_02ed
IL_02d9: ldc.i4.4
IL_02da: stloc.0
IL_02db: br.s IL_02ed
IL_02dd: ldc.i4.s 17
IL_02df: stloc.0
IL_02e0: br.s IL_02ed
IL_02e2: ldc.i4.s 14
IL_02e4: stloc.0
IL_02e5: br.s IL_02ed
IL_02e7: ldc.i4.3
IL_02e8: stloc.0
IL_02e9: br.s IL_02ed
IL_02eb: ldc.i4.0
IL_02ec: stloc.0
IL_02ed: ldloc.0
IL_02ee: ret
}
"
);
}
[Fact]
public void BalancedSwitchDispatch_Uint32()
{
// We do not currently detect that the set of values that we are dispatching on is a compact set,
// which would enable us to use the IL switch instruction even though the input was expressed using
// a set of relational comparisons.
var source = @"using System;
class C
{
static void Main()
{
Console.WriteLine(M(2U));
Console.WriteLine(M(3U));
Console.WriteLine(M(4U));
Console.WriteLine(M(5U));
Console.WriteLine(M(6U));
Console.WriteLine(M(7U));
Console.WriteLine(M(8U));
Console.WriteLine(M(9U));
Console.WriteLine(M(10U));
Console.WriteLine(M(11U));
Console.WriteLine(M(12U));
Console.WriteLine(M(13U));
Console.WriteLine(M(14U));
Console.WriteLine(M(15U));
Console.WriteLine(M(16U));
Console.WriteLine(M(17U));
Console.WriteLine(M(18U));
Console.WriteLine(M(19U));
Console.WriteLine(M(20U));
Console.WriteLine(M(21U));
Console.WriteLine(M(22U));
Console.WriteLine(M(23U));
Console.WriteLine(M(24U));
Console.WriteLine(M(25U));
Console.WriteLine(M(26U));
Console.WriteLine(M(27U));
Console.WriteLine(M(28U));
Console.WriteLine(M(29U));
}
static int M(uint d)
{
return d switch
{
>= 27U and < 29U => 19,
26U => 18,
9U => 5,
>= 2U and < 4U => 1,
12U => 8,
>= 21U and < 23U => 15,
19U => 13,
29U => 20,
>= 13U and < 15U => 9,
10U => 6,
15U => 10,
11U => 7,
4U => 2,
>= 16U and < 18U => 11,
>= 23U and < 25U => 16,
18U => 12,
>= 7U and < 9U => 4,
25U => 17,
20U => 14,
>= 5U and < 7U => 3,
_ => 0,
};
}
}
";
var expectedOutput =
@"1
1
2
3
3
4
4
5
6
7
8
9
9
10
11
11
12
13
14
15
15
16
16
17
18
19
19
20
";
var compVerifier = CompileAndVerify(source,
options: TestOptions.ReleaseExe.WithOutputKind(OutputKind.ConsoleApplication),
parseOptions: TestOptions.RegularWithPatternCombinators,
expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M", @"
{
// Code size 243 (0xf3)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 21
IL_0003: blt.un.s IL_0039
IL_0005: ldarg.0
IL_0006: ldc.i4.s 27
IL_0008: blt.un.s IL_001f
IL_000a: ldarg.0
IL_000b: ldc.i4.s 29
IL_000d: blt.un IL_0093
IL_0012: ldarg.0
IL_0013: ldc.i4.s 29
IL_0015: beq IL_00b3
IL_001a: br IL_00ef
IL_001f: ldarg.0
IL_0020: ldc.i4.s 23
IL_0022: blt.un IL_00a9
IL_0027: ldarg.0
IL_0028: ldc.i4.s 25
IL_002a: blt.un IL_00d3
IL_002f: ldarg.0
IL_0030: ldc.i4.s 26
IL_0032: beq.s IL_0098
IL_0034: br IL_00e1
IL_0039: ldarg.0
IL_003a: ldc.i4.s 13
IL_003c: blt.un.s IL_0061
IL_003e: ldarg.0
IL_003f: ldc.i4.s 15
IL_0041: blt.un.s IL_00b8
IL_0043: ldarg.0
IL_0044: ldc.i4.s 18
IL_0046: bge.un.s IL_004f
IL_0048: ldarg.0
IL_0049: ldc.i4.s 15
IL_004b: beq.s IL_00c1
IL_004d: br.s IL_00ce
IL_004f: ldarg.0
IL_0050: ldc.i4.s 18
IL_0052: beq IL_00d8
IL_0057: ldarg.0
IL_0058: ldc.i4.s 19
IL_005a: beq.s IL_00ae
IL_005c: br IL_00e6
IL_0061: ldarg.0
IL_0062: ldc.i4.4
IL_0063: bge.un.s IL_006e
IL_0065: ldarg.0
IL_0066: ldc.i4.2
IL_0067: bge.un.s IL_00a1
IL_0069: br IL_00ef
IL_006e: ldarg.0
IL_006f: ldc.i4.7
IL_0070: blt.un.s IL_008d
IL_0072: ldarg.0
IL_0073: ldc.i4.s 9
IL_0075: sub
IL_0076: switch (
IL_009d,
IL_00bd,
IL_00c6,
IL_00a5)
IL_008b: br.s IL_00dd
IL_008d: ldarg.0
IL_008e: ldc.i4.4
IL_008f: beq.s IL_00ca
IL_0091: br.s IL_00eb
IL_0093: ldc.i4.s 19
IL_0095: stloc.0
IL_0096: br.s IL_00f1
IL_0098: ldc.i4.s 18
IL_009a: stloc.0
IL_009b: br.s IL_00f1
IL_009d: ldc.i4.5
IL_009e: stloc.0
IL_009f: br.s IL_00f1
IL_00a1: ldc.i4.1
IL_00a2: stloc.0
IL_00a3: br.s IL_00f1
IL_00a5: ldc.i4.8
IL_00a6: stloc.0
IL_00a7: br.s IL_00f1
IL_00a9: ldc.i4.s 15
IL_00ab: stloc.0
IL_00ac: br.s IL_00f1
IL_00ae: ldc.i4.s 13
IL_00b0: stloc.0
IL_00b1: br.s IL_00f1
IL_00b3: ldc.i4.s 20
IL_00b5: stloc.0
IL_00b6: br.s IL_00f1
IL_00b8: ldc.i4.s 9
IL_00ba: stloc.0
IL_00bb: br.s IL_00f1
IL_00bd: ldc.i4.6
IL_00be: stloc.0
IL_00bf: br.s IL_00f1
IL_00c1: ldc.i4.s 10
IL_00c3: stloc.0
IL_00c4: br.s IL_00f1
IL_00c6: ldc.i4.7
IL_00c7: stloc.0
IL_00c8: br.s IL_00f1
IL_00ca: ldc.i4.2
IL_00cb: stloc.0
IL_00cc: br.s IL_00f1
IL_00ce: ldc.i4.s 11
IL_00d0: stloc.0
IL_00d1: br.s IL_00f1
IL_00d3: ldc.i4.s 16
IL_00d5: stloc.0
IL_00d6: br.s IL_00f1
IL_00d8: ldc.i4.s 12
IL_00da: stloc.0
IL_00db: br.s IL_00f1
IL_00dd: ldc.i4.4
IL_00de: stloc.0
IL_00df: br.s IL_00f1
IL_00e1: ldc.i4.s 17
IL_00e3: stloc.0
IL_00e4: br.s IL_00f1
IL_00e6: ldc.i4.s 14
IL_00e8: stloc.0
IL_00e9: br.s IL_00f1
IL_00eb: ldc.i4.3
IL_00ec: stloc.0
IL_00ed: br.s IL_00f1
IL_00ef: ldc.i4.0
IL_00f0: stloc.0
IL_00f1: ldloc.0
IL_00f2: ret
}
"
);
}
#endregion Code Quality tests
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicAnalysisResourceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests
{
public class DynamicAnalysisResourceTests : CSharpTestBase
{
const string InstrumentationHelperSource = @"
namespace Microsoft.CodeAnalysis.Runtime
{
public static class Instrumentation
{
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int fileIndex, ref bool[] payload, int payloadLength)
{
return payload;
}
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int[] fileIndices, ref bool[] payload, int payloadLength)
{
return payload;
}
public static void FlushPayload()
{
}
}
}
";
const string ExampleSource = @"
using System;
public class C
{
public static void Main()
{
Console.WriteLine(123);
Console.WriteLine(123);
}
public static int Fred => 3;
public static int Barney(int x) => x;
public static int Wilma
{
get { return 12; }
set { }
}
public static int Betty { get; }
public static int Pebbles { get; set; }
}
";
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)]
public void TestSpansPresentInResource()
{
var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
VerifyDocuments(reader, reader.Documents,
@"'C:\myproject\doc1.cs' 44-3F-7C-A1-EF-CA-A8-16-40-D2-09-4F-3E-52-7C-44-8D-22-C8-02 (SHA1)");
Assert.Equal(13, reader.Methods.Length);
string[] sourceLines = ExampleSource.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines, // Main
new SpanResult(5, 4, 9, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 31, "Console.WriteLine(123)"),
new SpanResult(8, 8, 8, 31, "Console.WriteLine(123)"));
VerifySpans(reader, reader.Methods[1], sourceLines, // Fred get
new SpanResult(11, 4, 11, 32, "public static int Fred => 3"),
new SpanResult(11, 30, 11, 31, "3"));
VerifySpans(reader, reader.Methods[2], sourceLines, // Barney
new SpanResult(13, 4, 13, 41, "public static int Barney(int x) => x"),
new SpanResult(13, 39, 13, 40, "x"));
VerifySpans(reader, reader.Methods[3], sourceLines, // Wilma get
new SpanResult(17, 8, 17, 26, "get { return 12; }"),
new SpanResult(17, 14, 17, 24, "return 12"));
VerifySpans(reader, reader.Methods[4], sourceLines, // Wilma set
new SpanResult(18, 8, 18, 15, "set { }"));
VerifySpans(reader, reader.Methods[5], sourceLines, // Betty get
new SpanResult(21, 4, 21, 36, "public static int Betty { get; }"),
new SpanResult(21, 30, 21, 34, "get"));
VerifySpans(reader, reader.Methods[6], sourceLines, // Pebbles get
new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"),
new SpanResult(23, 32, 23, 36, "get"));
VerifySpans(reader, reader.Methods[7], sourceLines, // Pebbles set
new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"),
new SpanResult(23, 37, 23, 41, "set"));
VerifySpans(reader, reader.Methods[8]);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)]
public void ResourceStatementKinds()
{
string source = @"
using System;
public class C
{
public static void Main()
{
int z = 11;
int x = z + 10;
switch (z)
{
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
if (x > 10)
{
x++;
}
else
{
x--;
}
for (int y = 0; y < 50; y++)
{
if (y < 30)
{
x++;
continue;
}
else
break;
}
int[] a = new int[] { 1, 2, 3, 4 };
foreach (int i in a)
{
x++;
}
while (x < 100)
{
x++;
}
try
{
x++;
if (x > 10)
{
throw new System.Exception();
}
x++;
}
catch (System.Exception e)
{
x++;
}
finally
{
x++;
}
lock (new object())
{
;
}
Console.WriteLine(x);
try
{
using ((System.IDisposable)new object())
{
;
}
}
catch (System.Exception e)
{
}
return;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
VerifyDocuments(reader, reader.Documents,
@"'C:\myproject\doc1.cs' 6A-DC-C0-8A-16-CB-7C-A5-99-8B-2E-0C-3C-81-69-2C-B2-10-EE-F1 (SHA1)");
Assert.Equal(6, reader.Methods.Length);
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 89, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "int z = 11"),
new SpanResult(8, 8, 8, 23, "int x = z + 10"),
new SpanResult(12, 16, 12, 22, "break"),
new SpanResult(14, 16, 14, 22, "break"),
new SpanResult(16, 16, 16, 22, "break"),
new SpanResult(18, 16, 18, 22, "break"),
new SpanResult(9, 16, 9, 17, "z"),
new SpanResult(23, 12, 23, 16, "x++"),
new SpanResult(27, 12, 27, 16, "x--"),
new SpanResult(21, 12, 21, 18, "x > 10"),
new SpanResult(30, 17, 30, 22, "y = 0"),
new SpanResult(30, 32, 30, 35, "y++"),
new SpanResult(34, 16, 34, 20, "x++"),
new SpanResult(35, 16, 35, 25, "continue"),
new SpanResult(38, 16, 38, 22, "break"),
new SpanResult(32, 16, 32, 22, "y < 30"),
new SpanResult(41, 8, 41, 43, "int[] a = new int[] { 1, 2, 3, 4 }"),
new SpanResult(44, 12, 44, 16, "x++"),
new SpanResult(42, 26, 42, 27, "a"),
new SpanResult(49, 12, 49, 16, "x++"),
new SpanResult(47, 15, 47, 22, "x < 100"),
new SpanResult(54, 12, 54, 16, "x++"),
new SpanResult(57, 16, 57, 45, "throw new System.Exception()"),
new SpanResult(55, 16, 55, 22, "x > 10"),
new SpanResult(59, 12, 59, 16, "x++"),
new SpanResult(63, 12, 63, 16, "x++"),
new SpanResult(67, 12, 67, 16, "x++"),
new SpanResult(72, 12, 72, 13, ";"),
new SpanResult(70, 14, 70, 26, "new object()"),
new SpanResult(75, 8, 75, 29, "Console.WriteLine(x)"),
new SpanResult(81, 16, 81, 17, ";"),
new SpanResult(79, 19, 79, 51, "(System.IDisposable)new object()"),
new SpanResult(88, 8, 88, 15, "return"));
VerifySpans(reader, reader.Methods[1]);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)]
public void TestMethodSpansWithAttributes()
{
string source = @"
using System;
using System.Security;
public class C
{
static int x;
public static void Main() // Method 0
{
Fred();
}
[Obsolete()]
static void Fred() // Method 1
{
}
static C() // Method 2
{
x = 12;
}
[Obsolete()]
public C() // Method 3
{
}
int Wilma
{
[SecurityCritical]
get { return 12; } // Method 4
}
[Obsolete()]
int Betty => 13; // Method 5
[SecurityCritical]
int Pebbles() // Method 6
{
return 3;
}
[SecurityCritical]
ref int BamBam(ref int x) // Method 7
{
return ref x;
}
[SecurityCritical]
C(int x) // Method 8
{
}
[Obsolete()]
public int Barney => 13; // Method 9
[SecurityCritical]
public static C operator +(C a, C b) // Method 10
{
return a;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
VerifyDocuments(reader, reader.Documents,
@"'C:\myproject\doc1.cs' A3-08-94-55-7C-64-8D-C7-61-7A-11-0B-4B-68-2C-3B-51-C3-C4-58 (SHA1)");
Assert.Equal(15, reader.Methods.Length);
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(8, 4, 11, 5, "public static void Main()"),
new SpanResult(10, 8, 10, 15, "Fred()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(14, 4, 16, 5, "static void Fred()"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(18, 4, 21, 5, "static C()"),
new SpanResult(20, 8, 20, 15, "x = 12"));
VerifySpans(reader, reader.Methods[3], sourceLines,
new SpanResult(24, 4, 26, 5, "public C()"));
VerifySpans(reader, reader.Methods[4], sourceLines,
new SpanResult(31, 8, 31, 26, "get {"),
new SpanResult(31, 14, 31, 24, "return 12"));
VerifySpans(reader, reader.Methods[5], sourceLines,
new SpanResult(35, 4, 35, 20, "int Betty"),
new SpanResult(35, 17, 35, 19, "13"));
VerifySpans(reader, reader.Methods[6], sourceLines,
new SpanResult(38, 4, 41, 5, "int Pebbles()"),
new SpanResult(40, 8, 40, 17, "return 3"));
VerifySpans(reader, reader.Methods[7], sourceLines,
new SpanResult(44, 4, 47, 5, "ref int BamBam"),
new SpanResult(46, 8, 46, 21, "return ref x"));
VerifySpans(reader, reader.Methods[8], sourceLines,
new SpanResult(50, 4, 52, 5, "C(int x)"));
VerifySpans(reader, reader.Methods[9], sourceLines,
new SpanResult(55, 4, 55, 28, "public int Barney"),
new SpanResult(55, 25, 55, 27, "13"));
VerifySpans(reader, reader.Methods[10], sourceLines,
new SpanResult(58, 4, 61, 5, "public static C operator +"),
new SpanResult(60, 8, 60, 17, "return a"));
}
[Fact]
public void TestPatternSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static string Operate(Person p) // Method 1
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s when (s.GPA < 2.0):
return $""Failing Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 11, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 34, "Student s = new Student()"),
new SpanResult(8, 8, 8, 24, "s.Name = \"Bozo\""),
new SpanResult(9, 8, 9, 20, "s.GPA = 2.3"),
new SpanResult(10, 8, 10, 19, "Operate(s)"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(13, 4, 28, 5, "static string Operate(Person p)"),
new SpanResult(17, 27, 17, 43, "when s.GPA > 3.5"),
new SpanResult(19, 27, 19, 45, "when (s.GPA < 2.0)"),
new SpanResult(18, 16, 18, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""),
new SpanResult(20, 16, 20, 64, "return $\"Failing Student {s.Name} ({s.GPA:N1})\""),
new SpanResult(22, 16, 22, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""),
new SpanResult(24, 16, 24, 58, "return $\"Teacher {t.Name} of {t.Subject}\""),
new SpanResult(26, 16, 26, 42, "return $\"Person {p.Name}\""),
new SpanResult(15, 16, 15, 17, "p"));
}
[Fact]
public void TestDeconstructionSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
var (x, y) = new C();
}
public void Deconstruct(out int x, out int y)
{
x = 1;
y = 2;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 29, "var (x, y) = new C()"));
}
[Fact]
public void TestForeachSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
C[] a = null;
foreach
(var x
in a)
;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 12, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 21, "C[] a = null"),
new SpanResult(11, 12, 11, 13, ";"),
new SpanResult(10, 15, 10, 16, "a")
);
}
[Fact]
public void TestForeachDeconstructionSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
C[] a = null;
foreach
(var (x, y)
in a)
;
}
public void Deconstruct(out int x, out int y)
{
x = 1;
y = 2;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 12, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 21, "C[] a = null"),
new SpanResult(11, 12, 11, 13, ";"),
new SpanResult(10, 15, 10, 16, "a")
);
}
[Fact]
public void TestFieldInitializerSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
C local = new C(); local = new C(1, 2);
}
static int Init() => 33; // Method 2
C() // Method 3
{
_z = 12;
}
static C() // Method 4
{
s_z = 123;
}
int _x = Init();
int _y = Init() + 12;
int _z;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z;
C(int x) // Method 5
{
_z = x;
}
C(int a, int b) // Method 6
{
_z = a + b;
}
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 13, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 26, "C local = new C()"),
new SpanResult(12, 27, 12, 47, "local = new C(1, 2)"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(15, 4, 15, 28, "static int Init() => 33"),
new SpanResult(15, 25, 15, 27, "33"));
VerifySpans(reader, reader.Methods[3], sourceLines,
new SpanResult(17, 4, 20, 5, "C()"),
new SpanResult(27, 13, 27, 19, "Init()"),
new SpanResult(28, 13, 28, 24, "Init() + 12"),
new SpanResult(44, 25, 44, 27, "15"),
new SpanResult(19, 8, 19, 16, "_z = 12"));
VerifySpans(reader, reader.Methods[4], sourceLines,
new SpanResult(22, 4, 25, 5, "static C()"),
new SpanResult(30, 21, 30, 27, "Init()"),
new SpanResult(31, 21, 31, 33, "Init() + 153"),
new SpanResult(45, 32, 45, 35, "255"),
new SpanResult(24, 8, 24, 18, "s_z = 123"));
VerifySpans(reader, reader.Methods[5], sourceLines,
new SpanResult(34, 4, 37, 5, "C(int x)"),
new SpanResult(27, 13, 27, 19, "Init()"),
new SpanResult(28, 13, 28, 24, "Init() + 12"),
new SpanResult(44, 25, 44, 27, "15"),
new SpanResult(36, 8, 36, 15, "_z = x"));
VerifySpans(reader, reader.Methods[6], sourceLines,
new SpanResult(39, 4, 42, 5, "C(int a, int b)"),
new SpanResult(27, 13, 27, 19, "Init()"),
new SpanResult(28, 13, 28, 24, "Init() + 12"),
new SpanResult(44, 25, 44, 27, "15"),
new SpanResult(41, 8, 41, 19, "_z = a + b"));
}
[Fact]
public void TestImplicitConstructorSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
C local = new C();
}
static int Init() => 33; // Method 2
int _x = Init();
int _y = Init() + 12;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z = 144;
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 13, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 26, "C local = new C()"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(15, 4, 15, 28, "static int Init() => 33"),
new SpanResult(15, 25, 15, 27, "33"));
VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized instance constructor
new SpanResult(17, 13, 17, 19, "Init()"),
new SpanResult(18, 13, 18, 24, "Init() + 12"),
new SpanResult(23, 25, 23, 27, "15"));
VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor
new SpanResult(19, 21, 19, 27, "Init()"),
new SpanResult(20, 21, 20, 33, "Init() + 153"),
new SpanResult(21, 21, 21, 24, "144"),
new SpanResult(24, 32, 24, 35, "255"));
}
[Fact]
public void TestImplicitConstructorsWithLambdasSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
int y = s_c._function();
D d = new D();
int z = d._c._function();
int zz = D.s_c._function();
}
public C(Func<int> f) // Method 2
{
_function = f;
}
static C s_c = new C(() => 115);
Func<int> _function;
}
class D
{
public C _c = new C(() => 120);
public static C s_c = new C(() => 144);
public C _c1 = new C(() => 130);
public static C s_c1 = new C(() => 156);
}
partial struct E
{
}
partial struct E
{
public static C s_c = new C(() => 1444);
public static C s_c1 = new C(() => { return 1567; });
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 16, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 32, "int y = s_c._function()"),
new SpanResult(13, 8, 13, 22, "D d = new D()"),
new SpanResult(14, 8, 14, 33, "int z = d._c._function()"),
new SpanResult(15, 8, 15, 35, "int zz = D.s_c._function()"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(18, 4, 21, 5, "public C(Func<int> f)"),
new SpanResult(20, 8, 20, 22, "_function = f"));
VerifySpans(reader, reader.Methods[3], sourceLines, // Synthesized static constructor for C
new SpanResult(23, 31, 23, 34, "115"),
new SpanResult(23, 19, 23, 35, "new C(() => 115)"));
VerifySpans(reader, reader.Methods[4], sourceLines, // Synthesized instance constructor for D
new SpanResult(29, 30, 29, 33, "120"),
new SpanResult(31, 31, 31, 34, "130"),
new SpanResult(29, 18, 29, 34, "new C(() => 120)"),
new SpanResult(31, 19, 31, 35, "new C(() => 130)"));
VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized static constructor for D
new SpanResult(30, 38, 30, 41, "144"),
new SpanResult(32, 39, 32, 42, "156"),
new SpanResult(30, 26, 30, 42, "new C(() => 144)"),
new SpanResult(32, 27, 32, 43, "new C(() => 156"));
VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor for E
new SpanResult(41, 38, 41, 42, "1444"),
new SpanResult(42, 41, 42, 53, "return 1567"),
new SpanResult(41, 26, 41, 43, "new C(() => 1444)"),
new SpanResult(42, 27, 42, 56, "new C(() => { return 1567; })"));
}
[Fact]
public void TestLocalFunctionWithLambdaSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
new D().M1();
}
}
public class D
{
public void M1() // Method 3
{
L1();
void L1()
{
var f = new Func<int>(
() => 1
);
f();
var f1 = new Func<int>(
() => { return 2; }
);
var f2 = new Func<int, int>(
(x) => x + 3
);
var f3 = new Func<int, int>(
x => x + 4
);
}
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 13, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 21, "new D().M1()"));
VerifySpans(reader, reader.Methods[3], sourceLines,
new SpanResult(18, 4, 41, 5, "public void M1()"),
new SpanResult(20, 8, 20, 13, "L1()"),
new SpanResult(24, 22, 24, 23, "1"),
new SpanResult(23, 12, 25, 14, "var f = new Func<int>"),
new SpanResult(27, 12, 27, 16, "f()"),
new SpanResult(30, 24, 30, 33, "return 2"),
new SpanResult(29, 12, 31, 14, "var f1 = new Func<int>"),
new SpanResult(34, 23, 34, 28, "x + 3"),
new SpanResult(33, 12, 35, 14, "var f2 = new Func<int, int>"),
new SpanResult(38, 21, 38, 26, "x + 4"),
new SpanResult(37, 12, 39, 14, "var f3 = new Func<int, int>"));
}
[Fact]
public void TestDynamicAnalysisResourceMissingWhenInstrumentationFlagIsDisabled()
{
var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default);
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
Assert.Null(reader);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void EmptyStaticConstructor_WithEnableTestCoverage()
{
string source = @"
#nullable enable
class C
{
static C()
{
}
static object obj = null!;
}" + InstrumentationHelperSource;
var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage));
CompileAndVerify(source, emitOptions: emitOptions).VerifyIL("C..cctor()",
@"{
// Code size 57 (0x39)
.maxstack 5
.locals init (bool[] V_0)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""C..cctor()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""C..cctor()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""C..cctor()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.1
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SynthesizedStaticConstructor_WithEnableTestCoverage()
{
string source = @"
#nullable enable
class C
{
static object obj = null!;
}" + InstrumentationHelperSource;
var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage));
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
emitOptions: emitOptions,
symbolValidator: validator);
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Empty(type.GetMembers(".cctor"));
}
}
private class SpanResult
{
public int StartLine { get; }
public int StartColumn { get; }
public int EndLine { get; }
public int EndColumn { get; }
public string TextStart { get; }
public SpanResult(int startLine, int startColumn, int endLine, int endColumn, string textStart)
{
StartLine = startLine;
StartColumn = startColumn;
EndLine = endLine;
EndColumn = endColumn;
TextStart = textStart;
}
}
private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, string[] sourceLines, params SpanResult[] expected)
{
ArrayBuilder<string> expectedSpanSpellings = ArrayBuilder<string>.GetInstance(expected.Length);
foreach (SpanResult expectedSpanResult in expected)
{
Assert.True(sourceLines[expectedSpanResult.StartLine].Substring(expectedSpanResult.StartColumn).StartsWith(expectedSpanResult.TextStart));
expectedSpanSpellings.Add(string.Format("({0},{1})-({2},{3})", expectedSpanResult.StartLine, expectedSpanResult.StartColumn, expectedSpanResult.EndLine, expectedSpanResult.EndColumn));
}
VerifySpans(reader, methodData, expectedSpanSpellings.ToArrayAndFree());
}
private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, params string[] expected)
{
AssertEx.Equal(expected, reader.GetSpans(methodData.Blob).Select(s => $"({s.StartLine},{s.StartColumn})-({s.EndLine},{s.EndColumn})"));
}
private void VerifyDocuments(DynamicAnalysisDataReader reader, ImmutableArray<DynamicAnalysisDocument> documents, params string[] expected)
{
var sha1 = new Guid("ff1816ec-aa5e-4d10-87f7-6f4963833460");
var actual = from d in documents
let name = reader.GetDocumentName(d.Name)
let hash = d.Hash.IsNil ? "" : " " + BitConverter.ToString(reader.GetBytes(d.Hash))
let hashAlgGuid = reader.GetGuid(d.HashAlgorithm)
let hashAlg = (hashAlgGuid == sha1) ? " (SHA1)" : (hashAlgGuid == default(Guid)) ? "" : " " + hashAlgGuid.ToString()
select $"'{name}'{hash}{hashAlg}";
AssertEx.Equal(expected, actual);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests
{
public class DynamicAnalysisResourceTests : CSharpTestBase
{
const string InstrumentationHelperSource = @"
namespace Microsoft.CodeAnalysis.Runtime
{
public static class Instrumentation
{
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int fileIndex, ref bool[] payload, int payloadLength)
{
return payload;
}
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int[] fileIndices, ref bool[] payload, int payloadLength)
{
return payload;
}
public static void FlushPayload()
{
}
}
}
";
const string ExampleSource = @"
using System;
public class C
{
public static void Main()
{
Console.WriteLine(123);
Console.WriteLine(123);
}
public static int Fred => 3;
public static int Barney(int x) => x;
public static int Wilma
{
get { return 12; }
set { }
}
public static int Betty { get; }
public static int Pebbles { get; set; }
}
";
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)]
public void TestSpansPresentInResource()
{
var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
VerifyDocuments(reader, reader.Documents,
@"'C:\myproject\doc1.cs' 44-3F-7C-A1-EF-CA-A8-16-40-D2-09-4F-3E-52-7C-44-8D-22-C8-02 (SHA1)");
Assert.Equal(13, reader.Methods.Length);
string[] sourceLines = ExampleSource.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines, // Main
new SpanResult(5, 4, 9, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 31, "Console.WriteLine(123)"),
new SpanResult(8, 8, 8, 31, "Console.WriteLine(123)"));
VerifySpans(reader, reader.Methods[1], sourceLines, // Fred get
new SpanResult(11, 4, 11, 32, "public static int Fred => 3"),
new SpanResult(11, 30, 11, 31, "3"));
VerifySpans(reader, reader.Methods[2], sourceLines, // Barney
new SpanResult(13, 4, 13, 41, "public static int Barney(int x) => x"),
new SpanResult(13, 39, 13, 40, "x"));
VerifySpans(reader, reader.Methods[3], sourceLines, // Wilma get
new SpanResult(17, 8, 17, 26, "get { return 12; }"),
new SpanResult(17, 14, 17, 24, "return 12"));
VerifySpans(reader, reader.Methods[4], sourceLines, // Wilma set
new SpanResult(18, 8, 18, 15, "set { }"));
VerifySpans(reader, reader.Methods[5], sourceLines, // Betty get
new SpanResult(21, 4, 21, 36, "public static int Betty { get; }"),
new SpanResult(21, 30, 21, 34, "get"));
VerifySpans(reader, reader.Methods[6], sourceLines, // Pebbles get
new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"),
new SpanResult(23, 32, 23, 36, "get"));
VerifySpans(reader, reader.Methods[7], sourceLines, // Pebbles set
new SpanResult(23, 4, 23, 43, "public static int Pebbles { get; set; }"),
new SpanResult(23, 37, 23, 41, "set"));
VerifySpans(reader, reader.Methods[8]);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)]
public void ResourceStatementKinds()
{
string source = @"
using System;
public class C
{
public static void Main()
{
int z = 11;
int x = z + 10;
switch (z)
{
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
if (x > 10)
{
x++;
}
else
{
x--;
}
for (int y = 0; y < 50; y++)
{
if (y < 30)
{
x++;
continue;
}
else
break;
}
int[] a = new int[] { 1, 2, 3, 4 };
foreach (int i in a)
{
x++;
}
while (x < 100)
{
x++;
}
try
{
x++;
if (x > 10)
{
throw new System.Exception();
}
x++;
}
catch (System.Exception e)
{
x++;
}
finally
{
x++;
}
lock (new object())
{
;
}
Console.WriteLine(x);
try
{
using ((System.IDisposable)new object())
{
;
}
}
catch (System.Exception e)
{
}
return;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
VerifyDocuments(reader, reader.Documents,
@"'C:\myproject\doc1.cs' 6A-DC-C0-8A-16-CB-7C-A5-99-8B-2E-0C-3C-81-69-2C-B2-10-EE-F1 (SHA1)");
Assert.Equal(6, reader.Methods.Length);
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 89, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "int z = 11"),
new SpanResult(8, 8, 8, 23, "int x = z + 10"),
new SpanResult(12, 16, 12, 22, "break"),
new SpanResult(14, 16, 14, 22, "break"),
new SpanResult(16, 16, 16, 22, "break"),
new SpanResult(18, 16, 18, 22, "break"),
new SpanResult(9, 16, 9, 17, "z"),
new SpanResult(23, 12, 23, 16, "x++"),
new SpanResult(27, 12, 27, 16, "x--"),
new SpanResult(21, 12, 21, 18, "x > 10"),
new SpanResult(30, 17, 30, 22, "y = 0"),
new SpanResult(30, 32, 30, 35, "y++"),
new SpanResult(34, 16, 34, 20, "x++"),
new SpanResult(35, 16, 35, 25, "continue"),
new SpanResult(38, 16, 38, 22, "break"),
new SpanResult(32, 16, 32, 22, "y < 30"),
new SpanResult(41, 8, 41, 43, "int[] a = new int[] { 1, 2, 3, 4 }"),
new SpanResult(44, 12, 44, 16, "x++"),
new SpanResult(42, 26, 42, 27, "a"),
new SpanResult(49, 12, 49, 16, "x++"),
new SpanResult(47, 15, 47, 22, "x < 100"),
new SpanResult(54, 12, 54, 16, "x++"),
new SpanResult(57, 16, 57, 45, "throw new System.Exception()"),
new SpanResult(55, 16, 55, 22, "x > 10"),
new SpanResult(59, 12, 59, 16, "x++"),
new SpanResult(63, 12, 63, 16, "x++"),
new SpanResult(67, 12, 67, 16, "x++"),
new SpanResult(72, 12, 72, 13, ";"),
new SpanResult(70, 14, 70, 26, "new object()"),
new SpanResult(75, 8, 75, 29, "Console.WriteLine(x)"),
new SpanResult(81, 16, 81, 17, ";"),
new SpanResult(79, 19, 79, 51, "(System.IDisposable)new object()"),
new SpanResult(88, 8, 88, 15, "return"));
VerifySpans(reader, reader.Methods[1]);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)]
public void TestMethodSpansWithAttributes()
{
string source = @"
using System;
using System.Security;
public class C
{
static int x;
public static void Main() // Method 0
{
Fred();
}
[Obsolete()]
static void Fred() // Method 1
{
}
static C() // Method 2
{
x = 12;
}
[Obsolete()]
public C() // Method 3
{
}
int Wilma
{
[SecurityCritical]
get { return 12; } // Method 4
}
[Obsolete()]
int Betty => 13; // Method 5
[SecurityCritical]
int Pebbles() // Method 6
{
return 3;
}
[SecurityCritical]
ref int BamBam(ref int x) // Method 7
{
return ref x;
}
[SecurityCritical]
C(int x) // Method 8
{
}
[Obsolete()]
public int Barney => 13; // Method 9
[SecurityCritical]
public static C operator +(C a, C b) // Method 10
{
return a;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
VerifyDocuments(reader, reader.Documents,
@"'C:\myproject\doc1.cs' A3-08-94-55-7C-64-8D-C7-61-7A-11-0B-4B-68-2C-3B-51-C3-C4-58 (SHA1)");
Assert.Equal(15, reader.Methods.Length);
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(8, 4, 11, 5, "public static void Main()"),
new SpanResult(10, 8, 10, 15, "Fred()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(14, 4, 16, 5, "static void Fred()"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(18, 4, 21, 5, "static C()"),
new SpanResult(20, 8, 20, 15, "x = 12"));
VerifySpans(reader, reader.Methods[3], sourceLines,
new SpanResult(24, 4, 26, 5, "public C()"));
VerifySpans(reader, reader.Methods[4], sourceLines,
new SpanResult(31, 8, 31, 26, "get {"),
new SpanResult(31, 14, 31, 24, "return 12"));
VerifySpans(reader, reader.Methods[5], sourceLines,
new SpanResult(35, 4, 35, 20, "int Betty"),
new SpanResult(35, 17, 35, 19, "13"));
VerifySpans(reader, reader.Methods[6], sourceLines,
new SpanResult(38, 4, 41, 5, "int Pebbles()"),
new SpanResult(40, 8, 40, 17, "return 3"));
VerifySpans(reader, reader.Methods[7], sourceLines,
new SpanResult(44, 4, 47, 5, "ref int BamBam"),
new SpanResult(46, 8, 46, 21, "return ref x"));
VerifySpans(reader, reader.Methods[8], sourceLines,
new SpanResult(50, 4, 52, 5, "C(int x)"));
VerifySpans(reader, reader.Methods[9], sourceLines,
new SpanResult(55, 4, 55, 28, "public int Barney"),
new SpanResult(55, 25, 55, 27, "13"));
VerifySpans(reader, reader.Methods[10], sourceLines,
new SpanResult(58, 4, 61, 5, "public static C operator +"),
new SpanResult(60, 8, 60, 17, "return a"));
}
[Fact]
public void TestPatternSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static string Operate(Person p) // Method 1
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s when (s.GPA < 2.0):
return $""Failing Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 11, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 34, "Student s = new Student()"),
new SpanResult(8, 8, 8, 24, "s.Name = \"Bozo\""),
new SpanResult(9, 8, 9, 20, "s.GPA = 2.3"),
new SpanResult(10, 8, 10, 19, "Operate(s)"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(13, 4, 28, 5, "static string Operate(Person p)"),
new SpanResult(17, 27, 17, 43, "when s.GPA > 3.5"),
new SpanResult(19, 27, 19, 45, "when (s.GPA < 2.0)"),
new SpanResult(18, 16, 18, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""),
new SpanResult(20, 16, 20, 64, "return $\"Failing Student {s.Name} ({s.GPA:N1})\""),
new SpanResult(22, 16, 22, 56, "return $\"Student {s.Name} ({s.GPA:N1})\""),
new SpanResult(24, 16, 24, 58, "return $\"Teacher {t.Name} of {t.Subject}\""),
new SpanResult(26, 16, 26, 42, "return $\"Person {p.Name}\""),
new SpanResult(15, 16, 15, 17, "p"));
}
[Fact]
public void TestPatternSpans_WithSharedWhenExpression()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
Method1(1, b1: false, b2: false);
}
static string Method1(int i, bool b1, bool b2) // Method 1
{
switch (i)
{
case not 1 when b1:
return ""b1"";
case var _ when b2:
return ""b2"";
case 1:
return ""1"";
default:
return ""default"";
}
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 23, 5, "static string Method1(int i, bool b1, bool b2)"),
new SpanResult(14, 23, 14, 30, "when b1:"),
new SpanResult(16, 23, 16, 30, "when b2:"),
new SpanResult(15, 16, 15, 28, @"return ""b1"";"),
new SpanResult(17, 16, 17, 28, @"return ""b2"";"),
new SpanResult(19, 16, 19, 27, @"return ""1"";"),
new SpanResult(21, 16, 21, 33, @"return ""default"";"),
new SpanResult(12, 16, 12, 17, "i"));
}
[Fact]
public void TestDeconstructionSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
var (x, y) = new C();
}
public void Deconstruct(out int x, out int y)
{
x = 1;
y = 2;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 29, "var (x, y) = new C()"));
}
[Fact]
public void TestForeachSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
C[] a = null;
foreach
(var x
in a)
;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 12, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 21, "C[] a = null"),
new SpanResult(11, 12, 11, 13, ";"),
new SpanResult(10, 15, 10, 16, "a")
);
}
[Fact]
public void TestForeachDeconstructionSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
C[] a = null;
foreach
(var (x, y)
in a)
;
}
public void Deconstruct(out int x, out int y)
{
x = 1;
y = 2;
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 12, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 21, "C[] a = null"),
new SpanResult(11, 12, 11, 13, ";"),
new SpanResult(10, 15, 10, 16, "a")
);
}
[Fact]
public void TestFieldInitializerSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
C local = new C(); local = new C(1, 2);
}
static int Init() => 33; // Method 2
C() // Method 3
{
_z = 12;
}
static C() // Method 4
{
s_z = 123;
}
int _x = Init();
int _y = Init() + 12;
int _z;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z;
C(int x) // Method 5
{
_z = x;
}
C(int a, int b) // Method 6
{
_z = a + b;
}
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 13, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 26, "C local = new C()"),
new SpanResult(12, 27, 12, 47, "local = new C(1, 2)"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(15, 4, 15, 28, "static int Init() => 33"),
new SpanResult(15, 25, 15, 27, "33"));
VerifySpans(reader, reader.Methods[3], sourceLines,
new SpanResult(17, 4, 20, 5, "C()"),
new SpanResult(27, 13, 27, 19, "Init()"),
new SpanResult(28, 13, 28, 24, "Init() + 12"),
new SpanResult(44, 25, 44, 27, "15"),
new SpanResult(19, 8, 19, 16, "_z = 12"));
VerifySpans(reader, reader.Methods[4], sourceLines,
new SpanResult(22, 4, 25, 5, "static C()"),
new SpanResult(30, 21, 30, 27, "Init()"),
new SpanResult(31, 21, 31, 33, "Init() + 153"),
new SpanResult(45, 32, 45, 35, "255"),
new SpanResult(24, 8, 24, 18, "s_z = 123"));
VerifySpans(reader, reader.Methods[5], sourceLines,
new SpanResult(34, 4, 37, 5, "C(int x)"),
new SpanResult(27, 13, 27, 19, "Init()"),
new SpanResult(28, 13, 28, 24, "Init() + 12"),
new SpanResult(44, 25, 44, 27, "15"),
new SpanResult(36, 8, 36, 15, "_z = x"));
VerifySpans(reader, reader.Methods[6], sourceLines,
new SpanResult(39, 4, 42, 5, "C(int a, int b)"),
new SpanResult(27, 13, 27, 19, "Init()"),
new SpanResult(28, 13, 28, 24, "Init() + 12"),
new SpanResult(44, 25, 44, 27, "15"),
new SpanResult(41, 8, 41, 19, "_z = a + b"));
}
[Fact]
public void TestImplicitConstructorSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
C local = new C();
}
static int Init() => 33; // Method 2
int _x = Init();
int _y = Init() + 12;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z = 144;
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 13, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 26, "C local = new C()"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(15, 4, 15, 28, "static int Init() => 33"),
new SpanResult(15, 25, 15, 27, "33"));
VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized instance constructor
new SpanResult(17, 13, 17, 19, "Init()"),
new SpanResult(18, 13, 18, 24, "Init() + 12"),
new SpanResult(23, 25, 23, 27, "15"));
VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor
new SpanResult(19, 21, 19, 27, "Init()"),
new SpanResult(20, 21, 20, 33, "Init() + 153"),
new SpanResult(21, 21, 21, 24, "144"),
new SpanResult(24, 32, 24, 35, "255"));
}
[Fact]
public void TestImplicitConstructorsWithLambdasSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
int y = s_c._function();
D d = new D();
int z = d._c._function();
int zz = D.s_c._function();
}
public C(Func<int> f) // Method 2
{
_function = f;
}
static C s_c = new C(() => 115);
Func<int> _function;
}
class D
{
public C _c = new C(() => 120);
public static C s_c = new C(() => 144);
public C _c1 = new C(() => 130);
public static C s_c1 = new C(() => 156);
}
partial struct E
{
}
partial struct E
{
public static C s_c = new C(() => 1444);
public static C s_c1 = new C(() => { return 1567; });
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 16, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 32, "int y = s_c._function()"),
new SpanResult(13, 8, 13, 22, "D d = new D()"),
new SpanResult(14, 8, 14, 33, "int z = d._c._function()"),
new SpanResult(15, 8, 15, 35, "int zz = D.s_c._function()"));
VerifySpans(reader, reader.Methods[2], sourceLines,
new SpanResult(18, 4, 21, 5, "public C(Func<int> f)"),
new SpanResult(20, 8, 20, 22, "_function = f"));
VerifySpans(reader, reader.Methods[3], sourceLines, // Synthesized static constructor for C
new SpanResult(23, 31, 23, 34, "115"),
new SpanResult(23, 19, 23, 35, "new C(() => 115)"));
VerifySpans(reader, reader.Methods[4], sourceLines, // Synthesized instance constructor for D
new SpanResult(29, 30, 29, 33, "120"),
new SpanResult(31, 31, 31, 34, "130"),
new SpanResult(29, 18, 29, 34, "new C(() => 120)"),
new SpanResult(31, 19, 31, 35, "new C(() => 130)"));
VerifySpans(reader, reader.Methods[5], sourceLines, // Synthesized static constructor for D
new SpanResult(30, 38, 30, 41, "144"),
new SpanResult(32, 39, 32, 42, "156"),
new SpanResult(30, 26, 30, 42, "new C(() => 144)"),
new SpanResult(32, 27, 32, 43, "new C(() => 156"));
VerifySpans(reader, reader.Methods[6], sourceLines, // Synthesized static constructor for E
new SpanResult(41, 38, 41, 42, "1444"),
new SpanResult(42, 41, 42, 53, "return 1567"),
new SpanResult(41, 26, 41, 43, "new C(() => 1444)"),
new SpanResult(42, 27, 42, 56, "new C(() => { return 1567; })"));
}
[Fact]
public void TestLocalFunctionWithLambdaSpans()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 0
{
TestMain();
}
static void TestMain() // Method 1
{
new D().M1();
}
}
public class D
{
public void M1() // Method 3
{
L1();
void L1()
{
var f = new Func<int>(
() => 1
);
f();
var f1 = new Func<int>(
() => { return 2; }
);
var f2 = new Func<int, int>(
(x) => x + 3
);
var f3 = new Func<int, int>(
x => x + 4
);
}
}
}
";
var c = CreateCompilation(Parse(source + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
string[] sourceLines = source.Split('\n');
VerifySpans(reader, reader.Methods[0], sourceLines,
new SpanResult(5, 4, 8, 5, "public static void Main()"),
new SpanResult(7, 8, 7, 19, "TestMain()"));
VerifySpans(reader, reader.Methods[1], sourceLines,
new SpanResult(10, 4, 13, 5, "static void TestMain()"),
new SpanResult(12, 8, 12, 21, "new D().M1()"));
VerifySpans(reader, reader.Methods[3], sourceLines,
new SpanResult(18, 4, 41, 5, "public void M1()"),
new SpanResult(20, 8, 20, 13, "L1()"),
new SpanResult(24, 22, 24, 23, "1"),
new SpanResult(23, 12, 25, 14, "var f = new Func<int>"),
new SpanResult(27, 12, 27, 16, "f()"),
new SpanResult(30, 24, 30, 33, "return 2"),
new SpanResult(29, 12, 31, 14, "var f1 = new Func<int>"),
new SpanResult(34, 23, 34, 28, "x + 3"),
new SpanResult(33, 12, 35, 14, "var f2 = new Func<int, int>"),
new SpanResult(38, 21, 38, 26, "x + 4"),
new SpanResult(37, 12, 39, 14, "var f3 = new Func<int, int>"));
}
[Fact]
public void TestDynamicAnalysisResourceMissingWhenInstrumentationFlagIsDisabled()
{
var c = CreateCompilation(Parse(ExampleSource + InstrumentationHelperSource, @"C:\myproject\doc1.cs"));
var peImage = c.EmitToArray(EmitOptions.Default);
var peReader = new PEReader(peImage);
var reader = DynamicAnalysisDataReader.TryCreateFromPE(peReader, "<DynamicAnalysisData>");
Assert.Null(reader);
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void EmptyStaticConstructor_WithEnableTestCoverage()
{
string source = @"
#nullable enable
class C
{
static C()
{
}
static object obj = null!;
}" + InstrumentationHelperSource;
var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage));
CompileAndVerify(source, emitOptions: emitOptions).VerifyIL("C..cctor()",
@"{
// Code size 57 (0x39)
.maxstack 5
.locals init (bool[] V_0)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""C..cctor()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""C..cctor()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""C..cctor()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.1
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ret
}");
}
[WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")]
[Fact]
public void SynthesizedStaticConstructor_WithEnableTestCoverage()
{
string source = @"
#nullable enable
class C
{
static object obj = null!;
}" + InstrumentationHelperSource;
var emitOptions = EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage));
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
emitOptions: emitOptions,
symbolValidator: validator);
void validator(ModuleSymbol module)
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
Assert.Empty(type.GetMembers(".cctor"));
}
}
private class SpanResult
{
public int StartLine { get; }
public int StartColumn { get; }
public int EndLine { get; }
public int EndColumn { get; }
public string TextStart { get; }
public SpanResult(int startLine, int startColumn, int endLine, int endColumn, string textStart)
{
StartLine = startLine;
StartColumn = startColumn;
EndLine = endLine;
EndColumn = endColumn;
TextStart = textStart;
}
}
private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, string[] sourceLines, params SpanResult[] expected)
{
ArrayBuilder<string> expectedSpanSpellings = ArrayBuilder<string>.GetInstance(expected.Length);
foreach (SpanResult expectedSpanResult in expected)
{
var text = sourceLines[expectedSpanResult.StartLine].Substring(expectedSpanResult.StartColumn);
Assert.True(text.StartsWith(expectedSpanResult.TextStart), $"Text doesn't start with {expectedSpanResult.TextStart}. Text is: {text}");
expectedSpanSpellings.Add(string.Format("({0},{1})-({2},{3})", expectedSpanResult.StartLine, expectedSpanResult.StartColumn, expectedSpanResult.EndLine, expectedSpanResult.EndColumn));
}
VerifySpans(reader, methodData, expectedSpanSpellings.ToArrayAndFree());
}
private static void VerifySpans(DynamicAnalysisDataReader reader, DynamicAnalysisMethod methodData, params string[] expected)
{
AssertEx.Equal(expected, reader.GetSpans(methodData.Blob).Select(s => $"({s.StartLine},{s.StartColumn})-({s.EndLine},{s.EndColumn})"));
}
private void VerifyDocuments(DynamicAnalysisDataReader reader, ImmutableArray<DynamicAnalysisDocument> documents, params string[] expected)
{
var sha1 = new Guid("ff1816ec-aa5e-4d10-87f7-6f4963833460");
var actual = from d in documents
let name = reader.GetDocumentName(d.Name)
let hash = d.Hash.IsNil ? "" : " " + BitConverter.ToString(reader.GetBytes(d.Hash))
let hashAlgGuid = reader.GetGuid(d.HashAlgorithm)
let hashAlg = (hashAlgGuid == sha1) ? " (SHA1)" : (hashAlgGuid == default(Guid)) ? "" : " " + hashAlgGuid.ToString()
select $"'{name}'{hash}{hashAlg}";
AssertEx.Equal(expected, actual);
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Roslyn.Test.Utilities;
using static Microsoft.CodeAnalysis.Test.Utilities.CSharpInstrumentationChecker;
namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests
{
public class DynamicInstrumentationTests : CSharpTestBase
{
[Fact]
public void HelpersInstrumentation()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
Method 4
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
string expectedCreatePayloadForMethodsSpanningSingleFileIL = @"{
// Code size 21 (0x15)
.maxstack 6
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldc.i4.1
IL_0003: newarr ""int""
IL_0008: dup
IL_0009: ldc.i4.0
IL_000a: ldarg.2
IL_000b: stelem.i4
IL_000c: ldarg.3
IL_000d: ldarg.s V_4
IL_000f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)""
IL_0014: ret
}";
string expectedCreatePayloadForMethodsSpanningMultipleFilesIL = @"{
// Code size 87 (0x57)
.maxstack 3
IL_0000: ldsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid""
IL_0005: ldarg.0
IL_0006: call ""bool System.Guid.op_Inequality(System.Guid, System.Guid)""
IL_000b: brfalse.s IL_002b
IL_000d: ldc.i4.s 100
IL_000f: newarr ""bool[]""
IL_0014: stsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0019: ldc.i4.s 100
IL_001b: newarr ""int[]""
IL_0020: stsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_0025: ldarg.0
IL_0026: stsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid""
IL_002b: ldarg.3
IL_002c: ldarg.s V_4
IL_002e: newarr ""bool""
IL_0033: ldnull
IL_0034: call ""bool[] System.Threading.Interlocked.CompareExchange<bool[]>(ref bool[], bool[], bool[])""
IL_0039: brtrue.s IL_004f
IL_003b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0040: ldarg.1
IL_0041: ldarg.3
IL_0042: ldind.ref
IL_0043: stelem.ref
IL_0044: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_0049: ldarg.1
IL_004a: ldarg.2
IL_004b: stelem.ref
IL_004c: ldarg.3
IL_004d: ldind.ref
IL_004e: ret
IL_004f: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0054: ldarg.1
IL_0055: ldelem.ref
IL_0056: ret
}";
string expectedFlushPayloadIL = @"{
// Code size 288 (0x120)
.maxstack 5
.locals init (bool[] V_0,
int V_1, //i
bool[] V_2, //payload
int V_3, //j
int V_4) //j
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0035
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.s 16
IL_002f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0034: stloc.0
IL_0035: ldloc.0
IL_0036: ldc.i4.0
IL_0037: ldc.i4.1
IL_0038: stelem.i1
IL_0039: ldloc.0
IL_003a: ldc.i4.1
IL_003b: ldc.i4.1
IL_003c: stelem.i1
IL_003d: ldstr ""Flushing""
IL_0042: call ""void System.Console.WriteLine(string)""
IL_0047: ldloc.0
IL_0048: ldc.i4.3
IL_0049: ldc.i4.1
IL_004a: stelem.i1
IL_004b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0050: brtrue.s IL_0057
IL_0052: ldloc.0
IL_0053: ldc.i4.2
IL_0054: ldc.i4.1
IL_0055: stelem.i1
IL_0056: ret
IL_0057: ldloc.0
IL_0058: ldc.i4.4
IL_0059: ldc.i4.1
IL_005a: stelem.i1
IL_005b: ldc.i4.0
IL_005c: stloc.1
IL_005d: br IL_0112
IL_0062: ldloc.0
IL_0063: ldc.i4.6
IL_0064: ldc.i4.1
IL_0065: stelem.i1
IL_0066: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_006b: ldloc.1
IL_006c: ldelem.ref
IL_006d: stloc.2
IL_006e: ldloc.0
IL_006f: ldc.i4.s 15
IL_0071: ldc.i4.1
IL_0072: stelem.i1
IL_0073: ldloc.2
IL_0074: brfalse IL_010a
IL_0079: ldloc.0
IL_007a: ldc.i4.7
IL_007b: ldc.i4.1
IL_007c: stelem.i1
IL_007d: ldstr ""Method ""
IL_0082: ldloca.s V_1
IL_0084: call ""string int.ToString()""
IL_0089: call ""string string.Concat(string, string)""
IL_008e: call ""void System.Console.WriteLine(string)""
IL_0093: ldloc.0
IL_0094: ldc.i4.8
IL_0095: ldc.i4.1
IL_0096: stelem.i1
IL_0097: ldc.i4.0
IL_0098: stloc.3
IL_0099: br.s IL_00ca
IL_009b: ldloc.0
IL_009c: ldc.i4.s 10
IL_009e: ldc.i4.1
IL_009f: stelem.i1
IL_00a0: ldstr ""File ""
IL_00a5: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_00aa: ldloc.1
IL_00ab: ldelem.ref
IL_00ac: ldloc.3
IL_00ad: ldelema ""int""
IL_00b2: call ""string int.ToString()""
IL_00b7: call ""string string.Concat(string, string)""
IL_00bc: call ""void System.Console.WriteLine(string)""
IL_00c1: ldloc.0
IL_00c2: ldc.i4.s 9
IL_00c4: ldc.i4.1
IL_00c5: stelem.i1
IL_00c6: ldloc.3
IL_00c7: ldc.i4.1
IL_00c8: add
IL_00c9: stloc.3
IL_00ca: ldloc.3
IL_00cb: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_00d0: ldloc.1
IL_00d1: ldelem.ref
IL_00d2: ldlen
IL_00d3: conv.i4
IL_00d4: blt.s IL_009b
IL_00d6: ldloc.0
IL_00d7: ldc.i4.s 11
IL_00d9: ldc.i4.1
IL_00da: stelem.i1
IL_00db: ldc.i4.0
IL_00dc: stloc.s V_4
IL_00de: br.s IL_0103
IL_00e0: ldloc.0
IL_00e1: ldc.i4.s 13
IL_00e3: ldc.i4.1
IL_00e4: stelem.i1
IL_00e5: ldloc.2
IL_00e6: ldloc.s V_4
IL_00e8: ldelem.u1
IL_00e9: call ""void System.Console.WriteLine(bool)""
IL_00ee: ldloc.0
IL_00ef: ldc.i4.s 14
IL_00f1: ldc.i4.1
IL_00f2: stelem.i1
IL_00f3: ldloc.2
IL_00f4: ldloc.s V_4
IL_00f6: ldc.i4.0
IL_00f7: stelem.i1
IL_00f8: ldloc.0
IL_00f9: ldc.i4.s 12
IL_00fb: ldc.i4.1
IL_00fc: stelem.i1
IL_00fd: ldloc.s V_4
IL_00ff: ldc.i4.1
IL_0100: add
IL_0101: stloc.s V_4
IL_0103: ldloc.s V_4
IL_0105: ldloc.2
IL_0106: ldlen
IL_0107: conv.i4
IL_0108: blt.s IL_00e0
IL_010a: ldloc.0
IL_010b: ldc.i4.5
IL_010c: ldc.i4.1
IL_010d: stelem.i1
IL_010e: ldloc.1
IL_010f: ldc.i4.1
IL_0110: add
IL_0111: stloc.1
IL_0112: ldloc.1
IL_0113: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0118: ldlen
IL_0119: conv.i4
IL_011a: blt IL_0062
IL_011f: ret
}";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)", expectedCreatePayloadForMethodsSpanningSingleFileIL);
verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)", expectedCreatePayloadForMethodsSpanningMultipleFilesIL);
verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload", expectedFlushPayloadIL);
verifier.VerifyDiagnostics();
}
[Fact]
public void GotoCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain()
{
Console.WriteLine(""goo"");
goto bar;
Console.Write(""you won't see me"");
bar: Console.WriteLine(""bar"");
Fred();
return;
}
static void Wilma()
{
Betty(true);
Barney(true);
Barney(false);
Betty(true);
}
static int Barney(bool b)
{
if (b)
return 10;
if (b)
return 100;
return 20;
}
static int Betty(bool b)
{
if (b)
return 30;
if (b)
return 100;
return 40;
}
static void Fred()
{
Wilma();
}
}
";
string expectedOutput = @"goo
bar
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
False
True
True
True
Method 3
File 1
True
True
True
True
True
Method 4
File 1
True
True
True
False
True
True
Method 5
File 1
True
True
True
False
False
False
Method 6
File 1
True
True
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
string expectedBarneyIL = @"{
// Code size 91 (0x5b)
.maxstack 5
.locals init (bool[] V_0)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""int Program.Barney(bool)""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""int Program.Barney(bool)""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""int Program.Barney(bool)""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.6
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: brfalse.s IL_0046
IL_003f: ldloc.0
IL_0040: ldc.i4.1
IL_0041: ldc.i4.1
IL_0042: stelem.i1
IL_0043: ldc.i4.s 10
IL_0045: ret
IL_0046: ldloc.0
IL_0047: ldc.i4.4
IL_0048: ldc.i4.1
IL_0049: stelem.i1
IL_004a: ldarg.0
IL_004b: brfalse.s IL_0054
IL_004d: ldloc.0
IL_004e: ldc.i4.3
IL_004f: ldc.i4.1
IL_0050: stelem.i1
IL_0051: ldc.i4.s 100
IL_0053: ret
IL_0054: ldloc.0
IL_0055: ldc.i4.5
IL_0056: ldc.i4.1
IL_0057: stelem.i1
IL_0058: ldc.i4.s 20
IL_005a: ret
}";
string expectedPIDStaticConstructorIL = @"{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldtoken Max Method Token Index
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: newarr ""bool[]""
IL_000c: stsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0011: ldstr ##MVID##
IL_0016: newobj ""System.Guid..ctor(string)""
IL_001b: stsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0020: ret
}";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Barney", expectedBarneyIL);
verifier.VerifyIL(".cctor", expectedPIDStaticConstructorIL);
verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(16, 9));
}
[Fact]
public void MethodsOfGenericTypesCoverage()
{
string source = @"
using System;
class MyBox<T> where T : class
{
readonly T _value;
public MyBox(T value)
{
_value = value;
}
public T GetValue()
{
if (_value == null)
{
return null;
}
return _value;
}
}
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain()
{
MyBox<object> x = new MyBox<object>(null);
Console.WriteLine(x.GetValue() == null ? ""null"" : x.GetValue().ToString());
MyBox<string> s = new MyBox<string>(""Hello"");
Console.WriteLine(s.GetValue() == null ? ""null"" : s.GetValue());
}
}
";
// All instrumentation points in method 2 are True because they are covered by at least one specialization.
//
// This test verifies that the payloads of methods of generic types are in terms of method definitions and
// not method references -- the indices for the methods would be different for references.
string expectedOutput = @"null
Hello
Flushing
Method 1
File 1
True
True
Method 2
File 1
True
True
True
True
Method 3
File 1
True
True
True
Method 4
File 1
True
True
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
string expectedReleaseGetValueIL = @"{
// Code size 98 (0x62)
.maxstack 5
.locals init (bool[] V_0,
T V_1)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""T MyBox<T>.GetValue()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""T MyBox<T>.GetValue()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""T MyBox<T>.GetValue()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.4
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: ldfld ""T MyBox<T>._value""
IL_0042: box ""T""
IL_0047: brtrue.s IL_0057
IL_0049: ldloc.0
IL_004a: ldc.i4.1
IL_004b: ldc.i4.1
IL_004c: stelem.i1
IL_004d: ldloca.s V_1
IL_004f: initobj ""T""
IL_0055: ldloc.1
IL_0056: ret
IL_0057: ldloc.0
IL_0058: ldc.i4.3
IL_0059: ldc.i4.1
IL_005a: stelem.i1
IL_005b: ldarg.0
IL_005c: ldfld ""T MyBox<T>._value""
IL_0061: ret
}";
string expectedDebugGetValueIL = @"{
// Code size 110 (0x6e)
.maxstack 5
.locals init (bool[] V_0,
bool V_1,
T V_2,
T V_3)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""T MyBox<T>.GetValue()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""T MyBox<T>.GetValue()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""T MyBox<T>.GetValue()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.4
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: ldfld ""T MyBox<T>._value""
IL_0042: box ""T""
IL_0047: ldnull
IL_0048: ceq
IL_004a: stloc.1
IL_004b: ldloc.1
IL_004c: brfalse.s IL_005f
IL_004e: nop
IL_004f: ldloc.0
IL_0050: ldc.i4.1
IL_0051: ldc.i4.1
IL_0052: stelem.i1
IL_0053: ldloca.s V_2
IL_0055: initobj ""T""
IL_005b: ldloc.2
IL_005c: stloc.3
IL_005d: br.s IL_006c
IL_005f: ldloc.0
IL_0060: ldc.i4.3
IL_0061: ldc.i4.1
IL_0062: stelem.i1
IL_0063: ldarg.0
IL_0064: ldfld ""T MyBox<T>._value""
IL_0069: stloc.3
IL_006a: br.s IL_006c
IL_006c: ldloc.3
IL_006d: ret
}";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyIL("MyBox<T>.GetValue", expectedReleaseGetValueIL);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyIL("MyBox<T>.GetValue", expectedDebugGetValueIL);
verifier.VerifyDiagnostics();
}
[Fact]
public void NonStaticImplicitBlockMethodsCoverage()
{
string source = @"
using System;
public class Program
{
public int Prop { get; }
public int Prop2 { get; } = 25;
public int Prop3 { get; set; } // Methods 3 and 4
public Program() // Method 5
{
Prop = 12;
Prop3 = 12;
Prop2 = Prop3;
}
public static void Main(string[] args) // Method 6
{
new Program();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(3, 1, "public int Prop3")
.True("get");
checker.Method(4, 1, "public int Prop3")
.True("set");
checker.Method(5, 1, "public Program()")
.True("25")
.True("Prop = 12;")
.True("Prop3 = 12;")
.True("Prop2 = Prop3;");
checker.Method(6, 1, "public static void Main")
.True("new Program();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(8, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
}
[Fact]
public void ImplicitBlockMethodsCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
int x = Count;
x += Prop;
Prop = x;
x += Prop2;
Lambda(x, (y) => y + 1);
}
static int Function(int x) => x;
static int Count => Function(44);
static int Prop { get; set; }
static int Prop2 { get; set; } = 12;
static int Lambda(int x, Func<int, int> l)
{
return l(x);
}
// Method 11 is a synthesized static constructor.
}
";
// There is no entry for method '8' since it's a Prop2_set which is never called.
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
Method 5
File 1
True
True
Method 6
File 1
True
True
Method 7
File 1
True
True
Method 9
File 1
True
True
Method 11
File 1
True
Method 13
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void LocalFunctionWithLambdaCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
new D().M1();
}
}
public class D
{
public void M1() // Method 4
{
L1();
void L1()
{
var f = new Func<int>(
() => 1
);
var f1 = new Func<int>(
() => 2
);
var f2 = new Func<int, int>(
(x) => x + 3
);
var f3 = new Func<int, int>(
x => x + 4
);
f();
f3(2);
}
}
// Method 5 is the synthesized instance constructor for D.
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, "public static void Main")
.True("TestMain();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(2, 1, "static void TestMain")
.True("new D().M1();");
checker.Method(4, 1, "public void M1()")
.True("L1();")
.True("1")
.True("var f = new Func<int>")
.False("2")
.True("var f1 = new Func<int>")
.False("x + 3")
.True("var f2 = new Func<int, int>")
.True("x + 4")
.True("var f3 = new Func<int, int>")
.True("f();")
.True("f3(2);");
checker.Method(5, 1, snippet: null, expectBodySpan: false);
checker.Method(7, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
}
[Fact]
public void MultipleFilesCoverage()
{
string source = @"
using System;
public class Program
{
#line 10 ""File1.cs""
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
#line 20 ""File2.cs""
static void TestMain() // Method 2
{
Fred();
Program p = new Program();
return;
}
#line 30 ""File3.cs""
static void Fred() // Method 3
{
return;
}
#line 40 ""File5.cs""
// The synthesized instance constructor is method 4 and
// appears in the original source file, which gets file index 4.
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 2
True
True
True
True
Method 3
File 3
True
True
Method 4
File 4
Method 6
File 5
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void MultipleDeclarationsCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
int x;
int a, b;
DoubleDeclaration(5);
DoubleForDeclaration(5);
}
static int DoubleDeclaration(int x) // Method 3
{
int c = x;
int a, b;
int f;
a = b = f = c;
int d = a, e = b;
return d + e + f;
}
static int DoubleForDeclaration(int x) // Method 4
{
for(int a = x, b = x; a + b < 10; a++)
{
Console.WriteLine(""Cannot get here."");
x++;
}
return x;
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
True
True
True
True
Method 4
File 1
True
True
True
False
False
False
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(14, 13),
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(15, 13),
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(15, 16));
}
[Fact]
public void UsingAndFixedCoverage()
{
string source = @"
using System;
using System.IO;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
using (var memoryStream = new MemoryStream())
{
;
}
using (MemoryStream s1 = new MemoryStream(), s2 = new MemoryStream())
{
;
}
var otherStream = new MemoryStream();
using (otherStream)
{
;
}
unsafe
{
double[] a = { 1, 2, 3 };
fixed(double* p = a)
{
;
}
fixed(double* q = a, r = a)
{
;
}
}
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails);
verifier.VerifyDiagnostics();
}
[Fact]
public void ManyStatementsCoverage() // Method 3
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain()
{
VariousStatements(2);
Empty();
}
static void VariousStatements(int z)
{
int x = z + 10;
switch (z)
{
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
if (x > 10)
{
x++;
}
else
{
x--;
}
for (int y = 0; y < 50; y++)
{
if (y < 30)
{
x++;
continue;
}
else
break;
}
int[] a = new int[] { 1, 2, 3, 4 };
foreach (int i in a)
{
x++;
}
while (x < 100)
{
x++;
}
try
{
x++;
if (x > 10)
{
throw new System.Exception();
}
x++;
}
catch (System.Exception)
{
x++;
}
finally
{
x++;
}
lock (new object())
{
;
}
Console.WriteLine(x);
try
{
using ((System.IDisposable)new object())
{
;
}
}
catch (System.Exception)
{
}
// Include an infinite loop to make sure that a compiler optimization doesn't eliminate the instrumentation.
while (true)
{
return;
}
}
static void Empty() // Method 4
{
}
}
";
string expectedOutput = @"103
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
False
True
False
False
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
False
True
True
True
True
True
False
True
True
True
Method 4
File 1
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void PatternsCoverage()
{
string source = @"
using System;
public class C
{
public static void Main()
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = s.Name switch { _ => 2.3 }; // switch expression is not instrumented
Operate(s);
}
static string Operate(Person p) // Method 3
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
// Methods 5 and 7 are implicit constructors.
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
Method 3
File 1
True
True
False
True
False
False
True
Method 5
File 1
Method 7
File 1
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Subject").WithArguments("Teacher.Subject", "null").WithLocation(37, 40));
}
[Fact]
public void DeconstructionStatementCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain2();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain2() // Method 2
{
var (x, y) = new C();
}
static void TestMain3() // Method 3
{
var (x, y) = new C();
}
public C() // Method 4
{
}
public void Deconstruct(out int x, out int y) // Method 5
{
x = 1;
y = 1 switch { 1 => 2, 3 => 4, _ => 5 }; // switch expression is not instrumented
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 4
File 1
True
Method 5
File 1
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
}
[Fact]
public void DeconstructionForeachStatementCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain2(new C[] { new C() });
TestMain3(new C[] { });
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain2(C[] a) // Method 2
{
foreach (
var (x, y)
in a)
;
}
static void TestMain3(C[] a) // Method 3
{
foreach (
var (x, y)
in a)
;
}
public C() // Method 4
{
}
public void Deconstruct(out int x, out int y) // Method 5
{
x = 1;
y = 2;
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
False
False
Method 4
File 1
True
Method 5
File 1
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
}
[Fact]
public void LambdaCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); // Method 2
}
static void TestMain()
{
int y = 5;
Func<int, int> tester = (x) =>
{
while (x > 10)
{
return y;
}
return x;
};
y = 75;
if (tester(20) > 50)
Console.WriteLine(""OK"");
else
Console.WriteLine(""Bad"");
}
}
";
string expectedOutput = @"OK
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
False
True
True
True
False
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void AsyncCoverage()
{
string source = @"
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
Console.WriteLine(Outer(""Goo"").Result);
}
async static Task<string> Outer(string s) // Method 3
{
string s1 = await First(s);
string s2 = await Second(s);
return s1 + s2;
}
async static Task<string> First(string s) // Method 4
{
string result = await Second(s) + ""Glue"";
if (result.Length > 2)
return result;
else
return ""Too short"";
}
async static Task<string> Second(string s) // Method 5
{
string doubled = """";
if (s.Length > 2)
doubled = s + s;
else
doubled = ""HuhHuh"";
return await Task.Factory.StartNew(() => doubled);
}
}
";
string expectedOutput = @"GooGooGlueGooGoo
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 3
File 1
True
True
True
True
Method 4
File 1
True
True
True
False
True
Method 5
File 1
True
True
True
False
True
True
True
Method 8
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void IteratorCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
foreach (var i in Goo())
{
Console.WriteLine(i);
}
foreach (var i in Goo())
{
Console.WriteLine(i);
}
}
public static System.Collections.Generic.IEnumerable<int> Goo()
{
for (int i = 0; i < 5; ++i)
{
yield return i;
}
}
}
";
string expectedOutput = @"0
1
2
3
4
0
1
2
3
4
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
Method 3
File 1
True
True
True
True
Method 6
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestFieldInitializerCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
C local = new C(); local = new C(1, s_z);
}
static int Init() => 33; // Method 3
C() // Method 4
{
_z = 12;
}
static C() // Method 5
{
s_z = 123;
}
int _x = Init();
int _y = Init() + 12;
int _z;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z;
C(int x) // Method 6
{
_z = x;
}
C(int a, int b) // Method 7
{
_z = a + b;
}
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
string expectedOutput = @"
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
True
True
True
Method 5
File 1
True
True
True
True
True
Method 7
File 1
True
True
True
True
True
Method 11
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestImplicitConstructorCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
C local = new C();
int x = local._x + local._y + C.s_x + C.s_y + C.s_z;
}
static int Init() => 33; // Method 3
// Method 6 is the implicit instance constructor.
// Method 7 is the implicit shared constructor.
int _x = Init();
int _y = Init() + 12;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z = 144;
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
string expectedOutput = @"
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
Method 6
File 1
True
True
True
Method 7
File 1
True
True
True
True
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestImplicitConstructorsWithLambdasCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
int y = s_c._function();
D d = new D();
int z = d._c._function();
int zz = D.s_c._function();
int zzz = d._c1._function();
}
public C(Func<int> f) // Method 3
{
_function = f;
}
static C s_c = new C(() => 115);
Func<int> _function;
}
partial class D
{
}
partial class D
{
}
partial class D
{
public C _c = new C(() => 120);
public static C s_c = new C(() => 144);
public C _c1 = new C(() => 130);
public static C s_c1 = new C(() => 156);
}
partial class D
{
}
partial struct E
{
}
partial struct E
{
public static C s_c = new C(() => 1444);
public static C s_c1 = new C(() => { return 1567; });
}
// Method 4 is the synthesized static constructor for C.
// Method 5 is the synthesized instance constructor for D.
// Method 6 is the synthesized static constructor for D.
";
string expectedOutput = @"
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
Method 5
File 1
True
True
True
True
Method 6
File 1
True
False
True
True
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void MissingMethodNeededForAnalysis()
{
string source = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class Exception { }
public class ValueType { }
public class Enum { }
public struct Void { }
public class Guid { }
}
public class Console
{
public static void WriteLine(string s) { }
public static void WriteLine(int i) { }
public static void WriteLine(bool b) { }
}
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static int TestMain()
{
return 3;
}
}
";
ImmutableArray<Diagnostic> diagnostics = CreateEmptyCompilation(source + InstrumentationHelperSource).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
foreach (Diagnostic diagnostic in diagnostics)
{
if (diagnostic.Code == (int)ErrorCode.ERR_MissingPredefinedMember &&
diagnostic.Arguments[0].Equals("System.Guid") && diagnostic.Arguments[1].Equals(".ctor"))
{
return;
}
}
Assert.True(false);
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Method()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
void M1() { Console.WriteLine(1); }
void M2() { Console.WriteLine(1); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.M1");
AssertInstrumented(verifier, "C.M2");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Ctor()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
int a = 1;
[ExcludeFromCodeCoverage]
public C() { Console.WriteLine(3); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..ctor");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Cctor()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static int a = 1;
[ExcludeFromCodeCoverage]
static C() { Console.WriteLine(3); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..cctor");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InMethod()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
static void M1() { L1(); void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); } }
static void M2() { L2(); void L2() { new Action(() => { Console.WriteLine(2); }).Invoke(); } }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.M1");
AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0");
AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1");
AssertInstrumented(verifier, "C.M2");
AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>g__L2|0"); // M2:L2
AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>b__1"); // M2:L2 lambda
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static void M1()
{
L1();
[ExcludeFromCodeCoverage]
void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); }
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource,
options: TestOptions.ReleaseDll,
parseOptions: TestOptions.Regular9);
AssertInstrumented(verifier, "C.M1");
AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0()");
AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1()");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Multiple()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static void M1()
{
#pragma warning disable 8321 // Unreferenced local function
void L1() { Console.WriteLine(1); }
[ExcludeFromCodeCoverage]
void L2() { Console.WriteLine(2); }
void L3() { Console.WriteLine(3); }
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource,
options: TestOptions.ReleaseDll,
parseOptions: TestOptions.Regular9);
AssertInstrumented(verifier, "C.M1");
AssertInstrumented(verifier, "C.<M1>g__L1|0_0(ref C.<>c__DisplayClass0_0)");
AssertNotInstrumented(verifier, "C.<M1>g__L2|0_1()");
AssertInstrumented(verifier, "C.<M1>g__L3|0_2(ref C.<>c__DisplayClass0_0)");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Nested()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static void M1()
{
L1();
void L1()
{
new Action(() =>
{
L2();
[ExcludeFromCodeCoverage]
void L2()
{
new Action(() =>
{
L3();
void L3()
{
Console.WriteLine(1);
}
}).Invoke();
}
}).Invoke();
}
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource,
options: TestOptions.ReleaseDll,
parseOptions: TestOptions.Regular9);
AssertInstrumented(verifier, "C.M1");
AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>g__L1|0()");
AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>b__1()");
AssertNotInstrumented(verifier, "C.<M1>g__L2|0_2()");
AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_3");
AssertNotInstrumented(verifier, "C.<M1>g__L3|0_4()");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InInitializers()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
Action IF = new Action(() => { Console.WriteLine(1); });
Action IP { get; } = new Action(() => { Console.WriteLine(2); });
static Action SF = new Action(() => { Console.WriteLine(3); });
static Action SP { get; } = new Action(() => { Console.WriteLine(4); });
[ExcludeFromCodeCoverage]
C() {}
static C() {}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..ctor");
AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_0");
AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_1");
AssertInstrumented(verifier, "C..cctor");
AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__0");
AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__1");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InAccessors()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
int P1
{
get { L1(); void L1() { Console.WriteLine(1); } return 1; }
set { L2(); void L2() { Console.WriteLine(2); } }
}
int P2
{
get { L3(); void L3() { Console.WriteLine(3); } return 3; }
set { L4(); void L4() { Console.WriteLine(4); } }
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.P1.get");
AssertNotInstrumented(verifier, "C.P1.set");
AssertNotInstrumented(verifier, "C.<get_P1>g__L1|1_0");
AssertNotInstrumented(verifier, "C.<set_P1>g__L2|2_0");
AssertInstrumented(verifier, "C.P2.get");
AssertInstrumented(verifier, "C.P2.set");
AssertInstrumented(verifier, "C.<get_P2>g__L3|4_0");
AssertInstrumented(verifier, "C.<set_P2>g__L4|5_0");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LambdaAttributes()
{
string source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void M1()
{
Action a1 = static () =>
{
Func<bool, int> f1 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; };
Func<bool, int> f2 = static (bool b) => { if (b) return 0; return 1; };
};
}
static void M2()
{
Action a2 = [ExcludeFromCodeCoverage] static () =>
{
Func<bool, int> f3 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; };
Func<bool, int> f4 = static (bool b) => { if (b) return 0; return 1; };
};
}
}";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview);
AssertInstrumented(verifier, "Program.M1");
AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__0()");
AssertNotInstrumented(verifier, "Program.<>c.<M1>b__0_1(bool)");
AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__2(bool)");
AssertInstrumented(verifier, "Program.M2");
AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_0()");
AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_1(bool)");
AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_2(bool)");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Type()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
class C
{
int x = 1;
static C() { }
void M1() { Console.WriteLine(1); }
int P { get => 1; set { } }
event Action E { add { } remove { } }
}
class D
{
int x = 1;
static D() { }
void M1() { Console.WriteLine(1); }
int P { get => 1; set { } }
event Action E { add { } remove { } }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..ctor");
AssertNotInstrumented(verifier, "C..cctor");
AssertNotInstrumented(verifier, "C.M1");
AssertNotInstrumented(verifier, "C.P.get");
AssertNotInstrumented(verifier, "C.P.set");
AssertNotInstrumented(verifier, "C.E.add");
AssertNotInstrumented(verifier, "C.E.remove");
AssertInstrumented(verifier, "D..ctor");
AssertInstrumented(verifier, "D..cctor");
AssertInstrumented(verifier, "D.M1");
AssertInstrumented(verifier, "D.P.get");
AssertInstrumented(verifier, "D.P.set");
AssertInstrumented(verifier, "D.E.add");
AssertInstrumented(verifier, "D.E.remove");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_NestedType()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class A
{
class B1
{
[ExcludeFromCodeCoverage]
class C
{
void M1() { Console.WriteLine(1); }
}
void M2() { Console.WriteLine(2); }
}
[ExcludeFromCodeCoverage]
partial class B2
{
partial class C1
{
void M3() { Console.WriteLine(3); }
}
class C2
{
void M4() { Console.WriteLine(4); }
}
void M5() { Console.WriteLine(5); }
}
partial class B2
{
[ExcludeFromCodeCoverage]
partial class C1
{
void M6() { Console.WriteLine(6); }
}
void M7() { Console.WriteLine(7); }
}
void M8() { Console.WriteLine(8); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "A.B1.C.M1");
AssertInstrumented(verifier, "A.B1.M2");
AssertNotInstrumented(verifier, "A.B2.C1.M3");
AssertNotInstrumented(verifier, "A.B2.C2.M4");
AssertNotInstrumented(verifier, "A.B2.C1.M6");
AssertNotInstrumented(verifier, "A.B2.M7");
AssertInstrumented(verifier, "A.M8");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Accessors()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
int P1 { get => 1; set {} }
[ExcludeFromCodeCoverage]
event Action E1 { add { } remove { } }
int P2 { get => 1; set {} }
event Action E2 { add { } remove { } }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.P1.get");
AssertNotInstrumented(verifier, "C.P1.set");
AssertNotInstrumented(verifier, "C.E1.add");
AssertNotInstrumented(verifier, "C.E1.remove");
AssertInstrumented(verifier, "C.P2.get");
AssertInstrumented(verifier, "C.P2.set");
AssertInstrumented(verifier, "C.E2.add");
AssertInstrumented(verifier, "C.E2.remove");
}
[CompilerTrait(CompilerFeature.InitOnlySetters)]
[Fact]
public void ExcludeFromCodeCoverageAttribute_Accessors_Init()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
int P1 { get => 1; init {} }
int P2 { get => 1; init {} }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource + IsExternalInitTypeDefinition,
options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9);
AssertNotInstrumented(verifier, "C.P1.get");
AssertNotInstrumented(verifier, "C.P1.init");
AssertInstrumented(verifier, "C.P2.get");
AssertInstrumented(verifier, "C.P2.init");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Good()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExcludeFromCodeCoverageAttribute : Attribute
{
public ExcludeFromCodeCoverageAttribute() {}
}
}
[ExcludeFromCodeCoverage]
class C
{
void M() {}
}
class D
{
void M() {}
}
";
var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
c.VerifyEmitDiagnostics();
AssertNotInstrumented(verifier, "C.M");
AssertInstrumented(verifier, "D.M");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExcludeFromCodeCoverageAttribute : Attribute
{
public ExcludeFromCodeCoverageAttribute(int x) {}
}
}
[ExcludeFromCodeCoverage(1)]
class C
{
void M() {}
}
class D
{
void M() {}
}
";
var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
c.VerifyEmitDiagnostics();
AssertInstrumented(verifier, "C.M");
AssertInstrumented(verifier, "D.M");
}
[Fact]
public void TestPartialMethodsWithImplementation()
{
var source = @"
using System;
public partial class Class1<T>
{
partial void Method1<U>(int x);
public void Method2(int x)
{
Console.WriteLine($""Method2: x = {x}"");
Method1<T>(x);
}
}
public partial class Class1<T>
{
partial void Method1<U>(int x)
{
Console.WriteLine($""Method1: x = {x}"");
if (x > 0)
{
Console.WriteLine(""Method1: x > 0"");
Method1<U>(0);
}
else if (x < 0)
{
Console.WriteLine(""Method1: x < 0"");
}
}
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
c.Method2(1);
}
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, "partial void Method1<U>(int x)")
.True(@"Console.WriteLine($""Method1: x = {x}"");")
.True(@"Console.WriteLine(""Method1: x > 0"");")
.True("Method1<U>(0);")
.False(@"Console.WriteLine(""Method1: x < 0"");")
.True("x < 0)")
.True("x > 0)");
checker.Method(2, 1, "public void Method2(int x)")
.True(@"Console.WriteLine($""Method2: x = {x}"");")
.True("Method1<T>(x);");
checker.Method(3, 1, ".ctor()", expectBodySpan: false);
checker.Method(4, 1, "public static void Main(string[] args)")
.True("Test();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(5, 1, "static void Test()")
.True(@"Console.WriteLine(""Test"");")
.True("var c = new Class1<int>();")
.True("c.Method2(1);");
checker.Method(8, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
var expectedOutput = @"Test
Method2: x = 1
Method1: x = 1
Method1: x > 0
Method1: x = 0
" + checker.ExpectedOutput;
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestPartialMethodsWithoutImplementation()
{
var source = @"
using System;
public partial class Class1<T>
{
partial void Method1<U>(int x);
public void Method2(int x)
{
Console.WriteLine($""Method2: x = {x}"");
Method1<T>(x);
}
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
c.Method2(1);
}
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, "public void Method2(int x)")
.True(@"Console.WriteLine($""Method2: x = {x}"");");
checker.Method(2, 1, ".ctor()", expectBodySpan: false);
checker.Method(3, 1, "public static void Main(string[] args)")
.True("Test();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(4, 1, "static void Test()")
.True(@"Console.WriteLine(""Test"");")
.True("var c = new Class1<int>();")
.True("c.Method2(1);");
checker.Method(7, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
var expectedOutput = @"Test
Method2: x = 1
" + checker.ExpectedOutput;
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestSynthesizedConstructorWithSpansInMultipleFilesCoverage()
{
var source1 = @"
using System;
public partial class Class1<T>
{
private int x = 1;
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
c.Method1(1);
}
}
" + InstrumentationHelperSource;
var source2 = @"
public partial class Class1<T>
{
private int y = 2;
}
public partial class Class1<T>
{
private int z = 3;
}";
var source3 = @"
using System;
public partial class Class1<T>
{
private Action<int> a = i =>
{
Console.WriteLine(i);
};
public void Method1(int i)
{
a(i);
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
}";
var sources = new[] {
(Name: "b.cs", Content: source1),
(Name: "c.cs", Content: source2),
(Name: "a.cs", Content: source3)
};
var expectedOutput = @"Test
1
1
2
3
Flushing
Method 1
File 1
True
True
True
True
True
Method 2
File 1
File 2
File 3
True
True
True
True
True
Method 3
File 2
True
True
True
Method 4
File 2
True
True
True
True
Method 7
File 2
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage()
{
var source1 = @"
using System;
public partial class Class1<T>
{
private static int x = 1;
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
Class1<int>.Method1(1);
}
}
" + InstrumentationHelperSource;
var source2 = @"
public partial class Class1<T>
{
private static int y = 2;
}
public partial class Class1<T>
{
private static int z = 3;
}";
var source3 = @"
using System;
public partial class Class1<T>
{
private static Action<int> a = i =>
{
Console.WriteLine(i);
};
public static void Method1(int i)
{
a(i);
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
}";
var sources = new[] {
(Name: "b.cs", Content: source1),
(Name: "c.cs", Content: source2),
(Name: "a.cs", Content: source3)
};
var expectedOutput = @"Test
1
1
2
3
Flushing
Method 1
File 1
True
True
True
True
True
Method 2
File 2
Method 3
File 1
File 2
File 3
True
True
True
True
True
Method 4
File 2
True
True
True
Method 5
File 2
True
True
True
True
Method 8
File 2
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestLineDirectiveCoverage()
{
var source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
#line 300 ""File2.cs""
Console.WriteLine(""Start"");
#line hidden
Console.WriteLine(""Hidden"");
#line default
Console.WriteLine(""Visible"");
#line 400 ""File3.cs""
Console.WriteLine(""End"");
}
}
" + InstrumentationHelperSource;
var expectedOutput = @"Start
Hidden
Visible
End
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
File 2
File 3
True
True
True
True
True
Method 5
File 3
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.TopLevelStatements)]
public void TopLevelStatements_01()
{
var source = @"
using System;
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
static void Test()
{
Console.WriteLine(""Test"");
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, snippet: "", expectBodySpan: false)
.True("Test();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();")
.True(@"Console.WriteLine(""Test"");");
checker.Method(5, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
var expectedOutput = @"Test
" + checker.ExpectedOutput;
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
}
private static void AssertNotInstrumented(CompilationVerifier verifier, string qualifiedMethodName)
=> AssertInstrumented(verifier, qualifiedMethodName, expected: false);
private static void AssertInstrumented(CompilationVerifier verifier, string qualifiedMethodName, bool expected = true)
{
string il = verifier.VisualizeIL(qualifiedMethodName);
// Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload,
// lambdas a reference to payload bool array.
bool instrumented = il.Contains("CreatePayload") || il.Contains("bool[]");
Assert.True(expected == instrumented, $"Method '{qualifiedMethodName}' should {(expected ? "be" : "not be")} instrumented. Actual IL:{Environment.NewLine}{il}");
}
private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, CSharpCompilationOptions options = null, CSharpParseOptions parseOptions = null, Verification verify = Verification.Passes)
{
return base.CompileAndVerify(
source,
expectedOutput: expectedOutput,
options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true),
parseOptions: parseOptions,
emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)),
verify: verify);
}
private CompilationVerifier CompileAndVerify((string Path, string Content)[] sources, string expectedOutput = null, CSharpCompilationOptions options = null)
{
var trees = ArrayBuilder<SyntaxTree>.GetInstance();
foreach (var source in sources)
{
// The trees must be assigned unique file names in order for instrumentation to work correctly.
trees.Add(Parse(source.Content, filename: source.Path));
}
var compilation = CreateCompilation(trees.ToArray(), options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true));
trees.Free();
return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Test.Utilities.CSharpInstrumentationChecker;
namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests
{
public class DynamicInstrumentationTests : CSharpTestBase
{
[Fact]
public void HelpersInstrumentation()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
Method 4
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
string expectedCreatePayloadForMethodsSpanningSingleFileIL = @"{
// Code size 21 (0x15)
.maxstack 6
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldc.i4.1
IL_0003: newarr ""int""
IL_0008: dup
IL_0009: ldc.i4.0
IL_000a: ldarg.2
IL_000b: stelem.i4
IL_000c: ldarg.3
IL_000d: ldarg.s V_4
IL_000f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)""
IL_0014: ret
}";
string expectedCreatePayloadForMethodsSpanningMultipleFilesIL = @"{
// Code size 87 (0x57)
.maxstack 3
IL_0000: ldsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid""
IL_0005: ldarg.0
IL_0006: call ""bool System.Guid.op_Inequality(System.Guid, System.Guid)""
IL_000b: brfalse.s IL_002b
IL_000d: ldc.i4.s 100
IL_000f: newarr ""bool[]""
IL_0014: stsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0019: ldc.i4.s 100
IL_001b: newarr ""int[]""
IL_0020: stsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_0025: ldarg.0
IL_0026: stsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid""
IL_002b: ldarg.3
IL_002c: ldarg.s V_4
IL_002e: newarr ""bool""
IL_0033: ldnull
IL_0034: call ""bool[] System.Threading.Interlocked.CompareExchange<bool[]>(ref bool[], bool[], bool[])""
IL_0039: brtrue.s IL_004f
IL_003b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0040: ldarg.1
IL_0041: ldarg.3
IL_0042: ldind.ref
IL_0043: stelem.ref
IL_0044: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_0049: ldarg.1
IL_004a: ldarg.2
IL_004b: stelem.ref
IL_004c: ldarg.3
IL_004d: ldind.ref
IL_004e: ret
IL_004f: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0054: ldarg.1
IL_0055: ldelem.ref
IL_0056: ret
}";
string expectedFlushPayloadIL = @"{
// Code size 288 (0x120)
.maxstack 5
.locals init (bool[] V_0,
int V_1, //i
bool[] V_2, //payload
int V_3, //j
int V_4) //j
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0035
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.s 16
IL_002f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0034: stloc.0
IL_0035: ldloc.0
IL_0036: ldc.i4.0
IL_0037: ldc.i4.1
IL_0038: stelem.i1
IL_0039: ldloc.0
IL_003a: ldc.i4.1
IL_003b: ldc.i4.1
IL_003c: stelem.i1
IL_003d: ldstr ""Flushing""
IL_0042: call ""void System.Console.WriteLine(string)""
IL_0047: ldloc.0
IL_0048: ldc.i4.3
IL_0049: ldc.i4.1
IL_004a: stelem.i1
IL_004b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0050: brtrue.s IL_0057
IL_0052: ldloc.0
IL_0053: ldc.i4.2
IL_0054: ldc.i4.1
IL_0055: stelem.i1
IL_0056: ret
IL_0057: ldloc.0
IL_0058: ldc.i4.4
IL_0059: ldc.i4.1
IL_005a: stelem.i1
IL_005b: ldc.i4.0
IL_005c: stloc.1
IL_005d: br IL_0112
IL_0062: ldloc.0
IL_0063: ldc.i4.6
IL_0064: ldc.i4.1
IL_0065: stelem.i1
IL_0066: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_006b: ldloc.1
IL_006c: ldelem.ref
IL_006d: stloc.2
IL_006e: ldloc.0
IL_006f: ldc.i4.s 15
IL_0071: ldc.i4.1
IL_0072: stelem.i1
IL_0073: ldloc.2
IL_0074: brfalse IL_010a
IL_0079: ldloc.0
IL_007a: ldc.i4.7
IL_007b: ldc.i4.1
IL_007c: stelem.i1
IL_007d: ldstr ""Method ""
IL_0082: ldloca.s V_1
IL_0084: call ""string int.ToString()""
IL_0089: call ""string string.Concat(string, string)""
IL_008e: call ""void System.Console.WriteLine(string)""
IL_0093: ldloc.0
IL_0094: ldc.i4.8
IL_0095: ldc.i4.1
IL_0096: stelem.i1
IL_0097: ldc.i4.0
IL_0098: stloc.3
IL_0099: br.s IL_00ca
IL_009b: ldloc.0
IL_009c: ldc.i4.s 10
IL_009e: ldc.i4.1
IL_009f: stelem.i1
IL_00a0: ldstr ""File ""
IL_00a5: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_00aa: ldloc.1
IL_00ab: ldelem.ref
IL_00ac: ldloc.3
IL_00ad: ldelema ""int""
IL_00b2: call ""string int.ToString()""
IL_00b7: call ""string string.Concat(string, string)""
IL_00bc: call ""void System.Console.WriteLine(string)""
IL_00c1: ldloc.0
IL_00c2: ldc.i4.s 9
IL_00c4: ldc.i4.1
IL_00c5: stelem.i1
IL_00c6: ldloc.3
IL_00c7: ldc.i4.1
IL_00c8: add
IL_00c9: stloc.3
IL_00ca: ldloc.3
IL_00cb: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices""
IL_00d0: ldloc.1
IL_00d1: ldelem.ref
IL_00d2: ldlen
IL_00d3: conv.i4
IL_00d4: blt.s IL_009b
IL_00d6: ldloc.0
IL_00d7: ldc.i4.s 11
IL_00d9: ldc.i4.1
IL_00da: stelem.i1
IL_00db: ldc.i4.0
IL_00dc: stloc.s V_4
IL_00de: br.s IL_0103
IL_00e0: ldloc.0
IL_00e1: ldc.i4.s 13
IL_00e3: ldc.i4.1
IL_00e4: stelem.i1
IL_00e5: ldloc.2
IL_00e6: ldloc.s V_4
IL_00e8: ldelem.u1
IL_00e9: call ""void System.Console.WriteLine(bool)""
IL_00ee: ldloc.0
IL_00ef: ldc.i4.s 14
IL_00f1: ldc.i4.1
IL_00f2: stelem.i1
IL_00f3: ldloc.2
IL_00f4: ldloc.s V_4
IL_00f6: ldc.i4.0
IL_00f7: stelem.i1
IL_00f8: ldloc.0
IL_00f9: ldc.i4.s 12
IL_00fb: ldc.i4.1
IL_00fc: stelem.i1
IL_00fd: ldloc.s V_4
IL_00ff: ldc.i4.1
IL_0100: add
IL_0101: stloc.s V_4
IL_0103: ldloc.s V_4
IL_0105: ldloc.2
IL_0106: ldlen
IL_0107: conv.i4
IL_0108: blt.s IL_00e0
IL_010a: ldloc.0
IL_010b: ldc.i4.5
IL_010c: ldc.i4.1
IL_010d: stelem.i1
IL_010e: ldloc.1
IL_010f: ldc.i4.1
IL_0110: add
IL_0111: stloc.1
IL_0112: ldloc.1
IL_0113: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads""
IL_0118: ldlen
IL_0119: conv.i4
IL_011a: blt IL_0062
IL_011f: ret
}";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)", expectedCreatePayloadForMethodsSpanningSingleFileIL);
verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)", expectedCreatePayloadForMethodsSpanningMultipleFilesIL);
verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload", expectedFlushPayloadIL);
verifier.VerifyDiagnostics();
}
[Fact]
public void GotoCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain()
{
Console.WriteLine(""goo"");
goto bar;
Console.Write(""you won't see me"");
bar: Console.WriteLine(""bar"");
Fred();
return;
}
static void Wilma()
{
Betty(true);
Barney(true);
Barney(false);
Betty(true);
}
static int Barney(bool b)
{
if (b)
return 10;
if (b)
return 100;
return 20;
}
static int Betty(bool b)
{
if (b)
return 30;
if (b)
return 100;
return 40;
}
static void Fred()
{
Wilma();
}
}
";
string expectedOutput = @"goo
bar
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
False
True
True
True
Method 3
File 1
True
True
True
True
True
Method 4
File 1
True
True
True
False
True
True
Method 5
File 1
True
True
True
False
False
False
Method 6
File 1
True
True
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
string expectedBarneyIL = @"{
// Code size 91 (0x5b)
.maxstack 5
.locals init (bool[] V_0)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""int Program.Barney(bool)""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""int Program.Barney(bool)""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""int Program.Barney(bool)""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.6
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: brfalse.s IL_0046
IL_003f: ldloc.0
IL_0040: ldc.i4.1
IL_0041: ldc.i4.1
IL_0042: stelem.i1
IL_0043: ldc.i4.s 10
IL_0045: ret
IL_0046: ldloc.0
IL_0047: ldc.i4.4
IL_0048: ldc.i4.1
IL_0049: stelem.i1
IL_004a: ldarg.0
IL_004b: brfalse.s IL_0054
IL_004d: ldloc.0
IL_004e: ldc.i4.3
IL_004f: ldc.i4.1
IL_0050: stelem.i1
IL_0051: ldc.i4.s 100
IL_0053: ret
IL_0054: ldloc.0
IL_0055: ldc.i4.5
IL_0056: ldc.i4.1
IL_0057: stelem.i1
IL_0058: ldc.i4.s 20
IL_005a: ret
}";
string expectedPIDStaticConstructorIL = @"{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldtoken Max Method Token Index
IL_0005: ldc.i4.1
IL_0006: add
IL_0007: newarr ""bool[]""
IL_000c: stsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0011: ldstr ##MVID##
IL_0016: newobj ""System.Guid..ctor(string)""
IL_001b: stsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0020: ret
}";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Barney", expectedBarneyIL);
verifier.VerifyIL(".cctor", expectedPIDStaticConstructorIL);
verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(16, 9));
}
[Fact]
public void MethodsOfGenericTypesCoverage()
{
string source = @"
using System;
class MyBox<T> where T : class
{
readonly T _value;
public MyBox(T value)
{
_value = value;
}
public T GetValue()
{
if (_value == null)
{
return null;
}
return _value;
}
}
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain()
{
MyBox<object> x = new MyBox<object>(null);
Console.WriteLine(x.GetValue() == null ? ""null"" : x.GetValue().ToString());
MyBox<string> s = new MyBox<string>(""Hello"");
Console.WriteLine(s.GetValue() == null ? ""null"" : s.GetValue());
}
}
";
// All instrumentation points in method 2 are True because they are covered by at least one specialization.
//
// This test verifies that the payloads of methods of generic types are in terms of method definitions and
// not method references -- the indices for the methods would be different for references.
string expectedOutput = @"null
Hello
Flushing
Method 1
File 1
True
True
Method 2
File 1
True
True
True
True
Method 3
File 1
True
True
True
Method 4
File 1
True
True
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
string expectedReleaseGetValueIL = @"{
// Code size 98 (0x62)
.maxstack 5
.locals init (bool[] V_0,
T V_1)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""T MyBox<T>.GetValue()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""T MyBox<T>.GetValue()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""T MyBox<T>.GetValue()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.4
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: ldfld ""T MyBox<T>._value""
IL_0042: box ""T""
IL_0047: brtrue.s IL_0057
IL_0049: ldloc.0
IL_004a: ldc.i4.1
IL_004b: ldc.i4.1
IL_004c: stelem.i1
IL_004d: ldloca.s V_1
IL_004f: initobj ""T""
IL_0055: ldloc.1
IL_0056: ret
IL_0057: ldloc.0
IL_0058: ldc.i4.3
IL_0059: ldc.i4.1
IL_005a: stelem.i1
IL_005b: ldarg.0
IL_005c: ldfld ""T MyBox<T>._value""
IL_0061: ret
}";
string expectedDebugGetValueIL = @"{
// Code size 110 (0x6e)
.maxstack 5
.locals init (bool[] V_0,
bool V_1,
T V_2,
T V_3)
IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0005: ldtoken ""T MyBox<T>.GetValue()""
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID""
IL_0014: ldtoken ""T MyBox<T>.GetValue()""
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0""
IL_0023: ldtoken ""T MyBox<T>.GetValue()""
IL_0028: ldelema ""bool[]""
IL_002d: ldc.i4.4
IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.0
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: ldfld ""T MyBox<T>._value""
IL_0042: box ""T""
IL_0047: ldnull
IL_0048: ceq
IL_004a: stloc.1
IL_004b: ldloc.1
IL_004c: brfalse.s IL_005f
IL_004e: nop
IL_004f: ldloc.0
IL_0050: ldc.i4.1
IL_0051: ldc.i4.1
IL_0052: stelem.i1
IL_0053: ldloca.s V_2
IL_0055: initobj ""T""
IL_005b: ldloc.2
IL_005c: stloc.3
IL_005d: br.s IL_006c
IL_005f: ldloc.0
IL_0060: ldc.i4.3
IL_0061: ldc.i4.1
IL_0062: stelem.i1
IL_0063: ldarg.0
IL_0064: ldfld ""T MyBox<T>._value""
IL_0069: stloc.3
IL_006a: br.s IL_006c
IL_006c: ldloc.3
IL_006d: ret
}";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyIL("MyBox<T>.GetValue", expectedReleaseGetValueIL);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyIL("MyBox<T>.GetValue", expectedDebugGetValueIL);
verifier.VerifyDiagnostics();
}
[Fact]
public void NonStaticImplicitBlockMethodsCoverage()
{
string source = @"
using System;
public class Program
{
public int Prop { get; }
public int Prop2 { get; } = 25;
public int Prop3 { get; set; } // Methods 3 and 4
public Program() // Method 5
{
Prop = 12;
Prop3 = 12;
Prop2 = Prop3;
}
public static void Main(string[] args) // Method 6
{
new Program();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(3, 1, "public int Prop3")
.True("get");
checker.Method(4, 1, "public int Prop3")
.True("set");
checker.Method(5, 1, "public Program()")
.True("25")
.True("Prop = 12;")
.True("Prop3 = 12;")
.True("Prop2 = Prop3;");
checker.Method(6, 1, "public static void Main")
.True("new Program();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(8, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
}
[Fact]
public void ImplicitBlockMethodsCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
int x = Count;
x += Prop;
Prop = x;
x += Prop2;
Lambda(x, (y) => y + 1);
}
static int Function(int x) => x;
static int Count => Function(44);
static int Prop { get; set; }
static int Prop2 { get; set; } = 12;
static int Lambda(int x, Func<int, int> l)
{
return l(x);
}
// Method 11 is a synthesized static constructor.
}
";
// There is no entry for method '8' since it's a Prop2_set which is never called.
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
Method 5
File 1
True
True
Method 6
File 1
True
True
Method 7
File 1
True
True
Method 9
File 1
True
True
Method 11
File 1
True
Method 13
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void LocalFunctionWithLambdaCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
new D().M1();
}
}
public class D
{
public void M1() // Method 4
{
L1();
void L1()
{
var f = new Func<int>(
() => 1
);
var f1 = new Func<int>(
() => 2
);
var f2 = new Func<int, int>(
(x) => x + 3
);
var f3 = new Func<int, int>(
x => x + 4
);
f();
f3(2);
}
}
// Method 5 is the synthesized instance constructor for D.
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, "public static void Main")
.True("TestMain();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(2, 1, "static void TestMain")
.True("new D().M1();");
checker.Method(4, 1, "public void M1()")
.True("L1();")
.True("1")
.True("var f = new Func<int>")
.False("2")
.True("var f1 = new Func<int>")
.False("x + 3")
.True("var f2 = new Func<int, int>")
.True("x + 4")
.True("var f3 = new Func<int, int>")
.True("f();")
.True("f3(2);");
checker.Method(5, 1, snippet: null, expectBodySpan: false);
checker.Method(7, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
checker.CompleteCheck(verifier.Compilation, source);
}
[Fact]
public void MultipleFilesCoverage()
{
string source = @"
using System;
public class Program
{
#line 10 ""File1.cs""
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
#line 20 ""File2.cs""
static void TestMain() // Method 2
{
Fred();
Program p = new Program();
return;
}
#line 30 ""File3.cs""
static void Fred() // Method 3
{
return;
}
#line 40 ""File5.cs""
// The synthesized instance constructor is method 4 and
// appears in the original source file, which gets file index 4.
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 2
True
True
True
True
Method 3
File 3
True
True
Method 4
File 4
Method 6
File 5
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void MultipleDeclarationsCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
int x;
int a, b;
DoubleDeclaration(5);
DoubleForDeclaration(5);
}
static int DoubleDeclaration(int x) // Method 3
{
int c = x;
int a, b;
int f;
a = b = f = c;
int d = a, e = b;
return d + e + f;
}
static int DoubleForDeclaration(int x) // Method 4
{
for(int a = x, b = x; a + b < 10; a++)
{
Console.WriteLine(""Cannot get here."");
x++;
}
return x;
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
True
True
True
True
Method 4
File 1
True
True
True
False
False
False
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(14, 13),
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(15, 13),
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(15, 16));
}
[Fact]
public void UsingAndFixedCoverage()
{
string source = @"
using System;
using System.IO;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
using (var memoryStream = new MemoryStream())
{
;
}
using (MemoryStream s1 = new MemoryStream(), s2 = new MemoryStream())
{
;
}
var otherStream = new MemoryStream();
using (otherStream)
{
;
}
unsafe
{
double[] a = { 1, 2, 3 };
fixed(double* p = a)
{
;
}
fixed(double* q = a, r = a)
{
;
}
}
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails);
verifier.VerifyDiagnostics();
}
[Fact]
public void ManyStatementsCoverage() // Method 3
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain()
{
VariousStatements(2);
Empty();
}
static void VariousStatements(int z)
{
int x = z + 10;
switch (z)
{
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
if (x > 10)
{
x++;
}
else
{
x--;
}
for (int y = 0; y < 50; y++)
{
if (y < 30)
{
x++;
continue;
}
else
break;
}
int[] a = new int[] { 1, 2, 3, 4 };
foreach (int i in a)
{
x++;
}
while (x < 100)
{
x++;
}
try
{
x++;
if (x > 10)
{
throw new System.Exception();
}
x++;
}
catch (System.Exception)
{
x++;
}
finally
{
x++;
}
lock (new object())
{
;
}
Console.WriteLine(x);
try
{
using ((System.IDisposable)new object())
{
;
}
}
catch (System.Exception)
{
}
// Include an infinite loop to make sure that a compiler optimization doesn't eliminate the instrumentation.
while (true)
{
return;
}
}
static void Empty() // Method 4
{
}
}
";
string expectedOutput = @"103
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
False
True
False
False
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
False
True
True
True
True
True
False
True
True
True
Method 4
File 1
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void PatternsCoverage()
{
string source = @"
using System;
public class C
{
public static void Main()
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = s.Name switch { _ => 2.3 }; // switch expression is not instrumented
Operate(s);
}
static string Operate(Person p) // Method 3
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
// Methods 5 and 7 are implicit constructors.
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
Method 3
File 1
True
True
False
True
False
False
True
Method 5
File 1
Method 7
File 1
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Subject").WithArguments("Teacher.Subject", "null").WithLocation(37, 40));
}
/// <see cref="DynamicAnalysisResourceTests.TestPatternSpans_WithSharedWhenExpression"/>
/// for meaning of the spans
[Fact]
public void PatternsCoverage_WithSharedWhenExpression()
{
string source = @"
using System;
public class C
{
public static void Main()
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
public static void TestMain()
{
Method3(1, b1: false, b2: false);
}
static string Method3(int i, bool b1, bool b2) // Method 3
{
switch (i)
{
case not 1 when b1:
return ""b1"";
case var _ when b2:
return ""b2"";
case 1:
return ""1"";
default:
return ""default"";
}
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 3
File 1
True
False
True
False
False
True
False
True
Method 6
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
}
[Fact]
public void DeconstructionStatementCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain2();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain2() // Method 2
{
var (x, y) = new C();
}
static void TestMain3() // Method 3
{
var (x, y) = new C();
}
public C() // Method 4
{
}
public void Deconstruct(out int x, out int y) // Method 5
{
x = 1;
y = 1 switch { 1 => 2, 3 => 4, _ => 5 }; // switch expression is not instrumented
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 4
File 1
True
Method 5
File 1
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
}
[Fact]
public void DeconstructionForeachStatementCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain2(new C[] { new C() });
TestMain3(new C[] { });
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain2(C[] a) // Method 2
{
foreach (
var (x, y)
in a)
;
}
static void TestMain3(C[] a) // Method 3
{
foreach (
var (x, y)
in a)
;
}
public C() // Method 4
{
}
public void Deconstruct(out int x, out int y) // Method 5
{
x = 1;
y = 2;
}
}
";
string expectedOutput = @"Flushing
Method 1
File 1
True
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
False
False
Method 4
File 1
True
Method 5
File 1
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
}
[Fact]
public void LambdaCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); // Method 2
}
static void TestMain()
{
int y = 5;
Func<int, int> tester = (x) =>
{
while (x > 10)
{
return y;
}
return x;
};
y = 75;
if (tester(20) > 50)
Console.WriteLine(""OK"");
else
Console.WriteLine(""Bad"");
}
}
";
string expectedOutput = @"OK
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
False
True
True
True
False
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void AsyncCoverage()
{
string source = @"
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
Console.WriteLine(Outer(""Goo"").Result);
}
async static Task<string> Outer(string s) // Method 3
{
string s1 = await First(s);
string s2 = await Second(s);
return s1 + s2;
}
async static Task<string> First(string s) // Method 4
{
string result = await Second(s) + ""Glue"";
if (result.Length > 2)
return result;
else
return ""Too short"";
}
async static Task<string> Second(string s) // Method 5
{
string doubled = """";
if (s.Length > 2)
doubled = s + s;
else
doubled = ""HuhHuh"";
return await Task.Factory.StartNew(() => doubled);
}
}
";
string expectedOutput = @"GooGooGlueGooGoo
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 3
File 1
True
True
True
True
Method 4
File 1
True
True
True
False
True
Method 5
File 1
True
True
True
False
True
True
True
Method 8
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void IteratorCoverage()
{
string source = @"
using System;
public class Program
{
public static void Main(string[] args) // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
foreach (var i in Goo())
{
Console.WriteLine(i);
}
foreach (var i in Goo())
{
Console.WriteLine(i);
}
}
public static System.Collections.Generic.IEnumerable<int> Goo()
{
for (int i = 0; i < 5; ++i)
{
yield return i;
}
}
}
";
string expectedOutput = @"0
1
2
3
4
0
1
2
3
4
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
Method 3
File 1
True
True
True
True
Method 6
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestFieldInitializerCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
C local = new C(); local = new C(1, s_z);
}
static int Init() => 33; // Method 3
C() // Method 4
{
_z = 12;
}
static C() // Method 5
{
s_z = 123;
}
int _x = Init();
int _y = Init() + 12;
int _z;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z;
C(int x) // Method 6
{
_z = x;
}
C(int a, int b) // Method 7
{
_z = a + b;
}
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
string expectedOutput = @"
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
True
True
True
Method 5
File 1
True
True
True
True
True
Method 7
File 1
True
True
True
True
True
Method 11
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestImplicitConstructorCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
C local = new C();
int x = local._x + local._y + C.s_x + C.s_y + C.s_z;
}
static int Init() => 33; // Method 3
// Method 6 is the implicit instance constructor.
// Method 7 is the implicit shared constructor.
int _x = Init();
int _y = Init() + 12;
static int s_x = Init();
static int s_y = Init() + 153;
static int s_z = 144;
int Prop1 { get; } = 15;
static int Prop2 { get; } = 255;
}
";
string expectedOutput = @"
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
Method 6
File 1
True
True
True
Method 7
File 1
True
True
True
True
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestImplicitConstructorsWithLambdasCoverage()
{
string source = @"
using System;
public class C
{
public static void Main() // Method 1
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void TestMain() // Method 2
{
int y = s_c._function();
D d = new D();
int z = d._c._function();
int zz = D.s_c._function();
int zzz = d._c1._function();
}
public C(Func<int> f) // Method 3
{
_function = f;
}
static C s_c = new C(() => 115);
Func<int> _function;
}
partial class D
{
}
partial class D
{
}
partial class D
{
public C _c = new C(() => 120);
public static C s_c = new C(() => 144);
public C _c1 = new C(() => 130);
public static C s_c1 = new C(() => 156);
}
partial class D
{
}
partial struct E
{
}
partial struct E
{
public static C s_c = new C(() => 1444);
public static C s_c1 = new C(() => { return 1567; });
}
// Method 4 is the synthesized static constructor for C.
// Method 5 is the synthesized instance constructor for D.
// Method 6 is the synthesized static constructor for D.
";
string expectedOutput = @"
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
Method 5
File 1
True
True
True
True
Method 6
File 1
True
False
True
True
Method 9
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
}
[Fact]
public void MissingMethodNeededForAnalysis()
{
string source = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class Exception { }
public class ValueType { }
public class Enum { }
public struct Void { }
public class Guid { }
}
public class Console
{
public static void WriteLine(string s) { }
public static void WriteLine(int i) { }
public static void WriteLine(bool b) { }
}
public class Program
{
public static void Main(string[] args)
{
TestMain();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static int TestMain()
{
return 3;
}
}
";
ImmutableArray<Diagnostic> diagnostics = CreateEmptyCompilation(source + InstrumentationHelperSource).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
foreach (Diagnostic diagnostic in diagnostics)
{
if (diagnostic.Code == (int)ErrorCode.ERR_MissingPredefinedMember &&
diagnostic.Arguments[0].Equals("System.Guid") && diagnostic.Arguments[1].Equals(".ctor"))
{
return;
}
}
Assert.True(false);
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Method()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
void M1() { Console.WriteLine(1); }
void M2() { Console.WriteLine(1); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.M1");
AssertInstrumented(verifier, "C.M2");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Ctor()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
int a = 1;
[ExcludeFromCodeCoverage]
public C() { Console.WriteLine(3); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..ctor");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Cctor()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static int a = 1;
[ExcludeFromCodeCoverage]
static C() { Console.WriteLine(3); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..cctor");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InMethod()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
static void M1() { L1(); void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); } }
static void M2() { L2(); void L2() { new Action(() => { Console.WriteLine(2); }).Invoke(); } }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.M1");
AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0");
AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1");
AssertInstrumented(verifier, "C.M2");
AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>g__L2|0"); // M2:L2
AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>b__1"); // M2:L2 lambda
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static void M1()
{
L1();
[ExcludeFromCodeCoverage]
void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); }
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource,
options: TestOptions.ReleaseDll,
parseOptions: TestOptions.Regular9);
AssertInstrumented(verifier, "C.M1");
AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0()");
AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1()");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Multiple()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static void M1()
{
#pragma warning disable 8321 // Unreferenced local function
void L1() { Console.WriteLine(1); }
[ExcludeFromCodeCoverage]
void L2() { Console.WriteLine(2); }
void L3() { Console.WriteLine(3); }
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource,
options: TestOptions.ReleaseDll,
parseOptions: TestOptions.Regular9);
AssertInstrumented(verifier, "C.M1");
AssertInstrumented(verifier, "C.<M1>g__L1|0_0(ref C.<>c__DisplayClass0_0)");
AssertNotInstrumented(verifier, "C.<M1>g__L2|0_1()");
AssertInstrumented(verifier, "C.<M1>g__L3|0_2(ref C.<>c__DisplayClass0_0)");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Nested()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
static void M1()
{
L1();
void L1()
{
new Action(() =>
{
L2();
[ExcludeFromCodeCoverage]
void L2()
{
new Action(() =>
{
L3();
void L3()
{
Console.WriteLine(1);
}
}).Invoke();
}
}).Invoke();
}
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource,
options: TestOptions.ReleaseDll,
parseOptions: TestOptions.Regular9);
AssertInstrumented(verifier, "C.M1");
AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>g__L1|0()");
AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>b__1()");
AssertNotInstrumented(verifier, "C.<M1>g__L2|0_2()");
AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_3");
AssertNotInstrumented(verifier, "C.<M1>g__L3|0_4()");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InInitializers()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
Action IF = new Action(() => { Console.WriteLine(1); });
Action IP { get; } = new Action(() => { Console.WriteLine(2); });
static Action SF = new Action(() => { Console.WriteLine(3); });
static Action SP { get; } = new Action(() => { Console.WriteLine(4); });
[ExcludeFromCodeCoverage]
C() {}
static C() {}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..ctor");
AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_0");
AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_1");
AssertInstrumented(verifier, "C..cctor");
AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__0");
AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__1");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InAccessors()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
int P1
{
get { L1(); void L1() { Console.WriteLine(1); } return 1; }
set { L2(); void L2() { Console.WriteLine(2); } }
}
int P2
{
get { L3(); void L3() { Console.WriteLine(3); } return 3; }
set { L4(); void L4() { Console.WriteLine(4); } }
}
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.P1.get");
AssertNotInstrumented(verifier, "C.P1.set");
AssertNotInstrumented(verifier, "C.<get_P1>g__L1|1_0");
AssertNotInstrumented(verifier, "C.<set_P1>g__L2|2_0");
AssertInstrumented(verifier, "C.P2.get");
AssertInstrumented(verifier, "C.P2.set");
AssertInstrumented(verifier, "C.<get_P2>g__L3|4_0");
AssertInstrumented(verifier, "C.<set_P2>g__L4|5_0");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_LambdaAttributes()
{
string source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void M1()
{
Action a1 = static () =>
{
Func<bool, int> f1 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; };
Func<bool, int> f2 = static (bool b) => { if (b) return 0; return 1; };
};
}
static void M2()
{
Action a2 = [ExcludeFromCodeCoverage] static () =>
{
Func<bool, int> f3 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; };
Func<bool, int> f4 = static (bool b) => { if (b) return 0; return 1; };
};
}
}";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview);
AssertInstrumented(verifier, "Program.M1");
AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__0()");
AssertNotInstrumented(verifier, "Program.<>c.<M1>b__0_1(bool)");
AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__2(bool)");
AssertInstrumented(verifier, "Program.M2");
AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_0()");
AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_1(bool)");
AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_2(bool)");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Type()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
class C
{
int x = 1;
static C() { }
void M1() { Console.WriteLine(1); }
int P { get => 1; set { } }
event Action E { add { } remove { } }
}
class D
{
int x = 1;
static D() { }
void M1() { Console.WriteLine(1); }
int P { get => 1; set { } }
event Action E { add { } remove { } }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C..ctor");
AssertNotInstrumented(verifier, "C..cctor");
AssertNotInstrumented(verifier, "C.M1");
AssertNotInstrumented(verifier, "C.P.get");
AssertNotInstrumented(verifier, "C.P.set");
AssertNotInstrumented(verifier, "C.E.add");
AssertNotInstrumented(verifier, "C.E.remove");
AssertInstrumented(verifier, "D..ctor");
AssertInstrumented(verifier, "D..cctor");
AssertInstrumented(verifier, "D.M1");
AssertInstrumented(verifier, "D.P.get");
AssertInstrumented(verifier, "D.P.set");
AssertInstrumented(verifier, "D.E.add");
AssertInstrumented(verifier, "D.E.remove");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_NestedType()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class A
{
class B1
{
[ExcludeFromCodeCoverage]
class C
{
void M1() { Console.WriteLine(1); }
}
void M2() { Console.WriteLine(2); }
}
[ExcludeFromCodeCoverage]
partial class B2
{
partial class C1
{
void M3() { Console.WriteLine(3); }
}
class C2
{
void M4() { Console.WriteLine(4); }
}
void M5() { Console.WriteLine(5); }
}
partial class B2
{
[ExcludeFromCodeCoverage]
partial class C1
{
void M6() { Console.WriteLine(6); }
}
void M7() { Console.WriteLine(7); }
}
void M8() { Console.WriteLine(8); }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "A.B1.C.M1");
AssertInstrumented(verifier, "A.B1.M2");
AssertNotInstrumented(verifier, "A.B2.C1.M3");
AssertNotInstrumented(verifier, "A.B2.C2.M4");
AssertNotInstrumented(verifier, "A.B2.C1.M6");
AssertNotInstrumented(verifier, "A.B2.M7");
AssertInstrumented(verifier, "A.M8");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_Accessors()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
int P1 { get => 1; set {} }
[ExcludeFromCodeCoverage]
event Action E1 { add { } remove { } }
int P2 { get => 1; set {} }
event Action E2 { add { } remove { } }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
AssertNotInstrumented(verifier, "C.P1.get");
AssertNotInstrumented(verifier, "C.P1.set");
AssertNotInstrumented(verifier, "C.E1.add");
AssertNotInstrumented(verifier, "C.E1.remove");
AssertInstrumented(verifier, "C.P2.get");
AssertInstrumented(verifier, "C.P2.set");
AssertInstrumented(verifier, "C.E2.add");
AssertInstrumented(verifier, "C.E2.remove");
}
[CompilerTrait(CompilerFeature.InitOnlySetters)]
[Fact]
public void ExcludeFromCodeCoverageAttribute_Accessors_Init()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
class C
{
[ExcludeFromCodeCoverage]
int P1 { get => 1; init {} }
int P2 { get => 1; init {} }
}
";
var verifier = CompileAndVerify(source + InstrumentationHelperSource + IsExternalInitTypeDefinition,
options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9);
AssertNotInstrumented(verifier, "C.P1.get");
AssertNotInstrumented(verifier, "C.P1.init");
AssertInstrumented(verifier, "C.P2.get");
AssertInstrumented(verifier, "C.P2.init");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Good()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExcludeFromCodeCoverageAttribute : Attribute
{
public ExcludeFromCodeCoverageAttribute() {}
}
}
[ExcludeFromCodeCoverage]
class C
{
void M() {}
}
class D
{
void M() {}
}
";
var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
c.VerifyEmitDiagnostics();
AssertNotInstrumented(verifier, "C.M");
AssertInstrumented(verifier, "D.M");
}
[Fact]
public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad()
{
string source = @"
using System;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExcludeFromCodeCoverageAttribute : Attribute
{
public ExcludeFromCodeCoverageAttribute(int x) {}
}
}
[ExcludeFromCodeCoverage(1)]
class C
{
void M() {}
}
class D
{
void M() {}
}
";
var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
c.VerifyEmitDiagnostics();
AssertInstrumented(verifier, "C.M");
AssertInstrumented(verifier, "D.M");
}
[Fact]
public void TestPartialMethodsWithImplementation()
{
var source = @"
using System;
public partial class Class1<T>
{
partial void Method1<U>(int x);
public void Method2(int x)
{
Console.WriteLine($""Method2: x = {x}"");
Method1<T>(x);
}
}
public partial class Class1<T>
{
partial void Method1<U>(int x)
{
Console.WriteLine($""Method1: x = {x}"");
if (x > 0)
{
Console.WriteLine(""Method1: x > 0"");
Method1<U>(0);
}
else if (x < 0)
{
Console.WriteLine(""Method1: x < 0"");
}
}
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
c.Method2(1);
}
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, "partial void Method1<U>(int x)")
.True(@"Console.WriteLine($""Method1: x = {x}"");")
.True(@"Console.WriteLine(""Method1: x > 0"");")
.True("Method1<U>(0);")
.False(@"Console.WriteLine(""Method1: x < 0"");")
.True("x < 0)")
.True("x > 0)");
checker.Method(2, 1, "public void Method2(int x)")
.True(@"Console.WriteLine($""Method2: x = {x}"");")
.True("Method1<T>(x);");
checker.Method(3, 1, ".ctor()", expectBodySpan: false);
checker.Method(4, 1, "public static void Main(string[] args)")
.True("Test();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(5, 1, "static void Test()")
.True(@"Console.WriteLine(""Test"");")
.True("var c = new Class1<int>();")
.True("c.Method2(1);");
checker.Method(8, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
var expectedOutput = @"Test
Method2: x = 1
Method1: x = 1
Method1: x > 0
Method1: x = 0
" + checker.ExpectedOutput;
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestPartialMethodsWithoutImplementation()
{
var source = @"
using System;
public partial class Class1<T>
{
partial void Method1<U>(int x);
public void Method2(int x)
{
Console.WriteLine($""Method2: x = {x}"");
Method1<T>(x);
}
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
c.Method2(1);
}
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, "public void Method2(int x)")
.True(@"Console.WriteLine($""Method2: x = {x}"");");
checker.Method(2, 1, ".ctor()", expectBodySpan: false);
checker.Method(3, 1, "public static void Main(string[] args)")
.True("Test();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();");
checker.Method(4, 1, "static void Test()")
.True(@"Console.WriteLine(""Test"");")
.True("var c = new Class1<int>();")
.True("c.Method2(1);");
checker.Method(7, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
var expectedOutput = @"Test
Method2: x = 1
" + checker.ExpectedOutput;
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestSynthesizedConstructorWithSpansInMultipleFilesCoverage()
{
var source1 = @"
using System;
public partial class Class1<T>
{
private int x = 1;
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
c.Method1(1);
}
}
" + InstrumentationHelperSource;
var source2 = @"
public partial class Class1<T>
{
private int y = 2;
}
public partial class Class1<T>
{
private int z = 3;
}";
var source3 = @"
using System;
public partial class Class1<T>
{
private Action<int> a = i =>
{
Console.WriteLine(i);
};
public void Method1(int i)
{
a(i);
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
}";
var sources = new[] {
(Name: "b.cs", Content: source1),
(Name: "c.cs", Content: source2),
(Name: "a.cs", Content: source3)
};
var expectedOutput = @"Test
1
1
2
3
Flushing
Method 1
File 1
True
True
True
True
True
Method 2
File 1
File 2
File 3
True
True
True
True
True
Method 3
File 2
True
True
True
Method 4
File 2
True
True
True
True
Method 7
File 2
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage()
{
var source1 = @"
using System;
public partial class Class1<T>
{
private static int x = 1;
}
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
Console.WriteLine(""Test"");
var c = new Class1<int>();
Class1<int>.Method1(1);
}
}
" + InstrumentationHelperSource;
var source2 = @"
public partial class Class1<T>
{
private static int y = 2;
}
public partial class Class1<T>
{
private static int z = 3;
}";
var source3 = @"
using System;
public partial class Class1<T>
{
private static Action<int> a = i =>
{
Console.WriteLine(i);
};
public static void Method1(int i)
{
a(i);
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
}";
var sources = new[] {
(Name: "b.cs", Content: source1),
(Name: "c.cs", Content: source2),
(Name: "a.cs", Content: source3)
};
var expectedOutput = @"Test
1
1
2
3
Flushing
Method 1
File 1
True
True
True
True
True
Method 2
File 2
Method 3
File 1
File 2
File 3
True
True
True
True
True
Method 4
File 2
True
True
True
Method 5
File 2
True
True
True
True
Method 8
File 2
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
public void TestLineDirectiveCoverage()
{
var source = @"
using System;
public class Program
{
public static void Main(string[] args)
{
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
}
static void Test()
{
#line 300 ""File2.cs""
Console.WriteLine(""Start"");
#line hidden
Console.WriteLine(""Hidden"");
#line default
Console.WriteLine(""Visible"");
#line 400 ""File3.cs""
Console.WriteLine(""End"");
}
}
" + InstrumentationHelperSource;
var expectedOutput = @"Start
Hidden
Visible
End
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
File 2
File 3
True
True
True
True
True
Method 5
File 3
True
True
False
True
True
True
True
True
True
True
True
True
True
True
True
True
";
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.TopLevelStatements)]
public void TopLevelStatements_01()
{
var source = @"
using System;
Test();
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();
static void Test()
{
Console.WriteLine(""Test"");
}
" + InstrumentationHelperSource;
var checker = new CSharpInstrumentationChecker();
checker.Method(1, 1, snippet: "", expectBodySpan: false)
.True("Test();")
.True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();")
.True(@"Console.WriteLine(""Test"");");
checker.Method(5, 1)
.True()
.False()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True()
.True();
var expectedOutput = @"Test
" + checker.ExpectedOutput;
var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
checker.CompleteCheck(verifier.Compilation, source);
verifier.VerifyDiagnostics();
}
private static void AssertNotInstrumented(CompilationVerifier verifier, string qualifiedMethodName)
=> AssertInstrumented(verifier, qualifiedMethodName, expected: false);
private static void AssertInstrumented(CompilationVerifier verifier, string qualifiedMethodName, bool expected = true)
{
string il = verifier.VisualizeIL(qualifiedMethodName);
// Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload,
// lambdas a reference to payload bool array.
bool instrumented = il.Contains("CreatePayload") || il.Contains("bool[]");
Assert.True(expected == instrumented, $"Method '{qualifiedMethodName}' should {(expected ? "be" : "not be")} instrumented. Actual IL:{Environment.NewLine}{il}");
}
private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, CSharpCompilationOptions options = null, CSharpParseOptions parseOptions = null, Verification verify = Verification.Passes)
{
return base.CompileAndVerify(
source,
expectedOutput: expectedOutput,
options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true),
parseOptions: parseOptions,
emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)),
verify: verify);
}
private CompilationVerifier CompileAndVerify((string Path, string Content)[] sources, string expectedOutput = null, CSharpCompilationOptions options = null)
{
var trees = ArrayBuilder<SyntaxTree>.GetInstance();
foreach (var source in sources)
{
// The trees must be assigned unique file names in order for instrumentation to work correctly.
trees.Add(Parse(source.Content, filename: source.Path));
}
var compilation = CreateCompilation(trees.ToArray(), options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true));
trees.Free();
return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Test/Emit/PDB/PDBTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBTests : CSharpPDBTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
#region General
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding1()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { }", encoding: null, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class C { }", encoding: null), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree("class D { }", encoding: Encoding.UTF8, path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify(
// Foo.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class A { }").WithLocation(1, 1),
// Bar.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class C { }").WithLocation(1, 1));
Assert.False(result.Success);
}
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding2()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { public void F() { } }", encoding: Encoding.Unicode, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { public void F() { } }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree("class C { public void F() { } }", encoding: new UTF8Encoding(true, false), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class D { public void F() { } }", new UTF8Encoding(false, false)), path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify();
Assert.True(result.Success);
var hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray();
var hash3 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(true, false).GetBytesWithPreamble(tree3.ToString())).ToArray();
var hash4 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(false, false).GetBytesWithPreamble(tree4.ToString())).ToArray();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""Foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash1) + @""" />
<file id=""2"" name="""" language=""C#"" />
<file id=""3"" name=""Bar.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash3) + @""" />
<file id=""4"" name=""Baz.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash4) + @""" />
</files>
</symbols>", options: PdbValidationOptions.ExcludeMethods);
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(WindowsOnly))]
public void RelativePathForExternalSource_Sha1_Windows()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""..\Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""..\Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"C:\Folder1\Folder2\Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""C:\Folder1\Folder2\Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""40-A6-20-02-2E-60-7D-4F-2D-A8-F4-A6-ED-2E-0E-49-8D-9F-D7-EB"" />
<file id=""2"" name=""C:\Folder1\Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(UnixLikeOnly))]
public void RelativePathForExternalSource_Sha1_Unix()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""../Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""../Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"/Folder1/Folder2/Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""/Folder1/Folder2/Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""82-08-07-BA-BA-52-02-D8-1D-1F-7C-E7-95-8A-6C-04-64-FF-50-31"" />
<file id=""2"" name=""/Folder1/Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors2()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'The version of Windows PDB writer is older than required: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterOlderVersionThanRequired, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors3()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll.WithDeterministic(true));
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Windows PDB writer doesn't support deterministic compilation: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterNotDeterministic, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors4()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => throw new DllNotFoundException("xxx") });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'xxx'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("xxx"));
Assert.False(result.Success);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressDynamicAndEncCDIForWinRT()
{
var source = @"
public class C
{
public static void F()
{
dynamic a = 1;
int b = 2;
foreach (var x in new[] { 1,2,3 })
{
System.Console.WriteLine(a * b);
}
}
}
";
var debug = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugWinMD);
debug.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0xb"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xe6"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xe7"" hidden=""true"" document=""1"" />
<entry offset=""0xeb"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xf4"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xf5"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<scope startOffset=""0x24"" endOffset=""0xe7"">
<local name=""x"" il_index=""4"" il_start=""0x24"" il_end=""0xe7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x9"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x26"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xdd"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xea"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xeb"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressTupleElementNamesCDIForWinRT()
{
var source =
@"class C
{
static void F()
{
(int A, int B) o = (1, 2);
}
}";
var debug = CreateCompilation(source, options: TestOptions.DebugWinMD);
debug.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""35"" document=""1"" />
<entry offset=""0x9"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void DuplicateDocuments()
{
var source1 = @"class C { static void F() { } }";
var source2 = @"class D { static void F() { } }";
var tree1 = Parse(source1, @"foo.cs");
var tree2 = Parse(source2, @"foo.cs");
var comp = CreateCompilation(new[] { tree1, tree2 });
// the first file wins (checksum CB 22 ...)
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""CB-22-D8-03-D3-27-32-64-2C-BC-7D-67-5D-E3-CB-AC-D1-64-25-83"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""D"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void CustomDebugEntryPoint_DLL()
{
var source = @"class C { static void F() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
Assert.Equal(0, peEntryPointToken);
}
[Fact]
public void CustomDebugEntryPoint_EXE()
{
var source = @"class M { static void Main() { } } class C { static void F<S>() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugExe);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
var mdReader = peReader.GetMetadataReader();
var methodDef = mdReader.GetMethodDefinition((MethodDefinitionHandle)MetadataTokens.Handle(peEntryPointToken));
Assert.Equal("Main", mdReader.GetString(methodDef.Name));
}
[Fact]
public void CustomDebugEntryPoint_Errors()
{
var source1 = @"class C { static void F() { } } class D<T> { static void G<S>() {} }";
var source2 = @"class C { static void F() { } }";
var c1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var c2 = CreateCompilation(source2, options: TestOptions.DebugDll);
var f1 = c1.GetMember<MethodSymbol>("C.F");
var f2 = c2.GetMember<MethodSymbol>("C.F");
var g = c1.GetMember<MethodSymbol>("D.G");
var d = c1.GetMember<NamedTypeSymbol>("D");
Assert.NotNull(f1);
Assert.NotNull(f2);
Assert.NotNull(g);
Assert.NotNull(d);
var stInt = c1.GetSpecialType(SpecialType.System_Int32);
var d_t_g_int = g.Construct(stInt);
var d_int = d.Construct(stInt);
var d_int_g = d_int.GetMember<MethodSymbol>("G");
var d_int_g_int = d_int_g.Construct(stInt);
var result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: f2.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_t_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
}
[Fact]
[WorkItem(768862, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/768862")]
public void TestLargeLineDelta()
{
var verbatim = string.Join("\r\n", Enumerable.Repeat("x", 1000));
var source = $@"
class C {{ public static void Main() => System.Console.WriteLine(@""{verbatim}""); }}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""2"" startColumn=""40"" endLine=""1001"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.PortablePdb);
// Native PDBs only support spans with line delta <= 127 (7 bit)
// https://github.com/Microsoft/microsoft-pdb/blob/main/include/cvinfo.h#L4621
c.VerifyPdb("C.Main", @"
<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=""2"" startColumn=""40"" endLine=""129"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_SameLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""5"" startColumn=""65533"" endLine=""5"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_DifferentLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(
""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""5"" startColumn=""65534"" endLine=""6"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
#endregion
#region Method Bodies
[Fact]
public void TestBasic()
{
var source = WithWindowsLineBreaks(@"
class Program
{
Program() { }
static void Main(string[] args)
{
Program p = new Program();
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Program"" methodName="".ctor"" />
<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=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""p"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSimpleLocals()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{ //local at method scope
object version = 6;
System.Console.WriteLine(""version {0}"", version);
{
//a scope that defines no locals
{
//a nested local
object foob = 1;
System.Console.WriteLine(""foob {0}"", foob);
}
{
//a nested local
int foob1 = 1;
System.Console.WriteLine(""foob1 {0}"", foob1);
}
System.Console.WriteLine(""Eva"");
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""44"" />
<slot kind=""0"" offset=""246"" />
<slot kind=""0"" offset=""402"" />
</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=""28"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""58"" document=""1"" />
<entry offset=""0x14"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""12"" startColumn=""17"" endLine=""12"" endColumn=""33"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""60"" document=""1"" />
<entry offset=""0x29"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x2a"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""17"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""62"" document=""1"" />
<entry offset=""0x3e"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x3f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x4a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x4b"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4c"">
<local name=""version"" il_index=""0"" il_start=""0x0"" il_end=""0x4c"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x2a"">
<local name=""foob"" il_index=""1"" il_start=""0x15"" il_end=""0x2a"" attributes=""0"" />
</scope>
<scope startOffset=""0x2a"" endOffset=""0x3f"">
<local name=""foob1"" il_index=""2"" il_start=""0x2a"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
public void ConstructorsWithoutInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<scope startOffset=""0x7"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""1"" />
<entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<scope startOffset=""0x7"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x7"" il_end=""0xb"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
[Fact]
public void ConstructorsWithInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
static object G = 1;
object F = G;
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x12"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<scope startOffset=""0x12"" endOffset=""0x14"">
<local name=""o"" il_index=""0"" il_start=""0x12"" il_end=""0x14"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""16"" document=""1"" />
<entry offset=""0x12"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<scope startOffset=""0x12"" endOffset=""0x16"">
<local name=""y"" il_index=""0"" il_start=""0x12"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Although the debugging info attached to DebuggerHidden method is not used by the debugger
/// (the debugger doesn't ever stop in the method) Dev11 emits the info and so do we.
///
/// StepThrough method needs the information if JustMyCode is disabled and a breakpoint is set within the method.
/// NonUserCode method needs the information if JustMyCode is disabled.
///
/// It's up to the tool that consumes the debugging information, not the compiler to decide whether to ignore the info or not.
/// BTW, the information can actually be retrieved at runtime from the PDB file via Reflection StackTrace.
/// </summary>
[Fact]
public void MethodsWithDebuggerAttributes()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.Diagnostics;
class Program
{
[DebuggerHidden]
static void Hidden()
{
int x = 1;
Console.WriteLine(x);
}
[DebuggerStepThrough]
static void StepThrough()
{
int y = 1;
Console.WriteLine(y);
}
[DebuggerNonUserCode]
static void NonUserCode()
{
int z = 1;
Console.WriteLine(z);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Hidden"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<namespace name=""System"" />
<namespace name=""System.Diagnostics"" />
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""StepThrough"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""NonUserCode"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
/// <summary>
/// If a synthesized method contains any user code,
/// the method must have a sequence point at
/// offset 0 for correct stepping behavior.
/// </summary>
[WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")]
[Fact]
public void SequencePointAtOffset0()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static Func<object, int> F = x =>
{
Func<object, int> f = o => 1;
Func<Func<object, int>, Func<object, int>> g = h => y => h(y);
return g(f)(null);
};
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-45"" />
<lambda offset=""-147"" />
<lambda offset=""-109"" />
<lambda offset=""-45"" />
<lambda offset=""-40"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""9"" endColumn=""7"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.cctor>b__3"" parameterNames=""y"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""66"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""-118"" />
<slot kind=""0"" offset=""-54"" />
<slot kind=""21"" offset=""-147"" />
</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=""38"" document=""1"" />
<entry offset=""0x21"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""71"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x51"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x53"">
<local name=""f"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
<local name=""g"" il_index=""1"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
</scope>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_1"" parameterNames=""o"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""36"" endLine=""6"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_2"" parameterNames=""h"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-45"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""7"" startColumn=""61"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading trivia is not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Methods()
{
string source = @"
class C
{
public static void Main1() /*Comment1*/{/*Comment2*/int a = 1;/*Comment3*/}/*Comment4*/
public static void Main2() {/*Comment2*/int a = 2;/*Comment3*/}/*Comment4*/
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that both syntax offsets are the same
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main1"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""44"" endLine=""4"" endColumn=""45"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""57"" endLine=""4"" endColumn=""67"" document=""1"" />
<entry offset=""0x3"" startLine=""4"" startColumn=""79"" endLine=""4"" endColumn=""80"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
<method containingType=""C"" name=""Main2"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""33"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""45"" endLine=""5"" endColumn=""55"" document=""1"" />
<entry offset=""0x3"" startLine=""5"" startColumn=""67"" endLine=""5"" endColumn=""68"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading and trailing trivia are not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Initializers()
{
string source = @"
using System;
class C1
{
public static Func<int> e=() => 0;
public static Func<int> f/*Comment0*/=/*Comment1*/() => 1;/*Comment2*/
public static Func<int> g=() => 2;
}
class C2
{
public static Func<int> e=() => 0;
public static Func<int> f=/*Comment1*/() => 1;
public static Func<int> g=() => 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that syntax offsets of both .cctor's are the same
c.VerifyPdb("C1..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C1"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""63"" document=""1"" />
<entry offset=""0x2a"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""39"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
c.VerifyPdb("C2..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C2"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""C1"" methodName="".cctor"" />
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""51"" document=""1"" />
<entry offset=""0x2a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Method1()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static int Main()
{
return 1;
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("Program.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</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=""18"" document=""1"" />
<entry offset=""0x5"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Property1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static int P
{
get { return 1; }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("C.P.get", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "C.get_P");
v.VerifyPdb("C.get_P", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""14"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""15"" endLine=""6"" endColumn=""24"" document=""1"" />
<entry offset=""0x5"" startLine=""6"" startColumn=""25"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Void1()
{
var source = @"
class Program
{
static void Main()
{
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 4 (0x4)
.maxstack 0
-IL_0000: nop
-IL_0001: br.s IL_0003
-IL_0003: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_ExpressionBodied1()
{
var source = @"
class Program
{
static int Main() => 1;
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 2 (0x2)
.maxstack 1
-IL_0000: ldc.i4.1
IL_0001: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_FromExceptionHandler1()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
static int Main()
{
try
{
Console.WriteLine();
return 1;
}
catch (Exception)
{
return 2;
}
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: call ""void System.Console.WriteLine()""
IL_0007: nop
-IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: leave.s IL_0012
}
catch System.Exception
{
-IL_000c: pop
-IL_000d: nop
-IL_000e: ldc.i4.2
IL_000f: stloc.0
IL_0010: leave.s IL_0012
}
-IL_0012: ldloc.0
IL_0013: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</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=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""33"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""22"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region IfStatement
[Fact]
public void IfStatement()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{
bool b = true;
if (b)
{
string s = ""true"";
System.Console.WriteLine(s);
}
else
{
string s = ""false"";
int i = 1;
while (i < 100)
{
int j = i, k = 1;
System.Console.WriteLine(j);
i = j + k;
}
i = i + 1;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""1"" offset=""38"" />
<slot kind=""0"" offset=""76"" />
<slot kind=""0"" offset=""188"" />
<slot kind=""0"" offset=""218"" />
<slot kind=""0"" offset=""292"" />
<slot kind=""0"" offset=""299"" />
<slot kind=""1"" offset=""240"" />
</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=""23"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x9"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""32"" document=""1"" />
<entry offset=""0x20"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""23"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x2a"" startLine=""19"" startColumn=""28"" endLine=""19"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x35"" startLine=""21"" startColumn=""17"" endLine=""21"" endColumn=""27"" document=""1"" />
<entry offset=""0x3c"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""14"" document=""1"" />
<entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x49"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""23"" document=""1"" />
<entry offset=""0x4f"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x50"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<local name=""b"" il_index=""0"" il_start=""0x0"" il_end=""0x51"" attributes=""0"" />
<scope startOffset=""0x8"" endOffset=""0x17"">
<local name=""s"" il_index=""2"" il_start=""0x8"" il_end=""0x17"" attributes=""0"" />
</scope>
<scope startOffset=""0x19"" endOffset=""0x50"">
<local name=""s"" il_index=""3"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<local name=""i"" il_index=""4"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<scope startOffset=""0x25"" endOffset=""0x3d"">
<local name=""j"" il_index=""5"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
<local name=""k"" il_index=""6"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region WhileStatement
[WorkItem(538299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538299")]
[Fact]
public void WhileStatement()
{
var source = @"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
while (p > 0) // SeqPt should be generated at the end of loop
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
int x = p;
field = x;
}
else
{
int x = p;
Console.WriteLine(x);
break;
}
}
field = -1;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Offset 0x01 should be:
// <entry offset=""0x1"" hidden=""true"" document=""1"" />
// Move original offset 0x01 to 0x33
// <entry offset=""0x33"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
//
// Note: 16707566 == 0x00FEEFEE
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""SeqPointForWhile"" methodName=""Main"" />
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0xf"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x10"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xc"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x13"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""27"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""27"" document=""1"" />
<entry offset=""0x1d"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""38"" document=""1"" />
<entry offset=""0x22"" startLine=""31"" startColumn=""17"" endLine=""31"" endColumn=""23"" document=""1"" />
<entry offset=""0x24"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
<entry offset=""0x28"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""20"" document=""1"" />
<entry offset=""0x2f"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x30"">
<scope startOffset=""0x11"" endOffset=""0x1a"">
<local name=""x"" il_index=""0"" il_start=""0x11"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForStatement
[Fact]
public void ForStatement1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static bool F(int i) { return true; }
static void G(int i) { }
static void M()
{
for (int i = 1; F(i); G(i))
{
System.Console.WriteLine(1);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""i"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" 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=""11"" startColumn=""13"" endLine=""11"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""9"" startColumn=""31"" endLine=""9"" endColumn=""35"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x20"">
<scope startOffset=""0x1"" endOffset=""0x1f"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x1f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForStatement2()
{
var source = @"
class C
{
static void M()
{
for (;;)
{
System.Console.WriteLine(1);
}
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForStatement3()
{
var source = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int i = 0;
for (;;i++)
{
System.Console.WriteLine(i);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</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=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x6"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForEachStatement
[Fact]
public void ForEachStatement_String()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var c in ""hello"")
{
System.Console.WriteLine(c);
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) '"hello"'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""34"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x23"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForEachStatement_Array()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static void Main()
{
foreach (var x in new int[2])
{
System.Console.WriteLine(x);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
</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=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""37"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x19"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""x"" il_index=""2"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArray()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new int[2, 3])
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2, 3]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 88 (0x58)
.maxstack 3
.locals init (int[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4,
int V_5) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: ldc.i4.2
IL_0003: ldc.i4.3
IL_0004: newobj ""int[*,*]..ctor""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.0
IL_000c: callvirt ""int System.Array.GetUpperBound(int)""
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldc.i4.1
IL_0014: callvirt ""int System.Array.GetUpperBound(int)""
IL_0019: stloc.2
IL_001a: ldloc.0
IL_001b: ldc.i4.0
IL_001c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0021: stloc.3
~IL_0022: br.s IL_0053
IL_0024: ldloc.0
IL_0025: ldc.i4.1
IL_0026: callvirt ""int System.Array.GetLowerBound(int)""
IL_002b: stloc.s V_4
~IL_002d: br.s IL_004a
-IL_002f: ldloc.0
IL_0030: ldloc.3
IL_0031: ldloc.s V_4
IL_0033: call ""int[*,*].Get""
IL_0038: stloc.s V_5
-IL_003a: nop
-IL_003b: ldloc.s V_5
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldloc.s V_4
IL_0046: ldc.i4.1
IL_0047: add
IL_0048: stloc.s V_4
-IL_004a: ldloc.s V_4
IL_004c: ldloc.2
IL_004d: ble.s IL_002f
~IL_004f: ldloc.3
IL_0050: ldc.i4.1
IL_0051: add
IL_0052: stloc.3
-IL_0053: ldloc.3
IL_0054: ldloc.1
IL_0055: ble.s IL_0024
-IL_0057: ret
}
", sequencePoints: "C.Main");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: <hidden>
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x51"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" 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=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x24"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalBeforeLocalFunction()
{
var source = @"
class C
{
void M()
{
int i = 0;
if (i != 0)
{
return;
}
string local()
{
throw null;
}
System.Console.Write(1);
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_000e
// sequence point: {
IL_000b: nop
// sequence point: return;
IL_000c: br.s IL_0016
// sequence point: <hidden>
IL_000e: nop
// sequence point: System.Console.Write(1);
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: nop
// sequence point: }
IL_0016: ret
}
", sequencePoints: "C.M", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethodWithExplicitReturn()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: return;
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInSimpleMethod()
{
var source = @"
using System;
class Program
{
public static void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_0011
// sequence point: Console.WriteLine();
IL_000b: call ""void System.Console.WriteLine()""
IL_0010: nop
// sequence point: }
IL_0011: ret
}
", sequencePoints: "Program.Test", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ElseConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine(""one"");
else
Console.WriteLine(""other"");
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0029
// sequence point: Console.WriteLine(""one"");
IL_001c: ldstr ""one""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: nop
// sequence point: <hidden>
IL_0027: br.s IL_0034
// sequence point: Console.WriteLine(""other"");
IL_0029: ldstr ""other""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: nop
// sequence point: <hidden>
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.2
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.2
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x63"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" 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=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""38"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""40"" document=""1"" />
<entry offset=""0x34"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x63"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x36"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInTry()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static void Test()
{
try
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
catch { }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
.try
{
// sequence point: {
IL_0001: nop
// sequence point: int i = 0;
IL_0002: ldc.i4.0
IL_0003: stloc.0
// sequence point: if (i != 0)
IL_0004: ldloc.0
IL_0005: ldc.i4.0
IL_0006: cgt.un
IL_0008: stloc.1
// sequence point: <hidden>
IL_0009: ldloc.1
IL_000a: brfalse.s IL_0012
// sequence point: Console.WriteLine();
IL_000c: call ""void System.Console.WriteLine()""
IL_0011: nop
// sequence point: }
IL_0012: nop
IL_0013: leave.s IL_001a
}
catch object
{
// sequence point: catch
IL_0015: pop
// sequence point: {
IL_0016: nop
// sequence point: }
IL_0017: nop
IL_0018: leave.s IL_001a
}
// sequence point: }
IL_001a: ret
}
", sequencePoints: "Program.Test", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""43"" />
<slot kind=""1"" offset=""65"" />
</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=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x4"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""37"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""15"" startColumn=""15"" endLine=""15"" endColumn=""16"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""17"" endLine=""15"" endColumn=""18"" document=""1"" />
<entry offset=""0x1a"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x13"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x13"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArrayBreakAndContinue()
{
var source = @"
using System;
class C
{
static void Main()
{
int[, ,] array = new[,,]
{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} },
};
foreach (int i in array)
{
if (i % 2 == 1) continue;
if (i > 4) break;
Console.WriteLine(i);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithModuleName("MODULE"));
// Stepping:
// After "continue", step to "in".
// After "break", step to first sequence point following loop body (in this case, method close brace).
v.VerifyIL("C.Main", @"
{
// Code size 169 (0xa9)
.maxstack 4
.locals init (int[,,] V_0, //array
int[,,] V_1,
int V_2,
int V_3,
int V_4,
int V_5,
int V_6,
int V_7,
int V_8, //i
bool V_9,
bool V_10)
-IL_0000: nop
-IL_0001: ldc.i4.2
IL_0002: ldc.i4.2
IL_0003: ldc.i4.2
IL_0004: newobj ""int[*,*,*]..ctor""
IL_0009: dup
IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>.8B4B2444E57AED8C2D05A1293255DA1B048C63224317D4666230760935FA4A18""
IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ldc.i4.0
IL_001a: callvirt ""int System.Array.GetUpperBound(int)""
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: callvirt ""int System.Array.GetUpperBound(int)""
IL_0027: stloc.3
IL_0028: ldloc.1
IL_0029: ldc.i4.2
IL_002a: callvirt ""int System.Array.GetUpperBound(int)""
IL_002f: stloc.s V_4
IL_0031: ldloc.1
IL_0032: ldc.i4.0
IL_0033: callvirt ""int System.Array.GetLowerBound(int)""
IL_0038: stloc.s V_5
~IL_003a: br.s IL_00a3
IL_003c: ldloc.1
IL_003d: ldc.i4.1
IL_003e: callvirt ""int System.Array.GetLowerBound(int)""
IL_0043: stloc.s V_6
~IL_0045: br.s IL_0098
IL_0047: ldloc.1
IL_0048: ldc.i4.2
IL_0049: callvirt ""int System.Array.GetLowerBound(int)""
IL_004e: stloc.s V_7
~IL_0050: br.s IL_008c
-IL_0052: ldloc.1
IL_0053: ldloc.s V_5
IL_0055: ldloc.s V_6
IL_0057: ldloc.s V_7
IL_0059: call ""int[*,*,*].Get""
IL_005e: stloc.s V_8
-IL_0060: nop
-IL_0061: ldloc.s V_8
IL_0063: ldc.i4.2
IL_0064: rem
IL_0065: ldc.i4.1
IL_0066: ceq
IL_0068: stloc.s V_9
~IL_006a: ldloc.s V_9
IL_006c: brfalse.s IL_0070
-IL_006e: br.s IL_0086
-IL_0070: ldloc.s V_8
IL_0072: ldc.i4.4
IL_0073: cgt
IL_0075: stloc.s V_10
~IL_0077: ldloc.s V_10
IL_0079: brfalse.s IL_007d
-IL_007b: br.s IL_00a8
-IL_007d: ldloc.s V_8
IL_007f: call ""void System.Console.WriteLine(int)""
IL_0084: nop
-IL_0085: nop
~IL_0086: ldloc.s V_7
IL_0088: ldc.i4.1
IL_0089: add
IL_008a: stloc.s V_7
-IL_008c: ldloc.s V_7
IL_008e: ldloc.s V_4
IL_0090: ble.s IL_0052
~IL_0092: ldloc.s V_6
IL_0094: ldc.i4.1
IL_0095: add
IL_0096: stloc.s V_6
-IL_0098: ldloc.s V_6
IL_009a: ldloc.3
IL_009b: ble.s IL_0047
~IL_009d: ldloc.s V_5
IL_009f: ldc.i4.1
IL_00a0: add
IL_00a1: stloc.s V_5
-IL_00a3: ldloc.s V_5
IL_00a5: ldloc.2
IL_00a6: ble.s IL_003c
-IL_00a8: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void ForEachStatement_Enumerator()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new System.Collections.Generic.List<int>())
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new System.Collections.Generic.List<int>()'
// 4) Hidden initial jump (of while loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) hidden point in Finally
// 11) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 59 (0x3b)
.maxstack 1
.locals init (System.Collections.Generic.List<int>.Enumerator V_0,
int V_1) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_0007: call ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()""
IL_000c: stloc.0
.try
{
~IL_000d: br.s IL_0020
-IL_000f: ldloca.s V_0
IL_0011: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get""
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: nop
-IL_001f: nop
-IL_0020: ldloca.s V_0
IL_0022: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()""
IL_0027: brtrue.s IL_000f
IL_0029: leave.s IL_003a
}
finally
{
~IL_002b: ldloca.s V_0
IL_002d: constrained. ""System.Collections.Generic.List<int>.Enumerator""
IL_0033: callvirt ""void System.IDisposable.Dispose()""
IL_0038: nop
IL_0039: endfinally
}
-IL_003a: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(718501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718501")]
[Fact]
public void ForEachNops()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
foreach (var i in l.AsEnumerable())
{
switch (i.Count)
{
case 1:
break;
default:
if (i.Count != 0)
{
}
break;
}
}
}
}
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<encLocalSlotMap>
<slot kind=""5"" offset=""15"" />
<slot kind=""0"" offset=""15"" />
<slot kind=""35"" offset=""83"" />
<slot kind=""1"" offset=""83"" />
<slot kind=""1"" offset=""237"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""20"" document=""1"" />
<entry offset=""0x2"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""47"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""12"" startColumn=""22"" endLine=""12"" endColumn=""27"" document=""1"" />
<entry offset=""0x1b"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""25"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""25"" endLine=""20"" endColumn=""42"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""21"" startColumn=""25"" endLine=""21"" endColumn=""26"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""25"" endLine=""22"" endColumn=""26"" document=""1"" />
<entry offset=""0x3e"" startLine=""24"" startColumn=""25"" endLine=""24"" endColumn=""31"" document=""1"" />
<entry offset=""0x40"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" document=""1"" />
<entry offset=""0x41"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x4b"" hidden=""true"" document=""1"" />
<entry offset=""0x55"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x57"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<namespace name=""System.Linq"" />
<scope startOffset=""0x14"" endOffset=""0x41"">
<local name=""i"" il_index=""1"" il_start=""0x14"" il_end=""0x41"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void ForEachStatement_Deconstruction()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void Main()
{
foreach (var (c, (d, e)) in F())
{
System.Console.WriteLine(c);
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //c
bool V_3, //d
double V_4, //e
System.ValueTuple<bool, double> V_5)
// sequence point: {
IL_0000: nop
// sequence point: foreach
IL_0001: nop
// sequence point: F()
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
// sequence point: <hidden>
IL_000a: br.s IL_003f
// sequence point: var (c, (d, e))
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
// sequence point: {
IL_0032: nop
// sequence point: System.Console.WriteLine(c);
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
// sequence point: }
IL_003a: nop
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
// sequence point: in
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
// sequence point: }
IL_0045: ret
}
", sequencePoints: "C.Main", source: source);
v.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""50"" endLine=""4"" endColumn=""76"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""25"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""32"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""40"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x32"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x3a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""34"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x45"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x46"">
<scope startOffset=""0xc"" endOffset=""0x3b"">
<local name=""c"" il_index=""2"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""d"" il_index=""3"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""e"" il_index=""4"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Switch
[Fact]
public void SwitchWithPattern_01()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static string Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""59"" />
<slot kind=""0"" offset=""163"" />
<slot kind=""0"" offset=""250"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x2e"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""57"" document=""1"" />
<entry offset=""0x4f"" hidden=""true"" document=""1"" />
<entry offset=""0x53"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""57"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x74"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""59"" document=""1"" />
<entry offset=""0x93"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""43"" document=""1"" />
<entry offset=""0xa7"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xaa"">
<scope startOffset=""0x1d"" endOffset=""0x4f"">
<local name=""s"" il_index=""0"" il_start=""0x1d"" il_end=""0x4f"" attributes=""0"" />
</scope>
<scope startOffset=""0x4f"" endOffset=""0x72"">
<local name=""s"" il_index=""1"" il_start=""0x4f"" il_end=""0x72"" attributes=""0"" />
</scope>
<scope startOffset=""0x72"" endOffset=""0x93"">
<local name=""t"" il_index=""2"" il_start=""0x72"" il_end=""0x93"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPattern_02()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return () => $""Teacher {t.Name} of {t.Subject}"";
default:
return () => $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""109"" closure=""1"" />
<lambda offset=""202"" closure=""1"" />
<lambda offset=""295"" closure=""1"" />
<lambda offset=""383"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x5f"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""63"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""63"" document=""1"" />
<entry offset=""0x8d"" hidden=""true"" document=""1"" />
<entry offset=""0x8f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""65"" document=""1"" />
<entry offset=""0x9f"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""49"" document=""1"" />
<entry offset=""0xaf"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb2"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb2"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xaf"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xaf"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPatternAndLocalFunctions()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
string f1() => $""Student {s.Name} ({s.GPA:N1})"";
return f1;
case Student s:
string f2() => $""Student {s.Name} ({s.GPA:N1})"";
return f2;
case Teacher t:
string f3() => $""Teacher {t.Name} of {t.Subject}"";
return f3;
default:
string f4() => $""Person {p.Name}"";
return f4;
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""111"" closure=""1"" />
<lambda offset=""234"" closure=""1"" />
<lambda offset=""357"" closure=""1"" />
<lambda offset=""475"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x60"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""27"" document=""1"" />
<entry offset=""0x8f"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""27"" document=""1"" />
<entry offset=""0xa2"" hidden=""true"" document=""1"" />
<entry offset=""0xa3"" startLine=""33"" startColumn=""17"" endLine=""33"" endColumn=""27"" document=""1"" />
<entry offset=""0xb3"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb6"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb6"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xb3"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xb3"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(17090, "https://github.com/dotnet/roslyn/issues/17090"), WorkItem(19731, "https://github.com/dotnet/roslyn/issues/19731")]
[Fact]
public void SwitchWithConstantPattern()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1();
M2();
}
static void M1()
{
switch
(1)
{
case 0 when true:
;
case 1:
Console.Write(1);
break;
case 2:
;
}
}
static void M2()
{
switch
(nameof(M2))
{
case nameof(M1) when true:
;
case nameof(M2):
Console.Write(nameof(M2));
break;
case nameof(Main):
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL(qualifiedMethodName: "Program.M1", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (int V_0,
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (1
IL_0001: ldc.i4.1
IL_0002: stloc.1
IL_0003: ldc.i4.1
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (string V_0,
string V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (nameof(M2)
IL_0001: ldstr ""M2""
IL_0006: stloc.1
IL_0007: ldstr ""M2""
IL_000c: stloc.0
// sequence point: <hidden>
IL_000d: br.s IL_000f
// sequence point: Console.Write(nameof(M2));
IL_000f: ldstr ""M2""
IL_0014: call ""void System.Console.Write(string)""
IL_0019: nop
// sequence point: break;
IL_001a: br.s IL_001c
// sequence point: }
IL_001c: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL("Program.M1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
verifier.VerifyIL("Program.M2",
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""M2""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_01()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1<int>(); // 1
M1<long>(); // 2
M2<string>(); // 3
M2<int>(); // 4
}
static void M1<T>()
{
switch (1)
{
case T t:
Console.Write(1);
break;
case int i:
Console.Write(2);
break;
}
}
static void M2<T>()
{
switch (nameof(M2))
{
case T t:
Console.Write(3);
break;
case string s:
Console.Write(4);
break;
case null:
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL(qualifiedMethodName: "Program.M1<T>", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 60 (0x3c)
.maxstack 1
.locals init (T V_0, //t
int V_1, //i
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (1)
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldc.i4.1
IL_0004: stloc.1
// sequence point: <hidden>
IL_0005: ldloc.1
IL_0006: box ""int""
IL_000b: isinst ""T""
IL_0010: brfalse.s IL_0030
IL_0012: ldloc.1
IL_0013: box ""int""
IL_0018: isinst ""T""
IL_001d: unbox.any ""T""
IL_0022: stloc.0
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: <hidden>
IL_0025: br.s IL_0027
// sequence point: Console.Write(1);
IL_0027: ldc.i4.1
IL_0028: call ""void System.Console.Write(int)""
IL_002d: nop
// sequence point: break;
IL_002e: br.s IL_003b
// sequence point: <hidden>
IL_0030: br.s IL_0032
// sequence point: Console.Write(2);
IL_0032: ldc.i4.2
IL_0033: call ""void System.Console.Write(int)""
IL_0038: nop
// sequence point: break;
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 58 (0x3a)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (nameof(M2))
IL_0001: ldstr ""M2""
IL_0006: stloc.2
IL_0007: ldstr ""M2""
IL_000c: stloc.1
// sequence point: <hidden>
IL_000d: ldloc.1
IL_000e: isinst ""T""
IL_0013: brfalse.s IL_002e
IL_0015: ldloc.1
IL_0016: isinst ""T""
IL_001b: unbox.any ""T""
IL_0020: stloc.0
// sequence point: <hidden>
IL_0021: br.s IL_0023
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: Console.Write(3);
IL_0025: ldc.i4.3
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: <hidden>
IL_002e: br.s IL_0030
// sequence point: Console.Write(4);
IL_0030: ldc.i4.4
IL_0031: call ""void System.Console.Write(int)""
IL_0036: nop
// sequence point: break;
IL_0037: br.s IL_0039
// sequence point: }
IL_0039: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL("Program.M1<T>",
@"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (int V_0) //i
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""int""
IL_0008: isinst ""T""
IL_000d: brfalse.s IL_0016
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldc.i4.2
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ret
}");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 28 (0x1c)
.maxstack 1
.locals init (string V_0) //s
IL_0000: ldstr ""M2""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: isinst ""T""
IL_000c: brfalse.s IL_0015
IL_000e: ldc.i4.3
IL_000f: call ""void System.Console.Write(int)""
IL_0014: ret
IL_0015: ldc.i4.4
IL_0016: call ""void System.Console.Write(int)""
IL_001b: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_02()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M2<string>(); // 6
M2<int>(); // 6
}
static void M2<T>()
{
const string x = null;
switch (x)
{
case T t:
;
case string s:
;
case null:
Console.Write(6);
break;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: switch (x)
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldnull
IL_0004: stloc.2
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(6);
IL_0007: ldc.i4.6
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.6
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
}
[Fact]
[WorkItem(31665, "https://github.com/dotnet/roslyn/issues/31665")]
public void TestSequencePoints_31665()
{
var source = @"
using System;
internal class Program
{
private static void Main(string[] args)
{
var s = ""1"";
if (true)
switch (s)
{
case ""1"":
Console.Out.WriteLine(""Input was 1"");
break;
default:
throw new Exception(""Default case"");
}
else
Console.Out.WriteLine(""Too many inputs"");
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main(string[])", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (string V_0, //s
bool V_1,
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: var s = ""1"";
IL_0001: ldstr ""1""
IL_0006: stloc.0
// sequence point: if (true)
IL_0007: ldc.i4.1
IL_0008: stloc.1
// sequence point: switch (s)
IL_0009: ldloc.0
IL_000a: stloc.3
// sequence point: <hidden>
IL_000b: ldloc.3
IL_000c: stloc.2
// sequence point: <hidden>
IL_000d: ldloc.2
IL_000e: ldstr ""1""
IL_0013: call ""bool string.op_Equality(string, string)""
IL_0018: brtrue.s IL_001c
IL_001a: br.s IL_002e
// sequence point: Console.Out.WriteLine(""Input was 1"");
IL_001c: call ""System.IO.TextWriter System.Console.Out.get""
IL_0021: ldstr ""Input was 1""
IL_0026: callvirt ""void System.IO.TextWriter.WriteLine(string)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: throw new Exception(""Default case"");
IL_002e: ldstr ""Default case""
IL_0033: newobj ""System.Exception..ctor(string)""
IL_0038: throw
// sequence point: <hidden>
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}
", sequencePoints: "Program.Main", source: source);
}
[Fact]
[WorkItem(17076, "https://github.com/dotnet/roslyn/issues/17076")]
public void TestSequencePoints_17076()
{
var source = @"
using System.Threading.Tasks;
internal class Program
{
private static void Main(string[] args)
{
M(new Node()).GetAwaiter().GetResult();
}
static async Task M(Node node)
{
while (node != null)
{
if (node is A a)
{
await Task.Yield();
return;
}
else if (node is B b)
{
await Task.Yield();
return;
}
node = node.Parent;
}
}
}
class Node
{
public Node Parent = null;
}
class A : Node { }
class B : Node { }
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 403 (0x193)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Program.<M>d__1 V_4,
bool V_5,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_6,
bool V_7,
System.Exception V_8)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<M>d__1.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_007e
IL_0014: br IL_0109
// sequence point: {
IL_0019: nop
// sequence point: <hidden>
IL_001a: br IL_0150
// sequence point: {
IL_001f: nop
// sequence point: if (node is A a)
IL_0020: ldarg.0
IL_0021: ldarg.0
IL_0022: ldfld ""Node Program.<M>d__1.node""
IL_0027: isinst ""A""
IL_002c: stfld ""A Program.<M>d__1.<a>5__1""
IL_0031: ldarg.0
IL_0032: ldfld ""A Program.<M>d__1.<a>5__1""
IL_0037: ldnull
IL_0038: cgt.un
IL_003a: stloc.1
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: brfalse.s IL_00a7
// sequence point: {
IL_003e: nop
// sequence point: await Task.Yield();
IL_003f: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0044: stloc.3
IL_0045: ldloca.s V_3
IL_0047: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_004c: stloc.2
// sequence point: <hidden>
IL_004d: ldloca.s V_2
IL_004f: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0054: brtrue.s IL_009a
IL_0056: ldarg.0
IL_0057: ldc.i4.0
IL_0058: dup
IL_0059: stloc.0
IL_005a: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_005f: ldarg.0
IL_0060: ldloc.2
IL_0061: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0066: ldarg.0
IL_0067: stloc.s V_4
IL_0069: ldarg.0
IL_006a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_006f: ldloca.s V_2
IL_0071: ldloca.s V_4
IL_0073: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0078: nop
IL_0079: leave IL_0192
// async: resume
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<M>d__1.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00a1: nop
// sequence point: return;
IL_00a2: leave IL_017e
// sequence point: if (node is B b)
IL_00a7: ldarg.0
IL_00a8: ldarg.0
IL_00a9: ldfld ""Node Program.<M>d__1.node""
IL_00ae: isinst ""B""
IL_00b3: stfld ""B Program.<M>d__1.<b>5__2""
IL_00b8: ldarg.0
IL_00b9: ldfld ""B Program.<M>d__1.<b>5__2""
IL_00be: ldnull
IL_00bf: cgt.un
IL_00c1: stloc.s V_5
// sequence point: <hidden>
IL_00c3: ldloc.s V_5
IL_00c5: brfalse.s IL_0130
// sequence point: {
IL_00c7: nop
// sequence point: await Task.Yield();
IL_00c8: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00cd: stloc.3
IL_00ce: ldloca.s V_3
IL_00d0: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00d5: stloc.s V_6
// sequence point: <hidden>
IL_00d7: ldloca.s V_6
IL_00d9: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00de: brtrue.s IL_0126
IL_00e0: ldarg.0
IL_00e1: ldc.i4.1
IL_00e2: dup
IL_00e3: stloc.0
IL_00e4: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_00e9: ldarg.0
IL_00ea: ldloc.s V_6
IL_00ec: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_00f1: ldarg.0
IL_00f2: stloc.s V_4
IL_00f4: ldarg.0
IL_00f5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_00fa: ldloca.s V_6
IL_00fc: ldloca.s V_4
IL_00fe: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0103: nop
IL_0104: leave IL_0192
// async: resume
IL_0109: ldarg.0
IL_010a: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_010f: stloc.s V_6
IL_0111: ldarg.0
IL_0112: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0117: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_011d: ldarg.0
IL_011e: ldc.i4.m1
IL_011f: dup
IL_0120: stloc.0
IL_0121: stfld ""int Program.<M>d__1.<>1__state""
IL_0126: ldloca.s V_6
IL_0128: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_012d: nop
// sequence point: return;
IL_012e: leave.s IL_017e
// sequence point: <hidden>
IL_0130: ldarg.0
IL_0131: ldnull
IL_0132: stfld ""B Program.<M>d__1.<b>5__2""
// sequence point: node = node.Parent;
IL_0137: ldarg.0
IL_0138: ldarg.0
IL_0139: ldfld ""Node Program.<M>d__1.node""
IL_013e: ldfld ""Node Node.Parent""
IL_0143: stfld ""Node Program.<M>d__1.node""
// sequence point: }
IL_0148: nop
IL_0149: ldarg.0
IL_014a: ldnull
IL_014b: stfld ""A Program.<M>d__1.<a>5__1""
// sequence point: while (node != null)
IL_0150: ldarg.0
IL_0151: ldfld ""Node Program.<M>d__1.node""
IL_0156: ldnull
IL_0157: cgt.un
IL_0159: stloc.s V_7
// sequence point: <hidden>
IL_015b: ldloc.s V_7
IL_015d: brtrue IL_001f
IL_0162: leave.s IL_017e
}
catch System.Exception
{
// sequence point: <hidden>
IL_0164: stloc.s V_8
IL_0166: ldarg.0
IL_0167: ldc.i4.s -2
IL_0169: stfld ""int Program.<M>d__1.<>1__state""
IL_016e: ldarg.0
IL_016f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_0174: ldloc.s V_8
IL_0176: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_017b: nop
IL_017c: leave.s IL_0192
}
// sequence point: }
IL_017e: ldarg.0
IL_017f: ldc.i4.s -2
IL_0181: stfld ""int Program.<M>d__1.<>1__state""
// sequence point: <hidden>
IL_0186: ldarg.0
IL_0187: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_018c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0191: nop
IL_0192: ret
}
", sequencePoints: "Program+<M>d__1.MoveNext", source: source);
}
[Fact]
[WorkItem(28288, "https://github.com/dotnet/roslyn/issues/28288")]
public void TestSequencePoints_28288()
{
var source = @"
using System.Threading.Tasks;
public class C
{
public static async Task Main()
{
object o = new C();
switch (o)
{
case C c:
System.Console.Write(1);
break;
default:
return;
}
if (M() != null)
{
}
}
private static object M()
{
return new C();
}
}";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 162 (0xa2)
.maxstack 2
.locals init (int V_0,
object V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: object o = new C();
IL_0008: ldarg.0
IL_0009: newobj ""C..ctor()""
IL_000e: stfld ""object C.<Main>d__0.<o>5__1""
// sequence point: switch (o)
IL_0013: ldarg.0
IL_0014: ldarg.0
IL_0015: ldfld ""object C.<Main>d__0.<o>5__1""
IL_001a: stloc.1
// sequence point: <hidden>
IL_001b: ldloc.1
IL_001c: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: <hidden>
IL_0021: ldarg.0
IL_0022: ldarg.0
IL_0023: ldfld ""object C.<Main>d__0.<>s__3""
IL_0028: isinst ""C""
IL_002d: stfld ""C C.<Main>d__0.<c>5__2""
IL_0032: ldarg.0
IL_0033: ldfld ""C C.<Main>d__0.<c>5__2""
IL_0038: brtrue.s IL_003c
IL_003a: br.s IL_0047
// sequence point: <hidden>
IL_003c: br.s IL_003e
// sequence point: System.Console.Write(1);
IL_003e: ldc.i4.1
IL_003f: call ""void System.Console.Write(int)""
IL_0044: nop
// sequence point: break;
IL_0045: br.s IL_0049
// sequence point: return;
IL_0047: leave.s IL_0086
// sequence point: <hidden>
IL_0049: ldarg.0
IL_004a: ldnull
IL_004b: stfld ""C C.<Main>d__0.<c>5__2""
IL_0050: ldarg.0
IL_0051: ldnull
IL_0052: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: if (M() != null)
IL_0057: call ""object C.M()""
IL_005c: ldnull
IL_005d: cgt.un
IL_005f: stloc.2
// sequence point: <hidden>
IL_0060: ldloc.2
IL_0061: brfalse.s IL_0065
// sequence point: {
IL_0063: nop
// sequence point: }
IL_0064: nop
// sequence point: <hidden>
IL_0065: leave.s IL_0086
}
catch System.Exception
{
// sequence point: <hidden>
IL_0067: stloc.3
IL_0068: ldarg.0
IL_0069: ldc.i4.s -2
IL_006b: stfld ""int C.<Main>d__0.<>1__state""
IL_0070: ldarg.0
IL_0071: ldnull
IL_0072: stfld ""object C.<Main>d__0.<o>5__1""
IL_0077: ldarg.0
IL_0078: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_007d: ldloc.3
IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0083: nop
IL_0084: leave.s IL_00a1
}
// sequence point: }
IL_0086: ldarg.0
IL_0087: ldc.i4.s -2
IL_0089: stfld ""int C.<Main>d__0.<>1__state""
// sequence point: <hidden>
IL_008e: ldarg.0
IL_008f: ldnull
IL_0090: stfld ""object C.<Main>d__0.<o>5__1""
IL_0095: ldarg.0
IL_0096: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a0: nop
IL_00a1: ret
}
", sequencePoints: "C+<Main>d__0.MoveNext", source: source);
}
[Fact]
public void SwitchExpressionWithPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
static string M(object o)
{
return o switch
{
int i => $""Number: {i}"",
_ => ""Don't know""
};
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""55"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x4"" startLine=""6"" startColumn=""18"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x2b"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x37"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3d"">
<scope startOffset=""0x16"" endOffset=""0x2b"">
<local name=""i"" il_index=""0"" il_start=""0x16"" il_end=""0x2b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region DoStatement
[Fact]
public void DoStatement()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
do
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
field = 1;
}
else
{
break;
}
} while (p > 0); // SeqPt should be generated for [while (p > 0);]
field = -1;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""28"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0x13"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""71"" />
<slot kind=""1"" offset=""159"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xd"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""26"" document=""1"" />
<entry offset=""0x13"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x24"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""14"" document=""1"" />
<entry offset=""0x28"" startLine=""28"" startColumn=""17"" endLine=""28"" endColumn=""23"" document=""1"" />
<entry offset=""0x2a"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" />
<entry offset=""0x2b"" startLine=""30"" startColumn=""11"" endLine=""30"" endColumn=""25"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""20"" document=""1"" />
<entry offset=""0x3a"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Constructor
[WorkItem(538317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538317")]
[Fact]
public void ConstructorSequencePoints1()
{
var source = WithWindowsLineBreaks(
@"namespace NS
{
public class MyClass
{
int intTest;
public MyClass()
{
intTest = 123;
}
public MyClass(params int[] values)
{
intTest = values[0] + values[1] + values[2];
}
public static int Main()
{
int intI = 1, intJ = 8;
int intK = 3;
// Can't step into Ctor
MyClass mc = new MyClass();
// Can't step into Ctor
mc = new MyClass(intI, intJ, intK);
return mc.intTest - 12;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Dev10 vs. Roslyn
//
// Default Ctor (no param)
// Dev10 Roslyn
// ======================================================================================
// Code size 18 (0x12) // Code size 16 (0x10)
// .maxstack 8 .maxstack 8
//* IL_0000: ldarg.0 *IL_0000: ldarg.0
// IL_0001: call IL_0001: callvirt
// instance void [mscorlib]System.Object::.ctor() instance void [mscorlib]System.Object::.ctor()
// IL_0006: nop *IL_0006: nop
//* IL_0007: nop
//* IL_0008: ldarg.0 *IL_0007: ldarg.0
// IL_0009: ldc.i4.s 123 IL_0008: ldc.i4.s 123
// IL_000b: stfld int32 NS.MyClass::intTest IL_000a: stfld int32 NS.MyClass::intTest
// IL_0010: nop
//* IL_0011: ret *IL_000f: ret
// -----------------------------------------------------------------------------------------
// SeqPoint: 0, 7 ,8, 0x10 0, 6, 7, 0xf
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""NS.MyClass"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""25"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name="".ctor"" parameterNames=""values"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""44"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""57"" document=""1"" />
<entry offset=""0x19"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name=""Main"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""56"" />
<slot kind=""0"" offset=""126"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""27"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0x5"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""40"" document=""1"" />
<entry offset=""0xd"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""48"" document=""1"" />
<entry offset=""0x25"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""36"" document=""1"" />
<entry offset=""0x32"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<local name=""intI"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intJ"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intK"" il_index=""2"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""mc"" il_index=""3"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ConstructorSequencePoints2()
{
TestSequencePoints(
@"using System;
class D
{
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class D
{
static D()
[|{|]
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D()
: [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class C { }
class D
{
[A]
[|public D()|]
{
}
}", TestOptions.DebugDll);
}
#endregion
#region Destructor
[Fact]
public void Destructors()
{
var source = @"
using System;
public class Base
{
~Base()
{
Console.WriteLine();
}
}
public class Derived : Base
{
~Derived()
{
Console.WriteLine();
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Base"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x13"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Derived"" name=""Finalize"">
<customDebugInfo>
<forward declaringType=""Base"" methodName=""Finalize"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Field and Property Initializers
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializers()
{
var text1 = WithWindowsLineBreaks(@"
public partial class C
{
int x = 1;
}
");
var text2 = WithWindowsLineBreaks(@"
public partial class C
{
int y = 1;
static void Main()
{
C c = new C();
}
}
");
// Having a unique name here may be important. The infrastructure of the pdb to xml conversion
// loads the assembly into the ReflectionOnlyLoadFrom context.
// So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new SyntaxTree[] { Parse(text1, "a.cs"), Parse(text2, "b.cs") });
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
<file id=""2"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializersWithLineDirectives()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int x = 1;
#line 12 ""foo.cs""
int z = Math.Abs(-3);
int w = Math.Abs(4);
#line 17 ""bar.cs""
double zed = Math.Sin(5);
}
#pragma checksum ""mah.cs"" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" ""ab007f1d23d9""
");
var text2 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int y = 1;
int x2 = 1;
#line 12 ""foo2.cs""
int z2 = Math.Abs(-3);
int w2 = Math.Abs(4);
}
");
var text3 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
#line 112 ""mah.cs""
int y3 = 1;
int x3 = 1;
int z3 = Math.Abs(-3);
#line default
int w3 = Math.Abs(4);
double zed3 = Math.Sin(5);
C() {
Console.WriteLine(""hi"");
}
static void Main()
{
C c = new C();
}
}
");
//Having a unique name here may be important. The infrastructure of the pdb to xml conversion
//loads the assembly into the ReflectionOnlyLoadFrom context.
//So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new[] { Parse(text1, "a.cs"), Parse(text2, "b.cs"), Parse(text3, "a.cs") }, options: TestOptions.DebugDll);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""E2-3B-47-02-DC-E4-8D-B4-FF-00-67-90-31-68-74-C0-06-D7-39-0E"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-CE-E5-E9-CB-53-E5-EF-C1-7F-2C-53-EC-02-FE-5C-34-2C-EF-94"" />
<file id=""3"" name=""foo.cs"" language=""C#"" />
<file id=""4"" name=""bar.cs"" language=""C#"" />
<file id=""5"" name=""foo2.cs"" language=""C#"" />
<file id=""6"" name=""mah.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""AB-00-7F-1D-23-D9"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""26"" document=""3"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""25"" document=""3"" />
<entry offset=""0x20"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""30"" document=""4"" />
<entry offset=""0x34"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""2"" />
<entry offset=""0x3b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""16"" document=""2"" />
<entry offset=""0x42"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""27"" document=""5"" />
<entry offset=""0x4f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""26"" document=""5"" />
<entry offset=""0x5b"" startLine=""112"" startColumn=""5"" endLine=""112"" endColumn=""16"" document=""6"" />
<entry offset=""0x62"" startLine=""113"" startColumn=""5"" endLine=""113"" endColumn=""16"" document=""6"" />
<entry offset=""0x69"" startLine=""114"" startColumn=""5"" endLine=""114"" endColumn=""27"" document=""6"" />
<entry offset=""0x76"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""26"" document=""1"" />
<entry offset=""0x82"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x96"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x9d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x9e"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0xa9"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(543313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543313")]
[Fact]
public void TestFieldInitializerExpressionLambda()
{
var source = @"
class C
{
int x = ((System.Func<int, int>)(z => z))(1);
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset=""-6"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""50"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__1_0"" parameterNames=""z"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""43"" endLine=""4"" endColumn=""44"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FieldInitializerSequencePointSpans()
{
var source = @"
class C
{
int x = 1, y = 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""14"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""16"" endLine=""4"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Auto-Property
[WorkItem(820806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820806")]
[Fact]
public void BreakpointForAutoImplementedProperty()
{
var source = @"
public class C
{
public static int AutoProp1 { get; private set; }
internal string AutoProp2 { get; set; }
internal protected C AutoProp3 { internal get; set; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_AutoProp1"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""35"" endLine=""4"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp1"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""40"" endLine=""4"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp2"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""33"" endLine=""5"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp2"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""38"" endLine=""5"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp3"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""38"" endLine=""6"" endColumn=""51"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp3"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""52"" endLine=""6"" endColumn=""56"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void PropertyDeclaration()
{
TestSequencePoints(
@"using System;
public class C
{
int P { [|get;|] set; }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; [|set;|] }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get [|{|] return 0; } }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; } = [|int.Parse(""42"")|];
}", TestOptions.DebugDll, TestOptions.Regular);
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Implicit()
{
var source = @"class C
{
static void Main()
{
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Explicit()
{
var source = @"class C
{
static void Main()
{
return;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(538298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538298")]
[Fact]
public void RegressSeqPtEndOfMethodAfterReturn()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointAfterReturn
{
public static int Main()
{
int ret = 0;
ReturnVoid(100);
if (field != ""Even"")
ret = 1;
ReturnVoid(99);
if (field != ""Odd"")
ret = ret + 1;
string rets = ReturnValue(101);
if (rets != ""Odd"")
ret = ret + 1;
rets = ReturnValue(102);
if (rets != ""Even"")
ret = ret + 1;
return ret;
}
static string field;
public static void ReturnVoid(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
field = ""Even"";
}
else
{
field = ""Odd"";
}
}
public static string ReturnValue(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
return ""Even"";
}
else
{
return ""Odd"";
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Expected are current actual output plus Two extra expected SeqPt:
// <entry offset=""0x73"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
// <entry offset=""0x22"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
//
// Note: NOT include other differences between Roslyn and Dev10, as they are filed in separated bugs
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointAfterReturn"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""204"" />
<slot kind=""1"" offset=""59"" />
<slot kind=""1"" offset=""138"" />
<slot kind=""1"" offset=""238"" />
<slot kind=""1"" offset=""330"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""21"" document=""1"" />
<entry offset=""0x20"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x28"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""28"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""27"" document=""1"" />
<entry offset=""0x3f"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""40"" document=""1"" />
<entry offset=""0x47"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""27"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x58"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""27"" document=""1"" />
<entry offset=""0x5c"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x64"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""28"" document=""1"" />
<entry offset=""0x71"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""27"" document=""1"" />
<entry offset=""0x79"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""20"" document=""1"" />
<entry offset=""0x7e"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x81"">
<namespace name=""System"" />
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
<local name=""rets"" il_index=""1"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnVoid"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""33"" startColumn=""13"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x18"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" />
<entry offset=""0x1c"" startLine=""37"" startColumn=""13"" endLine=""37"" endColumn=""27"" document=""1"" />
<entry offset=""0x26"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""39"" startColumn=""5"" endLine=""39"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnValue"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""42"" startColumn=""5"" endLine=""42"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""43"" startColumn=""9"" endLine=""43"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""45"" startColumn=""9"" endLine=""45"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""27"" document=""1"" />
<entry offset=""0x16"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""50"" startColumn=""13"" endLine=""50"" endColumn=""26"" document=""1"" />
<entry offset=""0x1f"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Exception Handling
[WorkItem(542064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542064")]
[Fact]
public void ExceptionHandling()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static int Main()
{
int ret = 0; // stop 1
try
{ // stop 2
throw new System.Exception(); // stop 3
}
catch (System.Exception e) // stop 4
{ // stop 5
ret = 1; // stop 6
}
try
{ // stop 7
throw new System.Exception(); // stop 8
}
catch // stop 9
{ // stop 10
return ret; // stop 11
}
}
}
");
// Dev12 inserts an additional sequence point on catch clause, just before
// the exception object is assigned to the variable. We don't place that sequence point.
// Also the scope of he exception variable is different.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""147"" />
<slot kind=""21"" offset=""0"" />
</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=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""42"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""35"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""42"" document=""1"" />
<entry offset=""0x19"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""24"" document=""1"" />
<entry offset=""0x1f"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<scope startOffset=""0xa"" endOffset=""0x11"">
<local name=""e"" il_index=""1"" il_start=""0xa"" il_end=""0x11"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug1()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class Test
{
static string filter(Exception e)
{
return null;
}
static void Main()
{
try
{
throw new InvalidOperationException();
}
catch (IOException e) when (filter(e) != null)
{
Console.WriteLine();
}
catch (Exception e) when (filter(e) != null)
{
Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0023
IL_0014: stloc.0
-IL_0015: ldloc.0
IL_0016: call ""string Test.filter(System.Exception)""
IL_001b: ldnull
IL_001c: cgt.un
IL_001e: stloc.1
~IL_001f: ldloc.1
IL_0020: ldc.i4.0
IL_0021: cgt.un
IL_0023: endfilter
} // end filter
{ // handler
~IL_0025: pop
-IL_0026: nop
-IL_0027: call ""void System.Console.WriteLine()""
IL_002c: nop
-IL_002d: nop
IL_002e: leave.s IL_0058
}
filter
{
~IL_0030: isinst ""System.Exception""
IL_0035: dup
IL_0036: brtrue.s IL_003c
IL_0038: pop
IL_0039: ldc.i4.0
IL_003a: br.s IL_004b
IL_003c: stloc.2
-IL_003d: ldloc.2
IL_003e: call ""string Test.filter(System.Exception)""
IL_0043: ldnull
IL_0044: cgt.un
IL_0046: stloc.3
~IL_0047: ldloc.3
IL_0048: ldc.i4.0
IL_0049: cgt.un
IL_004b: endfilter
} // end filter
{ // handler
~IL_004d: pop
-IL_004e: nop
-IL_004f: call ""void System.Console.WriteLine()""
IL_0054: nop
-IL_0055: nop
IL_0056: leave.s IL_0058
}
-IL_0058: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""filter"" parameterNames=""e"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""104"" />
<slot kind=""1"" offset=""120"" />
<slot kind=""0"" offset=""216"" />
<slot kind=""1"" offset=""230"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""51"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" startLine=""18"" startColumn=""31"" endLine=""18"" endColumn=""55"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""29"" endLine=""22"" endColumn=""53"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""10"" document=""1"" />
<entry offset=""0x4f"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""33"" document=""1"" />
<entry offset=""0x55"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x58"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x59"">
<scope startOffset=""0x8"" endOffset=""0x30"">
<local name=""e"" il_index=""0"" il_start=""0x8"" il_end=""0x30"" attributes=""0"" />
</scope>
<scope startOffset=""0x30"" endOffset=""0x58"">
<local name=""e"" il_index=""2"" il_start=""0x30"" il_end=""0x58"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug2()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static void Main()
{
try
{
throw new System.Exception();
}
catch when (F())
{
System.Console.WriteLine();
}
}
private static bool F()
{
return true;
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: call ""bool Test.F()""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""10"" startColumn=""15"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug3()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: ldsfld ""bool Test.a""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</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=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Release3()
{
var source = @"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll));
v.VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.try
{
-IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
filter
{
~IL_0006: pop
-IL_0007: ldsfld ""bool Test.a""
IL_000c: ldc.i4.0
IL_000d: cgt.un
IL_000f: endfilter
} // end filter
{ // handler
~IL_0011: pop
-IL_0012: call ""void System.Console.WriteLine()""
-IL_0017: leave.s IL_0019
}
-IL_0019: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x6"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(778655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778655")]
[Fact]
public void BranchToStartOfTry()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string str = null;
bool isEmpty = string.IsNullOrEmpty(str);
// isEmpty is always true here, so it should never go thru this if statement.
if (!isEmpty)
{
throw new Exception();
}
try
{
Console.WriteLine();
}
catch
{
}
}
}
");
// Note the hidden sequence point @IL_0019.
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=""18"" />
<slot kind=""0"" offset=""44"" />
<slot kind=""1"" offset=""177"" />
</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=""27"" document=""1"" />
<entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""50"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""22"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""35"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""33"" document=""1"" />
<entry offset=""0x21"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x24"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x29"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""str"" il_index=""0"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
<local name=""isEmpty"" il_index=""1"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region UsingStatement
[Fact]
public void UsingStatement_EmbeddedStatement()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass a = new DisposableClass(1), b = new DisposableClass(2))
System.Console.WriteLine(""First"");
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 53 (0x35)
.maxstack 1
.locals init (DisposableClass V_0, //a
DisposableClass V_1) //b
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass a = new DisposableClass(1)
IL_0001: ldc.i4.1
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: b = new DisposableClass(2)
IL_0008: ldc.i4.2
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: System.Console.WriteLine(""First"");
IL_000f: ldstr ""First""
IL_0014: call ""void System.Console.WriteLine(string)""
IL_0019: nop
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.1
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: <hidden>
IL_0027: leave.s IL_0034
}
finally
{
// sequence point: <hidden>
IL_0029: ldloc.0
IL_002a: brfalse.s IL_0033
IL_002c: ldloc.0
IL_002d: callvirt ""void System.IDisposable.Dispose()""
IL_0032: nop
// sequence point: <hidden>
IL_0033: endfinally
}
// sequence point: }
IL_0034: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""47"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<scope startOffset=""0x1"" endOffset=""0x34"">
<local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UsingStatement_Block()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass c = new DisposableClass(3), d = new DisposableClass(4))
{
System.Console.WriteLine(""Second"");
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 55 (0x37)
.maxstack 1
.locals init (DisposableClass V_0, //c
DisposableClass V_1) //d
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass c = new DisposableClass(3)
IL_0001: ldc.i4.3
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: d = new DisposableClass(4)
IL_0008: ldc.i4.4
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: {
IL_000f: nop
// sequence point: System.Console.WriteLine(""Second"");
IL_0010: ldstr ""Second""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: nop
// sequence point: }
IL_001b: nop
IL_001c: leave.s IL_0029
}
finally
{
// sequence point: <hidden>
IL_001e: ldloc.1
IL_001f: brfalse.s IL_0028
IL_0021: ldloc.1
IL_0022: callvirt ""void System.IDisposable.Dispose()""
IL_0027: nop
// sequence point: <hidden>
IL_0028: endfinally
}
// sequence point: <hidden>
IL_0029: leave.s IL_0036
}
finally
{
// sequence point: <hidden>
IL_002b: ldloc.0
IL_002c: brfalse.s IL_0035
IL_002e: ldloc.0
IL_002f: callvirt ""void System.IDisposable.Dispose()""
IL_0034: nop
// sequence point: <hidden>
IL_0035: endfinally
}
// sequence point: }
IL_0036: ret
}
"
);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x10"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""48"" document=""1"" />
<entry offset=""0x1b"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x28"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<scope startOffset=""0x1"" endOffset=""0x36"">
<local name=""c"" il_index=""0"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
<local name=""d"" il_index=""1"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
value = false;
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_0018
// sequence point: value = false;
IL_0016: ldc.i4.0
IL_0017: stloc.1
// sequence point: <hidden>
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.2
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.2
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: return value;
IL_0025: ldloc.1
IL_0026: stloc.s V_4
IL_0028: br.s IL_002a
// sequence point: }
IL_002a: ldloc.s V_4
IL_002c: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional2()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
{
value = false;
}
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 47 (0x2f)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_001a
// sequence point: {
IL_0016: nop
// sequence point: value = false;
IL_0017: ldc.i4.0
IL_0018: stloc.1
// sequence point: }
IL_0019: nop
// sequence point: <hidden>
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.2
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.2
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: return value;
IL_0027: ldloc.1
IL_0028: stloc.s V_4
IL_002a: br.s IL_002c
// sequence point: }
IL_002c: ldloc.s V_4
IL_002e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedWhile()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
while (x)
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: while (x)
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedFor()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
for ( ; x == true; )
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: x == true
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void LockStatement_EmbeddedIf()
{
var source = @"
class C
{
void F(bool x)
{
string y = """";
lock (y)
if (!x)
System.Console.Write(1);
else
System.Console.Write(2);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (string V_0, //y
string V_1,
bool V_2,
bool V_3)
// sequence point: {
IL_0000: nop
// sequence point: string y = """";
IL_0001: ldstr """"
IL_0006: stloc.0
// sequence point: lock (y)
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldc.i4.0
IL_000a: stloc.2
.try
{
IL_000b: ldloc.1
IL_000c: ldloca.s V_2
IL_000e: call ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_0013: nop
// sequence point: if (!x)
IL_0014: ldarg.1
IL_0015: ldc.i4.0
IL_0016: ceq
IL_0018: stloc.3
// sequence point: <hidden>
IL_0019: ldloc.3
IL_001a: brfalse.s IL_0025
// sequence point: System.Console.Write(1);
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.Write(int)""
IL_0022: nop
// sequence point: <hidden>
IL_0023: br.s IL_002c
// sequence point: System.Console.Write(2);
IL_0025: ldc.i4.2
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: <hidden>
IL_002c: leave.s IL_0039
}
finally
{
// sequence point: <hidden>
IL_002e: ldloc.2
IL_002f: brfalse.s IL_0038
IL_0031: ldloc.1
IL_0032: call ""void System.Threading.Monitor.Exit(object)""
IL_0037: nop
// sequence point: <hidden>
IL_0038: endfinally
}
// sequence point: }
IL_0039: ret
}
", sequencePoints: "C.F", source: source);
}
#endregion
#region Using Declaration
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static void Main()
{
using MemoryStream m = new MemoryStream(), n = new MemoryStream();
Console.WriteLine(1);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
System.IO.MemoryStream V_1) //n
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: n = new MemoryStream()
IL_0007: newobj ""System.IO.MemoryStream..ctor()""
IL_000c: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_000d: ldc.i4.1
IL_000e: call ""void System.Console.WriteLine(int)""
IL_0013: nop
// sequence point: }
IL_0014: leave.s IL_002c
}
finally
{
// sequence point: <hidden>
IL_0016: ldloc.1
IL_0017: brfalse.s IL_0020
IL_0019: ldloc.1
IL_001a: callvirt ""void System.IDisposable.Dispose()""
IL_001f: nop
// sequence point: <hidden>
IL_0020: endfinally
}
}
finally
{
// sequence point: <hidden>
IL_0021: ldloc.0
IL_0022: brfalse.s IL_002b
IL_0024: ldloc.0
IL_0025: callvirt ""void System.IDisposable.Dispose()""
IL_002a: nop
// sequence point: <hidden>
IL_002b: endfinally
}
// sequence point: }
IL_002c: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""0"" offset=""54"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""50"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""52"" endLine=""8"" endColumn=""74"" document=""1"" />
<entry offset=""0xd"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x14"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x20"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
<local name=""n"" il_index=""1"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScopeWithReturn()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static int Main()
{
using MemoryStream m = new MemoryStream();
Console.WriteLine(1);
return 1;
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream();
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: Console.WriteLine(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: nop
// sequence point: return 1;
IL_000e: ldc.i4.1
IL_000f: stloc.1
IL_0010: leave.s IL_001d
}
finally
{
// sequence point: <hidden>
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001c
IL_0015: ldloc.0
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
// sequence point: <hidden>
IL_001c: endfinally
}
// sequence point: }
IL_001d: ldloc.1
IL_001e: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""51"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0xe"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""18"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1f"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_IfBodyScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
public static bool G() => true;
static void Main()
{
if (G())
{
using var m = new MemoryStream();
Console.WriteLine(1);
}
Console.WriteLine(2);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// In this case the sequence point `}` is not emitted on the leave instruction,
// but to a nop instruction following the disposal.
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init (bool V_0,
System.IO.MemoryStream V_1) //m
// sequence point: {
IL_0000: nop
// sequence point: if (G())
IL_0001: call ""bool C.G()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0026
// sequence point: {
IL_000a: nop
// sequence point: using var m = new MemoryStream();
IL_000b: newobj ""System.IO.MemoryStream..ctor()""
IL_0010: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_0011: ldc.i4.1
IL_0012: call ""void System.Console.WriteLine(int)""
IL_0017: nop
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.1
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.1
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: }
IL_0025: nop
// sequence point: Console.WriteLine(2);
IL_0026: ldc.i4.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
// sequence point: }
IL_002d: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""11"" />
<slot kind=""0"" offset=""55"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""17"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""46"" document=""1"" />
<entry offset=""0x11"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""30"" document=""1"" />
<entry offset=""0x2d"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<scope startOffset=""0xa"" endOffset=""0x26"">
<local name=""m"" il_index=""1"" il_start=""0xa"" il_end=""0x26"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
// LockStatement tested in CodeGenLock
#region Anonymous Type
[Fact]
public void AnonymousType_Empty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new {};
}
}
");
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=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</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=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void AnonymousType_NonEmpty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new { a = 1 };
}
}
");
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=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</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=""31"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region FixedStatement
[Fact]
public void FixedStatementSingleAddress()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""9"" offset=""47"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""11"" startColumn=""16"" endLine=""11"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""20"" document=""1"" />
<entry offset=""0x15"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""32"" document=""1"" />
<entry offset=""0x25"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x26"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x19"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x19"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleString()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""9"" offset=""24"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""35"" document=""1"" />
<entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x21"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x21"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleArray()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
(*p)++;
}
Console.Write(c.a[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""79"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""28"" document=""1"" />
<entry offset=""0x32"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x39"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""1"" />
<entry offset=""0x4a"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4b"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x3c"">
<local name=""p"" il_index=""1"" il_start=""0x15"" il_end=""0x3c"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleAddresses()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.WriteLine(c.x + c.y);
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""0"" offset=""57"" />
<slot kind=""9"" offset=""47"" />
<slot kind=""9"" offset=""57"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x21"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""20"" document=""1"" />
<entry offset=""0x24"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""38"" document=""1"" />
<entry offset=""0x3f"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x40"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x2c"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleStrings()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"", q = ""goodbye"")
{
Console.Write(*p);
Console.Write(*q);
}
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""9"" offset=""24"" />
<slot kind=""9"" offset=""37"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x1b"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""48"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""31"" document=""1"" />
<entry offset=""0x32"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x3f"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
<local name=""q"" il_index=""1"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleArrays()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
int[] b = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
Console.Write(c.b[0]);
fixed (int* p = c.a, q = c.b)
{
*p = 1;
*q = 2;
}
Console.Write(c.a[0]);
Console.Write(c.b[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""111"" />
<slot kind=""0"" offset=""120"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""31"" document=""1"" />
<entry offset=""0x23"" startLine=""14"" startColumn=""16"" endLine=""14"" endColumn=""28"" document=""1"" />
<entry offset=""0x40"" startLine=""14"" startColumn=""30"" endLine=""14"" endColumn=""37"" document=""1"" />
<entry offset=""0x60"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x61"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""20"" document=""1"" />
<entry offset=""0x64"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x67"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" />
<entry offset=""0x68"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""31"" document=""1"" />
<entry offset=""0x7b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""31"" document=""1"" />
<entry offset=""0x89"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8a"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x8a"" attributes=""0"" />
<scope startOffset=""0x23"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0xc"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleMixed()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""48"" />
<slot kind=""0"" offset=""58"" />
<slot kind=""0"" offset=""67"" />
<slot kind=""9"" offset=""48"" />
<slot kind=""temp"" />
<slot kind=""9"" offset=""67"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x13"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""41"" endLine=""12"" endColumn=""52"" document=""1"" />
<entry offset=""0x49"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x4a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""36"" document=""1"" />
<entry offset=""0x52"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""36"" document=""1"" />
<entry offset=""0x5a"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""36"" document=""1"" />
<entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x63"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6e"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x6e"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""r"" il_index=""3"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""18"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""28"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Line Directives
[Fact]
public void LineDirective()
{
var source = @"
#line 50 ""foo.cs""
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""57"" startColumn=""9"" endLine=""57"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")]
[Fact]
public void DisabledLineDirective()
{
var source = @"
#if false
#line 50 ""foo.cs""
#endif
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestLineDirectivesHidden()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public class C
{
public void Foo()
{
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line hidden
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line default
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
}
}
");
var compilation = CreateCompilation(text1, options: TestOptions.DebugDll);
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Foo"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""6"" offset=""137"" />
<slot kind=""8"" offset=""137"" />
<slot kind=""0"" offset=""137"" />
<slot kind=""6"" offset=""264"" />
<slot kind=""8"" offset=""264"" />
<slot kind=""0"" offset=""264"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""23"" document=""1"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""7"" startColumn=""24"" endLine=""7"" endColumn=""26"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""1"" />
<entry offset=""0x65"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""51"" document=""1"" />
<entry offset=""0x7b"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""1"" />
<entry offset=""0x84"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""1"" />
<entry offset=""0x85"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""34"" document=""1"" />
<entry offset=""0x8d"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x8e"" hidden=""true"" document=""1"" />
<entry offset=""0x94"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x9c"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9d"">
<namespace name=""System"" />
<scope startOffset=""0x18"" endOffset=""0x25"">
<local name=""x"" il_index=""2"" il_start=""0x18"" il_end=""0x25"" attributes=""0"" />
</scope>
<scope startOffset=""0x47"" endOffset=""0x57"">
<local name=""x"" il_index=""5"" il_start=""0x47"" il_end=""0x57"" attributes=""0"" />
</scope>
<scope startOffset=""0x7d"" endOffset=""0x8e"">
<local name=""x"" il_index=""8"" il_start=""0x7d"" il_end=""0x8e"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenMethods()
{
var src = WithWindowsLineBreaks(@"
using System;
class C
{
#line hidden
public static void H()
{
F();
}
#line default
public static void G()
{
F();
}
#line hidden
public static void F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""64"" />
<slot kind=""0"" offset=""158"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenEntryPoint()
{
var src = @"
class C
{
#line hidden
public static void Main()
{
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe);
// Note: Dev10 emitted a hidden sequence point to #line hidden method,
// which enabled the debugger to locate the first user visible sequence point starting from the entry point.
// Roslyn does not emit such sequence point. We could potentially synthesize one but that would defeat the purpose of
// #line hidden directive.
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"" format=""windows"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
</method>
</methods>
</symbols>",
// When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method
// and thus there is no entry point record either.
options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void HiddenIterator()
{
var src = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class C
{
public static void Main()
{
F();
}
#line hidden
public static IEnumerable<int> F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
yield return 1;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
// We don't really need the debug info for kickoff method when the entire iterator method is hidden,
// but it doesn't hurt and removing it would need extra effort that's unnecessary.
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</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=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forwardIterator name=""<F>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""64"" />
<slot kind=""0"" offset=""158"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Nested Types
[Fact]
public void NestedTypes()
{
string source = WithWindowsLineBreaks(@"
using System;
namespace N
{
public class C
{
public class D<T>
{
public class E
{
public static void f(int a)
{
Console.WriteLine();
}
}
}
}
}
");
var c = CreateCompilation(Parse(source, filename: "file.cs"));
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""file.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""F7-03-46-2C-11-16-DE-85-F9-DD-5C-76-F6-55-D9-13-E0-95-DE-14"" />
</files>
<methods>
<method containingType=""N.C+D`1+E"" name=""f"" parameterNames=""a"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""6"" endLine=""14"" endColumn=""26"" document=""1"" />
<entry offset=""0x5"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Expression Bodied Members
[Fact]
public void ExpressionBodiedProperty()
{
var source = WithWindowsLineBreaks(@"
class C
{
public int P => M();
public int M()
{
return 2;
}
}");
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""21"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedIndexer()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int this[Int32 i] => M();
public int M()
{
return 2;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_Item"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""36"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_Item"" parameterNames=""i"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedMethod()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public Int32 P => 2;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""23"" endLine=""6"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedOperator()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public static C operator ++(C c) => c;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Increment"" parameterNames=""c"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""41"" endLine=""4"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedConversion()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public static explicit operator C(Int32 i) => new C();
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Explicit"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""51"" endLine=""6"" endColumn=""58"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedConstructor()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int X;
public C(Int32 x) => X = x;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""22"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""26"" endLine=""7"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xe"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedDestructor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int X;
~C() => X = 0;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""13"" endLine=""5"" endColumn=""18"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedAccessor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int x;
public int X
{
get => x;
set => x = value;
}
public event System.Action E
{
add => x = 1;
remove => x = 0;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_X"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""17"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_X"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""25"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""add_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""remove_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Synthesized Methods
[Fact]
public void ImportsInLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
System.Action f = () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
f();
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""63"" />
</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=""30"" document=""1"" />
<entry offset=""0x39"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInIterator()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static IEnumerable<object> F()
{
var c = new[] { 1, 2, 3 };
foreach (var i in c.Select(i => i))
{
yield return i;
}
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x27"" endOffset=""0xd5"" />
<slot />
<slot startOffset=""0x7f"" endOffset=""0xb6"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x28"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x40"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""43"" document=""1"" />
<entry offset=""0x7d"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x90"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x91"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""28"" document=""1"" />
<entry offset=""0xad"" hidden=""true"" document=""1"" />
<entry offset=""0xb5"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb6"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xd1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
<entry offset=""0xd5"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInAsync()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task F()
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x1f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""F"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")]
[Fact]
public void ImportsInAsyncLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
class C
{
static void M()
{
System.Action f = async () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forwardIterator name=""<<M>b__0_0>d"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""69"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
c.VerifyPdb("C+<>c+<<M>b__0_0>d.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c+<<M>b__0_0>d"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""50"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""39"" document=""1"" />
<entry offset=""0x1f"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x4c"" />
<kickoffMethod declaringType=""C+<>c"" methodName=""<M>b__0_0"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Patterns
[Fact]
public void SyntaxOffset_IsPattern()
{
var source = @"class C { bool F(object o) => o is int i && o is 3 && o is bool; }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""12"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""31"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static int Main()
{
switch (F())
{
// declaration pattern
case int x when G(x) > 10: return 1;
// discard pattern
case bool _: return 2;
// var pattern
case var (y, z): return 3;
// constant pattern
case 4.0: return 4;
// positional patterns
case C() when B(): return 5;
case (): return 6;
case C(int p, C(int q)): return 7;
case C(x: int p): return 8;
// property pattern
case D { P: 1, Q: D { P: 2 }, R: C(int z) }: return 9;
default: return 10;
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 432 (0x1b0)
.maxstack 3
.locals init (int V_0, //x
object V_1, //y
object V_2, //z
int V_3, //p
int V_4, //q
int V_5, //p
int V_6, //z
object V_7,
System.Runtime.CompilerServices.ITuple V_8,
int V_9,
double V_10,
C V_11,
object V_12,
C V_13,
D V_14,
int V_15,
D V_16,
int V_17,
C V_18,
object V_19,
int V_20)
// sequence point: {
IL_0000: nop
// sequence point: switch (F())
IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_19
// sequence point: <hidden>
IL_0008: ldloc.s V_19
IL_000a: stloc.s V_7
// sequence point: <hidden>
IL_000c: ldloc.s V_7
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_7
IL_0017: unbox.any ""int""
IL_001c: stloc.0
// sequence point: <hidden>
IL_001d: br IL_014d
IL_0022: ldloc.s V_7
IL_0024: isinst ""bool""
IL_0029: brtrue IL_015e
IL_002e: ldloc.s V_7
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_8
IL_0037: ldloc.s V_8
IL_0039: brfalse.s IL_0080
IL_003b: ldloc.s V_8
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_9
// sequence point: <hidden>
IL_0044: ldloc.s V_9
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0060
IL_0049: ldloc.s V_8
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.1
// sequence point: <hidden>
IL_0052: ldloc.s V_8
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.2
// sequence point: <hidden>
IL_005b: br IL_0163
IL_0060: ldloc.s V_7
IL_0062: isinst ""C""
IL_0067: brtrue IL_016f
IL_006c: br.s IL_0077
IL_006e: ldloc.s V_9
IL_0070: brfalse IL_018c
IL_0075: br.s IL_00b5
IL_0077: ldloc.s V_9
IL_0079: brfalse IL_018c
IL_007e: br.s IL_00f5
IL_0080: ldloc.s V_7
IL_0082: isinst ""double""
IL_0087: brfalse.s IL_00a7
IL_0089: ldloc.s V_7
IL_008b: unbox.any ""double""
IL_0090: stloc.s V_10
// sequence point: <hidden>
IL_0092: ldloc.s V_10
IL_0094: ldc.r8 4
IL_009d: beq IL_016a
IL_00a2: br IL_01a7
IL_00a7: ldloc.s V_7
IL_00a9: isinst ""C""
IL_00ae: brtrue IL_017b
IL_00b3: br.s IL_00f5
IL_00b5: ldloc.s V_7
IL_00b7: castclass ""C""
IL_00bc: stloc.s V_11
// sequence point: <hidden>
IL_00be: ldloc.s V_11
IL_00c0: ldloca.s V_3
IL_00c2: ldloca.s V_12
IL_00c4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00c9: nop
// sequence point: <hidden>
IL_00ca: ldloc.s V_12
IL_00cc: isinst ""C""
IL_00d1: stloc.s V_13
IL_00d3: ldloc.s V_13
IL_00d5: brfalse.s IL_00e6
IL_00d7: ldloc.s V_13
IL_00d9: ldloca.s V_4
IL_00db: callvirt ""void C.Deconstruct(out int)""
IL_00e0: nop
// sequence point: <hidden>
IL_00e1: br IL_0191
IL_00e6: ldloc.s V_11
IL_00e8: ldloca.s V_5
IL_00ea: callvirt ""void C.Deconstruct(out int)""
IL_00ef: nop
// sequence point: <hidden>
IL_00f0: br IL_0198
IL_00f5: ldloc.s V_7
IL_00f7: isinst ""D""
IL_00fc: stloc.s V_14
IL_00fe: ldloc.s V_14
IL_0100: brfalse IL_01a7
IL_0105: ldloc.s V_14
IL_0107: callvirt ""int D.P.get""
IL_010c: stloc.s V_15
// sequence point: <hidden>
IL_010e: ldloc.s V_15
IL_0110: ldc.i4.1
IL_0111: bne.un IL_01a7
IL_0116: ldloc.s V_14
IL_0118: callvirt ""D D.Q.get""
IL_011d: stloc.s V_16
// sequence point: <hidden>
IL_011f: ldloc.s V_16
IL_0121: brfalse IL_01a7
IL_0126: ldloc.s V_16
IL_0128: callvirt ""int D.P.get""
IL_012d: stloc.s V_17
// sequence point: <hidden>
IL_012f: ldloc.s V_17
IL_0131: ldc.i4.2
IL_0132: bne.un.s IL_01a7
IL_0134: ldloc.s V_14
IL_0136: callvirt ""C D.R.get""
IL_013b: stloc.s V_18
// sequence point: <hidden>
IL_013d: ldloc.s V_18
IL_013f: brfalse.s IL_01a7
IL_0141: ldloc.s V_18
IL_0143: ldloca.s V_6
IL_0145: callvirt ""void C.Deconstruct(out int)""
IL_014a: nop
// sequence point: <hidden>
IL_014b: br.s IL_019f
// sequence point: when G(x) > 10
IL_014d: ldloc.0
IL_014e: call ""int Program.G(int)""
IL_0153: ldc.i4.s 10
IL_0155: bgt.s IL_0159
// sequence point: <hidden>
IL_0157: br.s IL_01a7
// sequence point: return 1;
IL_0159: ldc.i4.1
IL_015a: stloc.s V_20
IL_015c: br.s IL_01ad
// sequence point: return 2;
IL_015e: ldc.i4.2
IL_015f: stloc.s V_20
IL_0161: br.s IL_01ad
// sequence point: <hidden>
IL_0163: br.s IL_0165
// sequence point: return 3;
IL_0165: ldc.i4.3
IL_0166: stloc.s V_20
IL_0168: br.s IL_01ad
// sequence point: return 4;
IL_016a: ldc.i4.4
IL_016b: stloc.s V_20
IL_016d: br.s IL_01ad
// sequence point: when B()
IL_016f: call ""bool Program.B()""
IL_0174: brtrue.s IL_0187
// sequence point: <hidden>
IL_0176: br IL_006e
// sequence point: when B()
IL_017b: call ""bool Program.B()""
IL_0180: brtrue.s IL_0187
// sequence point: <hidden>
IL_0182: br IL_00b5
// sequence point: return 5;
IL_0187: ldc.i4.5
IL_0188: stloc.s V_20
IL_018a: br.s IL_01ad
// sequence point: return 6;
IL_018c: ldc.i4.6
IL_018d: stloc.s V_20
IL_018f: br.s IL_01ad
// sequence point: <hidden>
IL_0191: br.s IL_0193
// sequence point: return 7;
IL_0193: ldc.i4.7
IL_0194: stloc.s V_20
IL_0196: br.s IL_01ad
// sequence point: <hidden>
IL_0198: br.s IL_019a
// sequence point: return 8;
IL_019a: ldc.i4.8
IL_019b: stloc.s V_20
IL_019d: br.s IL_01ad
// sequence point: <hidden>
IL_019f: br.s IL_01a1
// sequence point: return 9;
IL_01a1: ldc.i4.s 9
IL_01a3: stloc.s V_20
IL_01a5: br.s IL_01ad
// sequence point: return 10;
IL_01a7: ldc.i4.s 10
IL_01a9: stloc.s V_20
IL_01ab: br.s IL_01ad
// sequence point: }
IL_01ad: ldloc.s V_20
IL_01af: ret
}
", source: source);
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""93"" />
<slot kind=""0"" offset=""244"" />
<slot kind=""0"" offset=""247"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""474"" />
<slot kind=""0"" offset=""516"" />
<slot kind=""0"" offset=""617"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""35"" offset=""11"" ordinal=""5"" />
<slot kind=""35"" offset=""11"" ordinal=""6"" />
<slot kind=""35"" offset=""11"" ordinal=""7"" />
<slot kind=""35"" offset=""11"" ordinal=""8"" />
<slot kind=""35"" offset=""11"" ordinal=""9"" />
<slot kind=""35"" offset=""11"" ordinal=""10"" />
<slot kind=""35"" offset=""11"" ordinal=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
<entry offset=""0xbe"" hidden=""true"" document=""1"" />
<entry offset=""0xca"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" hidden=""true"" document=""1"" />
<entry offset=""0xf0"" hidden=""true"" document=""1"" />
<entry offset=""0x10e"" hidden=""true"" document=""1"" />
<entry offset=""0x11f"" hidden=""true"" document=""1"" />
<entry offset=""0x12f"" hidden=""true"" document=""1"" />
<entry offset=""0x13d"" hidden=""true"" document=""1"" />
<entry offset=""0x14b"" hidden=""true"" document=""1"" />
<entry offset=""0x14d"" startLine=""27"" startColumn=""24"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""27"" startColumn=""40"" endLine=""27"" endColumn=""49"" document=""1"" />
<entry offset=""0x15e"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""35"" document=""1"" />
<entry offset=""0x163"" hidden=""true"" document=""1"" />
<entry offset=""0x165"" startLine=""33"" startColumn=""30"" endLine=""33"" endColumn=""39"" document=""1"" />
<entry offset=""0x16a"" startLine=""36"" startColumn=""23"" endLine=""36"" endColumn=""32"" document=""1"" />
<entry offset=""0x16f"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x176"" hidden=""true"" document=""1"" />
<entry offset=""0x17b"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x182"" hidden=""true"" document=""1"" />
<entry offset=""0x187"" startLine=""39"" startColumn=""32"" endLine=""39"" endColumn=""41"" document=""1"" />
<entry offset=""0x18c"" startLine=""40"" startColumn=""22"" endLine=""40"" endColumn=""31"" document=""1"" />
<entry offset=""0x191"" hidden=""true"" document=""1"" />
<entry offset=""0x193"" startLine=""41"" startColumn=""38"" endLine=""41"" endColumn=""47"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19a"" startLine=""42"" startColumn=""31"" endLine=""42"" endColumn=""40"" document=""1"" />
<entry offset=""0x19f"" hidden=""true"" document=""1"" />
<entry offset=""0x1a1"" startLine=""45"" startColumn=""58"" endLine=""45"" endColumn=""67"" document=""1"" />
<entry offset=""0x1a7"" startLine=""47"" startColumn=""22"" endLine=""47"" endColumn=""32"" document=""1"" />
<entry offset=""0x1ad"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b0"">
<scope startOffset=""0x14d"" endOffset=""0x15e"">
<local name=""x"" il_index=""0"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" />
</scope>
<scope startOffset=""0x163"" endOffset=""0x16a"">
<local name=""y"" il_index=""1"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
<local name=""z"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
</scope>
<scope startOffset=""0x191"" endOffset=""0x198"">
<local name=""p"" il_index=""3"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
<local name=""q"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
</scope>
<scope startOffset=""0x198"" endOffset=""0x19f"">
<local name=""p"" il_index=""5"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" />
</scope>
<scope startOffset=""0x19f"" endOffset=""0x1a7"">
<local name=""z"" il_index=""6"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchExpression()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static void Main()
{
var a = F() switch
{
// declaration pattern
int x when G(x) > 10 => 1,
// discard pattern
bool _ => 2,
// var pattern
var (y, z) => 3,
// constant pattern
4.0 => 4,
// positional patterns
C() when B() => 5,
() => 6,
C(int p, C(int q)) => 7,
C(x: int p) => 8,
// property pattern
D { P: 1, Q: D { P: 2 }, R: C (int z) } => 9,
_ => 10,
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
// note no sequence points emitted within the switch expression
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 437 (0x1b5)
.maxstack 3
.locals init (int V_0, //a
int V_1, //x
object V_2, //y
object V_3, //z
int V_4, //p
int V_5, //q
int V_6, //p
int V_7, //z
int V_8,
object V_9,
System.Runtime.CompilerServices.ITuple V_10,
int V_11,
double V_12,
C V_13,
object V_14,
C V_15,
D V_16,
int V_17,
D V_18,
int V_19,
C V_20)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_9
IL_0008: ldc.i4.1
IL_0009: brtrue.s IL_000c
-IL_000b: nop
~IL_000c: ldloc.s V_9
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_9
IL_0017: unbox.any ""int""
IL_001c: stloc.1
~IL_001d: br IL_014d
IL_0022: ldloc.s V_9
IL_0024: isinst ""bool""
IL_0029: brtrue IL_015e
IL_002e: ldloc.s V_9
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_10
IL_0037: ldloc.s V_10
IL_0039: brfalse.s IL_0080
IL_003b: ldloc.s V_10
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_11
~IL_0044: ldloc.s V_11
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0060
IL_0049: ldloc.s V_10
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.2
~IL_0052: ldloc.s V_10
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.3
~IL_005b: br IL_0163
IL_0060: ldloc.s V_9
IL_0062: isinst ""C""
IL_0067: brtrue IL_016f
IL_006c: br.s IL_0077
IL_006e: ldloc.s V_11
IL_0070: brfalse IL_018c
IL_0075: br.s IL_00b5
IL_0077: ldloc.s V_11
IL_0079: brfalse IL_018c
IL_007e: br.s IL_00f5
IL_0080: ldloc.s V_9
IL_0082: isinst ""double""
IL_0087: brfalse.s IL_00a7
IL_0089: ldloc.s V_9
IL_008b: unbox.any ""double""
IL_0090: stloc.s V_12
~IL_0092: ldloc.s V_12
IL_0094: ldc.r8 4
IL_009d: beq IL_016a
IL_00a2: br IL_01a7
IL_00a7: ldloc.s V_9
IL_00a9: isinst ""C""
IL_00ae: brtrue IL_017b
IL_00b3: br.s IL_00f5
IL_00b5: ldloc.s V_9
IL_00b7: castclass ""C""
IL_00bc: stloc.s V_13
~IL_00be: ldloc.s V_13
IL_00c0: ldloca.s V_4
IL_00c2: ldloca.s V_14
IL_00c4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00c9: nop
~IL_00ca: ldloc.s V_14
IL_00cc: isinst ""C""
IL_00d1: stloc.s V_15
IL_00d3: ldloc.s V_15
IL_00d5: brfalse.s IL_00e6
IL_00d7: ldloc.s V_15
IL_00d9: ldloca.s V_5
IL_00db: callvirt ""void C.Deconstruct(out int)""
IL_00e0: nop
~IL_00e1: br IL_0191
IL_00e6: ldloc.s V_13
IL_00e8: ldloca.s V_6
IL_00ea: callvirt ""void C.Deconstruct(out int)""
IL_00ef: nop
~IL_00f0: br IL_0198
IL_00f5: ldloc.s V_9
IL_00f7: isinst ""D""
IL_00fc: stloc.s V_16
IL_00fe: ldloc.s V_16
IL_0100: brfalse IL_01a7
IL_0105: ldloc.s V_16
IL_0107: callvirt ""int D.P.get""
IL_010c: stloc.s V_17
~IL_010e: ldloc.s V_17
IL_0110: ldc.i4.1
IL_0111: bne.un IL_01a7
IL_0116: ldloc.s V_16
IL_0118: callvirt ""D D.Q.get""
IL_011d: stloc.s V_18
~IL_011f: ldloc.s V_18
IL_0121: brfalse IL_01a7
IL_0126: ldloc.s V_18
IL_0128: callvirt ""int D.P.get""
IL_012d: stloc.s V_19
~IL_012f: ldloc.s V_19
IL_0131: ldc.i4.2
IL_0132: bne.un.s IL_01a7
IL_0134: ldloc.s V_16
IL_0136: callvirt ""C D.R.get""
IL_013b: stloc.s V_20
~IL_013d: ldloc.s V_20
IL_013f: brfalse.s IL_01a7
IL_0141: ldloc.s V_20
IL_0143: ldloca.s V_7
IL_0145: callvirt ""void C.Deconstruct(out int)""
IL_014a: nop
~IL_014b: br.s IL_019f
-IL_014d: ldloc.1
IL_014e: call ""int Program.G(int)""
IL_0153: ldc.i4.s 10
IL_0155: bgt.s IL_0159
~IL_0157: br.s IL_01a7
-IL_0159: ldc.i4.1
IL_015a: stloc.s V_8
IL_015c: br.s IL_01ad
-IL_015e: ldc.i4.2
IL_015f: stloc.s V_8
IL_0161: br.s IL_01ad
~IL_0163: br.s IL_0165
-IL_0165: ldc.i4.3
IL_0166: stloc.s V_8
IL_0168: br.s IL_01ad
-IL_016a: ldc.i4.4
IL_016b: stloc.s V_8
IL_016d: br.s IL_01ad
-IL_016f: call ""bool Program.B()""
IL_0174: brtrue.s IL_0187
~IL_0176: br IL_006e
-IL_017b: call ""bool Program.B()""
IL_0180: brtrue.s IL_0187
~IL_0182: br IL_00b5
-IL_0187: ldc.i4.5
IL_0188: stloc.s V_8
IL_018a: br.s IL_01ad
-IL_018c: ldc.i4.6
IL_018d: stloc.s V_8
IL_018f: br.s IL_01ad
~IL_0191: br.s IL_0193
-IL_0193: ldc.i4.7
IL_0194: stloc.s V_8
IL_0196: br.s IL_01ad
~IL_0198: br.s IL_019a
-IL_019a: ldc.i4.8
IL_019b: stloc.s V_8
IL_019d: br.s IL_01ad
~IL_019f: br.s IL_01a1
-IL_01a1: ldc.i4.s 9
IL_01a3: stloc.s V_8
IL_01a5: br.s IL_01ad
-IL_01a7: ldc.i4.s 10
IL_01a9: stloc.s V_8
IL_01ab: br.s IL_01ad
~IL_01ad: ldc.i4.1
IL_01ae: brtrue.s IL_01b1
-IL_01b0: nop
~IL_01b1: ldloc.s V_8
IL_01b3: stloc.0
-IL_01b4: ret
}
");
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""94"" />
<slot kind=""0"" offset=""225"" />
<slot kind=""0"" offset=""228"" />
<slot kind=""0"" offset=""406"" />
<slot kind=""0"" offset=""415"" />
<slot kind=""0"" offset=""447"" />
<slot kind=""0"" offset=""539"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""23"" />
<slot kind=""35"" offset=""23"" ordinal=""1"" />
<slot kind=""35"" offset=""23"" ordinal=""2"" />
<slot kind=""35"" offset=""23"" ordinal=""3"" />
<slot kind=""35"" offset=""23"" ordinal=""4"" />
<slot kind=""35"" offset=""23"" ordinal=""5"" />
<slot kind=""35"" offset=""23"" ordinal=""6"" />
<slot kind=""35"" offset=""23"" ordinal=""7"" />
<slot kind=""35"" offset=""23"" ordinal=""8"" />
<slot kind=""35"" offset=""23"" ordinal=""9"" />
<slot kind=""35"" offset=""23"" ordinal=""10"" />
<slot kind=""35"" offset=""23"" ordinal=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0xb"" startLine=""24"" startColumn=""21"" endLine=""48"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
<entry offset=""0xbe"" hidden=""true"" document=""1"" />
<entry offset=""0xca"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" hidden=""true"" document=""1"" />
<entry offset=""0xf0"" hidden=""true"" document=""1"" />
<entry offset=""0x10e"" hidden=""true"" document=""1"" />
<entry offset=""0x11f"" hidden=""true"" document=""1"" />
<entry offset=""0x12f"" hidden=""true"" document=""1"" />
<entry offset=""0x13d"" hidden=""true"" document=""1"" />
<entry offset=""0x14b"" hidden=""true"" document=""1"" />
<entry offset=""0x14d"" startLine=""27"" startColumn=""19"" endLine=""27"" endColumn=""33"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""27"" startColumn=""37"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x15e"" startLine=""30"" startColumn=""23"" endLine=""30"" endColumn=""24"" document=""1"" />
<entry offset=""0x163"" hidden=""true"" document=""1"" />
<entry offset=""0x165"" startLine=""33"" startColumn=""27"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x16a"" startLine=""36"" startColumn=""20"" endLine=""36"" endColumn=""21"" document=""1"" />
<entry offset=""0x16f"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" />
<entry offset=""0x176"" hidden=""true"" document=""1"" />
<entry offset=""0x17b"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" />
<entry offset=""0x182"" hidden=""true"" document=""1"" />
<entry offset=""0x187"" startLine=""39"" startColumn=""29"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x18c"" startLine=""40"" startColumn=""19"" endLine=""40"" endColumn=""20"" document=""1"" />
<entry offset=""0x191"" hidden=""true"" document=""1"" />
<entry offset=""0x193"" startLine=""41"" startColumn=""35"" endLine=""41"" endColumn=""36"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19a"" startLine=""42"" startColumn=""28"" endLine=""42"" endColumn=""29"" document=""1"" />
<entry offset=""0x19f"" hidden=""true"" document=""1"" />
<entry offset=""0x1a1"" startLine=""45"" startColumn=""56"" endLine=""45"" endColumn=""57"" document=""1"" />
<entry offset=""0x1a7"" startLine=""47"" startColumn=""18"" endLine=""47"" endColumn=""20"" document=""1"" />
<entry offset=""0x1ad"" hidden=""true"" document=""1"" />
<entry offset=""0x1b0"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0x1b1"" hidden=""true"" document=""1"" />
<entry offset=""0x1b4"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b5"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b5"" attributes=""0"" />
<scope startOffset=""0x14d"" endOffset=""0x15e"">
<local name=""x"" il_index=""1"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" />
</scope>
<scope startOffset=""0x163"" endOffset=""0x16a"">
<local name=""y"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
</scope>
<scope startOffset=""0x191"" endOffset=""0x198"">
<local name=""p"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
</scope>
<scope startOffset=""0x198"" endOffset=""0x19f"">
<local name=""p"" il_index=""6"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" />
</scope>
<scope startOffset=""0x19f"" endOffset=""0x1a7"">
<local name=""z"" il_index=""7"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_IsPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static bool M()
{
object obj = F();
return
// declaration pattern
obj is int x ||
// discard pattern
obj is bool _ ||
// var pattern
obj is var (y, z1) ||
// constant pattern
obj is 4.0 ||
// positional patterns
obj is C() ||
obj is () ||
obj is C(int p1, C(int q)) ||
obj is C(x: int p2) ||
// property pattern
obj is D { P: 1, Q: D { P: 2 }, R: C(int z2) };
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.M", sequencePoints: "Program.M", expectedIL: @"
{
// Code size 301 (0x12d)
.maxstack 3
.locals init (object V_0, //obj
int V_1, //x
object V_2, //y
object V_3, //z1
int V_4, //p1
int V_5, //q
int V_6, //p2
int V_7, //z2
System.Runtime.CompilerServices.ITuple V_8,
C V_9,
object V_10,
C V_11,
D V_12,
D V_13,
bool V_14)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.0
-IL_0007: ldloc.0
IL_0008: isinst ""int""
IL_000d: brfalse.s IL_001b
IL_000f: ldloc.0
IL_0010: unbox.any ""int""
IL_0015: stloc.1
IL_0016: br IL_0125
IL_001b: ldloc.0
IL_001c: isinst ""bool""
IL_0021: brtrue IL_0125
IL_0026: ldloc.0
IL_0027: isinst ""System.Runtime.CompilerServices.ITuple""
IL_002c: stloc.s V_8
IL_002e: ldloc.s V_8
IL_0030: brfalse.s IL_0053
IL_0032: ldloc.s V_8
IL_0034: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0039: ldc.i4.2
IL_003a: bne.un.s IL_0053
IL_003c: ldloc.s V_8
IL_003e: ldc.i4.0
IL_003f: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0044: stloc.2
IL_0045: ldloc.s V_8
IL_0047: ldc.i4.1
IL_0048: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_004d: stloc.3
IL_004e: br IL_0125
IL_0053: ldloc.0
IL_0054: isinst ""double""
IL_0059: brfalse.s IL_006f
IL_005b: ldloc.0
IL_005c: unbox.any ""double""
IL_0061: ldc.r8 4
IL_006a: beq IL_0125
IL_006f: ldloc.0
IL_0070: isinst ""C""
IL_0075: brtrue IL_0125
IL_007a: ldloc.0
IL_007b: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0080: stloc.s V_8
IL_0082: ldloc.s V_8
IL_0084: brfalse.s IL_0092
IL_0086: ldloc.s V_8
IL_0088: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_008d: brfalse IL_0125
IL_0092: ldloc.0
IL_0093: isinst ""C""
IL_0098: stloc.s V_9
IL_009a: ldloc.s V_9
IL_009c: brfalse.s IL_00c3
IL_009e: ldloc.s V_9
IL_00a0: ldloca.s V_4
IL_00a2: ldloca.s V_10
IL_00a4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00a9: nop
IL_00aa: ldloc.s V_10
IL_00ac: isinst ""C""
IL_00b1: stloc.s V_11
IL_00b3: ldloc.s V_11
IL_00b5: brfalse.s IL_00c3
IL_00b7: ldloc.s V_11
IL_00b9: ldloca.s V_5
IL_00bb: callvirt ""void C.Deconstruct(out int)""
IL_00c0: nop
IL_00c1: br.s IL_0125
IL_00c3: ldloc.0
IL_00c4: isinst ""C""
IL_00c9: stloc.s V_11
IL_00cb: ldloc.s V_11
IL_00cd: brfalse.s IL_00db
IL_00cf: ldloc.s V_11
IL_00d1: ldloca.s V_6
IL_00d3: callvirt ""void C.Deconstruct(out int)""
IL_00d8: nop
IL_00d9: br.s IL_0125
IL_00db: ldloc.0
IL_00dc: isinst ""D""
IL_00e1: stloc.s V_12
IL_00e3: ldloc.s V_12
IL_00e5: brfalse.s IL_0122
IL_00e7: ldloc.s V_12
IL_00e9: callvirt ""int D.P.get""
IL_00ee: ldc.i4.1
IL_00ef: bne.un.s IL_0122
IL_00f1: ldloc.s V_12
IL_00f3: callvirt ""D D.Q.get""
IL_00f8: stloc.s V_13
IL_00fa: ldloc.s V_13
IL_00fc: brfalse.s IL_0122
IL_00fe: ldloc.s V_13
IL_0100: callvirt ""int D.P.get""
IL_0105: ldc.i4.2
IL_0106: bne.un.s IL_0122
IL_0108: ldloc.s V_12
IL_010a: callvirt ""C D.R.get""
IL_010f: stloc.s V_11
IL_0111: ldloc.s V_11
IL_0113: brfalse.s IL_0122
IL_0115: ldloc.s V_11
IL_0117: ldloca.s V_7
IL_0119: callvirt ""void C.Deconstruct(out int)""
IL_011e: nop
IL_011f: ldc.i4.1
IL_0120: br.s IL_0123
IL_0122: ldc.i4.0
IL_0123: br.s IL_0126
IL_0125: ldc.i4.1
IL_0126: stloc.s V_14
IL_0128: br.s IL_012a
-IL_012a: ldloc.s V_14
IL_012c: ret
}
");
verifier.VerifyPdb("Program.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
<slot kind=""0"" offset=""106"" />
<slot kind=""0"" offset=""230"" />
<slot kind=""0"" offset=""233"" />
<slot kind=""0"" offset=""419"" />
<slot kind=""0"" offset=""429"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""561"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""25"" startColumn=""9"" endLine=""45"" endColumn=""60"" document=""1"" />
<entry offset=""0x12a"" startLine=""46"" startColumn=""5"" endLine=""46"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x12d"">
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""y"" il_index=""2"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z1"" il_index=""3"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p1"" il_index=""4"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p2"" il_index=""6"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z2"" il_index=""7"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(37232, "https://github.com/dotnet/roslyn/issues/37232")]
[WorkItem(37237, "https://github.com/dotnet/roslyn/issues/37237")]
[Fact]
public void Patterns_SwitchExpression_Closures()
{
string source = WithWindowsLineBreaks(@"
using System;
public class C
{
static int M()
{
return F() switch
{
1 => F() switch
{
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 10
},
2 => F() switch
{
C { P: int r } => G(() => r),
_ => 20
},
C { Q: int s } => G(() => s),
_ => 0
}
switch
{
var t when t > 0 => G(() => t),
_ => 0
};
}
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 472 (0x1d8)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
C.<>c__DisplayClass0_1 V_2, //CS$<>8__locals1
int V_3,
object V_4,
int V_5,
C V_6,
object V_7,
C.<>c__DisplayClass0_2 V_8, //CS$<>8__locals2
int V_9,
object V_10,
C V_11,
object V_12,
object V_13,
C V_14,
object V_15,
C.<>c__DisplayClass0_3 V_16, //CS$<>8__locals3
object V_17,
C V_18,
object V_19,
int V_20)
// sequence point: {
IL_0000: nop
// sequence point: <hidden>
IL_0001: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_000c: stloc.2
IL_000d: call ""object C.F()""
IL_0012: stloc.s V_4
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
// sequence point: switch ... }
IL_0017: nop
// sequence point: <hidden>
IL_0018: ldloc.s V_4
IL_001a: isinst ""int""
IL_001f: brfalse.s IL_003e
IL_0021: ldloc.s V_4
IL_0023: unbox.any ""int""
IL_0028: stloc.s V_5
// sequence point: <hidden>
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.1
IL_002d: beq.s IL_0075
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_5
IL_0033: ldc.i4.2
IL_0034: beq IL_0116
IL_0039: br IL_0194
IL_003e: ldloc.s V_4
IL_0040: isinst ""C""
IL_0045: stloc.s V_6
IL_0047: ldloc.s V_6
IL_0049: brfalse IL_0194
IL_004e: ldloc.s V_6
IL_0050: callvirt ""object C.Q.get""
IL_0055: stloc.s V_7
// sequence point: <hidden>
IL_0057: ldloc.s V_7
IL_0059: isinst ""int""
IL_005e: brfalse IL_0194
IL_0063: ldloc.2
IL_0064: ldloc.s V_7
IL_0066: unbox.any ""int""
IL_006b: stfld ""int C.<>c__DisplayClass0_1.<s>5__3""
// sequence point: <hidden>
IL_0070: br IL_017e
// sequence point: <hidden>
IL_0075: newobj ""C.<>c__DisplayClass0_2..ctor()""
IL_007a: stloc.s V_8
IL_007c: call ""object C.F()""
IL_0081: stloc.s V_10
IL_0083: ldc.i4.1
IL_0084: brtrue.s IL_0087
// sequence point: switch ...
IL_0086: nop
// sequence point: <hidden>
IL_0087: ldloc.s V_10
IL_0089: isinst ""C""
IL_008e: stloc.s V_11
IL_0090: ldloc.s V_11
IL_0092: brfalse.s IL_0104
IL_0094: ldloc.s V_11
IL_0096: callvirt ""object C.P.get""
IL_009b: stloc.s V_12
// sequence point: <hidden>
IL_009d: ldloc.s V_12
IL_009f: isinst ""int""
IL_00a4: brfalse.s IL_0104
IL_00a6: ldloc.s V_8
IL_00a8: ldloc.s V_12
IL_00aa: unbox.any ""int""
IL_00af: stfld ""int C.<>c__DisplayClass0_2.<p>5__4""
// sequence point: <hidden>
IL_00b4: ldloc.s V_11
IL_00b6: callvirt ""object C.Q.get""
IL_00bb: stloc.s V_13
// sequence point: <hidden>
IL_00bd: ldloc.s V_13
IL_00bf: isinst ""C""
IL_00c4: stloc.s V_14
IL_00c6: ldloc.s V_14
IL_00c8: brfalse.s IL_0104
IL_00ca: ldloc.s V_14
IL_00cc: callvirt ""object C.P.get""
IL_00d1: stloc.s V_15
// sequence point: <hidden>
IL_00d3: ldloc.s V_15
IL_00d5: isinst ""int""
IL_00da: brfalse.s IL_0104
IL_00dc: ldloc.s V_8
IL_00de: ldloc.s V_15
IL_00e0: unbox.any ""int""
IL_00e5: stfld ""int C.<>c__DisplayClass0_2.<q>5__5""
// sequence point: <hidden>
IL_00ea: br.s IL_00ec
// sequence point: <hidden>
IL_00ec: br.s IL_00ee
// sequence point: G(() => p + q)
IL_00ee: ldloc.s V_8
IL_00f0: ldftn ""int C.<>c__DisplayClass0_2.<M>b__2()""
IL_00f6: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_00fb: call ""int C.G(System.Func<int>)""
IL_0100: stloc.s V_9
IL_0102: br.s IL_010a
// sequence point: 10
IL_0104: ldc.i4.s 10
IL_0106: stloc.s V_9
IL_0108: br.s IL_010a
// sequence point: <hidden>
IL_010a: ldc.i4.1
IL_010b: brtrue.s IL_010e
// sequence point: switch ... }
IL_010d: nop
// sequence point: F() switch ...
IL_010e: ldloc.s V_9
IL_0110: stloc.3
IL_0111: br IL_0198
// sequence point: <hidden>
IL_0116: newobj ""C.<>c__DisplayClass0_3..ctor()""
IL_011b: stloc.s V_16
IL_011d: call ""object C.F()""
IL_0122: stloc.s V_17
IL_0124: ldc.i4.1
IL_0125: brtrue.s IL_0128
// sequence point: switch ...
IL_0127: nop
// sequence point: <hidden>
IL_0128: ldloc.s V_17
IL_012a: isinst ""C""
IL_012f: stloc.s V_18
IL_0131: ldloc.s V_18
IL_0133: brfalse.s IL_016f
IL_0135: ldloc.s V_18
IL_0137: callvirt ""object C.P.get""
IL_013c: stloc.s V_19
// sequence point: <hidden>
IL_013e: ldloc.s V_19
IL_0140: isinst ""int""
IL_0145: brfalse.s IL_016f
IL_0147: ldloc.s V_16
IL_0149: ldloc.s V_19
IL_014b: unbox.any ""int""
IL_0150: stfld ""int C.<>c__DisplayClass0_3.<r>5__6""
// sequence point: <hidden>
IL_0155: br.s IL_0157
// sequence point: <hidden>
IL_0157: br.s IL_0159
// sequence point: G(() => r)
IL_0159: ldloc.s V_16
IL_015b: ldftn ""int C.<>c__DisplayClass0_3.<M>b__3()""
IL_0161: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0166: call ""int C.G(System.Func<int>)""
IL_016b: stloc.s V_9
IL_016d: br.s IL_0175
// sequence point: 20
IL_016f: ldc.i4.s 20
IL_0171: stloc.s V_9
IL_0173: br.s IL_0175
// sequence point: <hidden>
IL_0175: ldc.i4.1
IL_0176: brtrue.s IL_0179
// sequence point: F() switch ...
IL_0178: nop
// sequence point: F() switch ...
IL_0179: ldloc.s V_9
IL_017b: stloc.3
IL_017c: br.s IL_0198
// sequence point: <hidden>
IL_017e: br.s IL_0180
// sequence point: G(() => s)
IL_0180: ldloc.2
IL_0181: ldftn ""int C.<>c__DisplayClass0_1.<M>b__1()""
IL_0187: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_018c: call ""int C.G(System.Func<int>)""
IL_0191: stloc.3
IL_0192: br.s IL_0198
// sequence point: 0
IL_0194: ldc.i4.0
IL_0195: stloc.3
IL_0196: br.s IL_0198
// sequence point: <hidden>
IL_0198: ldc.i4.1
IL_0199: brtrue.s IL_019c
// sequence point: return F() s ... };
IL_019b: nop
// sequence point: <hidden>
IL_019c: ldloc.0
IL_019d: ldloc.3
IL_019e: stfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01a3: ldc.i4.1
IL_01a4: brtrue.s IL_01a7
// sequence point: switch ... }
IL_01a6: nop
// sequence point: <hidden>
IL_01a7: br.s IL_01a9
// sequence point: when t > 0
IL_01a9: ldloc.0
IL_01aa: ldfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01af: ldc.i4.0
IL_01b0: bgt.s IL_01b4
// sequence point: <hidden>
IL_01b2: br.s IL_01c8
// sequence point: G(() => t)
IL_01b4: ldloc.0
IL_01b5: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_01bb: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_01c0: call ""int C.G(System.Func<int>)""
IL_01c5: stloc.1
IL_01c6: br.s IL_01cc
// sequence point: 0
IL_01c8: ldc.i4.0
IL_01c9: stloc.1
IL_01ca: br.s IL_01cc
// sequence point: <hidden>
IL_01cc: ldc.i4.1
IL_01cd: brtrue.s IL_01d0
// sequence point: return F() s ... };
IL_01cf: nop
// sequence point: <hidden>
IL_01d0: ldloc.1
IL_01d1: stloc.s V_20
IL_01d3: br.s IL_01d5
// sequence point: }
IL_01d5: ldloc.s V_20
IL_01d7: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""30"" offset=""22"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""22"" />
<slot kind=""35"" offset=""22"" ordinal=""1"" />
<slot kind=""35"" offset=""22"" ordinal=""2"" />
<slot kind=""35"" offset=""22"" ordinal=""3"" />
<slot kind=""30"" offset=""63"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""63"" />
<slot kind=""35"" offset=""63"" ordinal=""1"" />
<slot kind=""35"" offset=""63"" ordinal=""2"" />
<slot kind=""35"" offset=""63"" ordinal=""3"" />
<slot kind=""35"" offset=""63"" ordinal=""4"" />
<slot kind=""35"" offset=""63"" ordinal=""5"" />
<slot kind=""30"" offset=""238"" />
<slot kind=""35"" offset=""238"" />
<slot kind=""35"" offset=""238"" ordinal=""1"" />
<slot kind=""35"" offset=""238"" ordinal=""2"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<closure offset=""22"" />
<closure offset=""63"" />
<closure offset=""238"" />
<lambda offset=""511"" closure=""0"" />
<lambda offset=""407"" closure=""1"" />
<lambda offset=""157"" closure=""2"" />
<lambda offset=""313"" closure=""3"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x17"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x18"" hidden=""true"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" hidden=""true"" document=""1"" />
<entry offset=""0x86"" startLine=""9"" startColumn=""22"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x87"" hidden=""true"" document=""1"" />
<entry offset=""0x9d"" hidden=""true"" document=""1"" />
<entry offset=""0xb4"" hidden=""true"" document=""1"" />
<entry offset=""0xbd"" hidden=""true"" document=""1"" />
<entry offset=""0xd3"" hidden=""true"" document=""1"" />
<entry offset=""0xea"" hidden=""true"" document=""1"" />
<entry offset=""0xec"" hidden=""true"" document=""1"" />
<entry offset=""0xee"" startLine=""11"" startColumn=""59"" endLine=""11"" endColumn=""73"" document=""1"" />
<entry offset=""0x104"" startLine=""12"" startColumn=""27"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x10a"" hidden=""true"" document=""1"" />
<entry offset=""0x10d"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x10e"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x116"" hidden=""true"" document=""1"" />
<entry offset=""0x127"" startLine=""14"" startColumn=""22"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x128"" hidden=""true"" document=""1"" />
<entry offset=""0x13e"" hidden=""true"" document=""1"" />
<entry offset=""0x155"" hidden=""true"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""16"" startColumn=""40"" endLine=""16"" endColumn=""50"" document=""1"" />
<entry offset=""0x16f"" startLine=""17"" startColumn=""27"" endLine=""17"" endColumn=""29"" document=""1"" />
<entry offset=""0x175"" hidden=""true"" document=""1"" />
<entry offset=""0x178"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x179"" startLine=""14"" startColumn=""18"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x17e"" hidden=""true"" document=""1"" />
<entry offset=""0x180"" startLine=""19"" startColumn=""31"" endLine=""19"" endColumn=""41"" document=""1"" />
<entry offset=""0x194"" startLine=""20"" startColumn=""18"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19b"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x19c"" hidden=""true"" document=""1"" />
<entry offset=""0x1a6"" startLine=""22"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a7"" hidden=""true"" document=""1"" />
<entry offset=""0x1a9"" startLine=""24"" startColumn=""19"" endLine=""24"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b2"" hidden=""true"" document=""1"" />
<entry offset=""0x1b4"" startLine=""24"" startColumn=""33"" endLine=""24"" endColumn=""43"" document=""1"" />
<entry offset=""0x1c8"" startLine=""25"" startColumn=""18"" endLine=""25"" endColumn=""19"" document=""1"" />
<entry offset=""0x1cc"" hidden=""true"" document=""1"" />
<entry offset=""0x1cf"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x1d0"" hidden=""true"" document=""1"" />
<entry offset=""0x1d5"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1d8"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x1d5"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x1d5"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x1a3"">
<local name=""CS$<>8__locals1"" il_index=""2"" il_start=""0x7"" il_end=""0x1a3"" attributes=""0"" />
<scope startOffset=""0x75"" endOffset=""0x111"">
<local name=""CS$<>8__locals2"" il_index=""8"" il_start=""0x75"" il_end=""0x111"" attributes=""0"" />
</scope>
<scope startOffset=""0x116"" endOffset=""0x17c"">
<local name=""CS$<>8__locals3"" il_index=""16"" il_start=""0x116"" il_end=""0x17c"" attributes=""0"" />
</scope>
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_01()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static int F(object o)
{
return o switch
{
int i => new Func<int>(() => i + i switch
{
1 => 2,
_ => 3
})(),
_ => 4
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance int32 '<F>b__0' () cil managed
{
// Method begins at RVA 0x20ac
// Code size 38 (0x26)
.maxstack 2
.locals init (
[0] int32,
[1] int32
)
IL_0000: ldarg.0
IL_0001: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0011: ldc.i4.1
IL_0012: beq.s IL_0016
IL_0014: br.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.1
IL_0018: br.s IL_001e
IL_001a: ldc.i4.3
IL_001b: stloc.1
IL_001c: br.s IL_001e
IL_001e: ldc.i4.1
IL_001f: brtrue.s IL_0022
IL_0021: nop
IL_0022: ldloc.0
IL_0023: ldloc.1
IL_0024: add
IL_0025: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
int32 F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 69 (0x45)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] int32,
[2] int32
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance int32 C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<int32>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<int32>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003b
IL_0037: ldc.i4.4
IL_0038: stloc.1
IL_0039: br.s IL_003b
IL_003b: ldc.i4.1
IL_003c: brtrue.s IL_003f
IL_003e: nop
IL_003f: ldloc.1
IL_0040: stloc.2
IL_0041: br.s IL_0043
IL_0043: ldloc.2
IL_0044: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""80"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3e"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x45"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x43"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x43"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
<encLocalSlotMap>
<slot kind=""28"" offset=""86"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""48"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x1a"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_02()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static string F(object o)
{
return o switch
{
int i => new Func<string>(() => ""1"" + i switch
{
1 => new Func<string>(() => ""2"" + i)(),
_ => ""3""
})(),
_ => ""4""
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
.field public class [netstandard]System.Func`1<string> '<>9__1'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance string '<F>b__0' () cil managed
{
// Method begins at RVA 0x20b0
// Code size 78 (0x4e)
.maxstack 3
.locals init (
[0] string,
[1] class [netstandard]System.Func`1<string>
)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.0
IL_0005: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000a: ldc.i4.1
IL_000b: beq.s IL_000f
IL_000d: br.s IL_0036
IL_000f: ldarg.0
IL_0010: ldfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_0015: dup
IL_0016: brtrue.s IL_002e
IL_0018: pop
IL_0019: ldarg.0
IL_001a: ldarg.0
IL_001b: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__1'()
IL_0021: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_0026: dup
IL_0027: stloc.1
IL_0028: stfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_002d: ldloc.1
IL_002e: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0033: stloc.0
IL_0034: br.s IL_003e
IL_0036: ldstr ""3""
IL_003b: stloc.0
IL_003c: br.s IL_003e
IL_003e: ldc.i4.1
IL_003f: brtrue.s IL_0042
IL_0041: nop
IL_0042: ldstr ""1""
IL_0047: ldloc.0
IL_0048: call string [netstandard]System.String::Concat(string, string)
IL_004d: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
.method assembly hidebysig
instance string '<F>b__1' () cil managed
{
// Method begins at RVA 0x210a
// Code size 22 (0x16)
.maxstack 8
IL_0000: ldstr ""2""
IL_0005: ldarg.0
IL_0006: ldflda int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000b: call instance string [netstandard]System.Int32::ToString()
IL_0010: call string [netstandard]System.String::Concat(string, string)
IL_0015: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__1'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
string F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 73 (0x49)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] string,
[2] string
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003f
IL_0037: ldstr ""4""
IL_003c: stloc.1
IL_003d: br.s IL_003f
IL_003f: ldc.i4.1
IL_0040: brtrue.s IL_0043
IL_0042: nop
IL_0043: ldloc.1
IL_0044: stloc.2
IL_0045: br.s IL_0047
IL_0047: ldloc.2
IL_0048: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""83"" closure=""0"" />
<lambda offset=""158"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x42"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x43"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x49"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x47"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x47"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""53"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""55"" document=""1"" />
<entry offset=""0x36"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""25"" document=""1"" />
<entry offset=""0x3e"" hidden=""true"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x42"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody()
{
string source = @"
using System;
public class C
{
static int M() => F() switch
{
1 => 1,
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 0
};
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 171 (0xab)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
object V_2,
int V_3,
C V_4,
object V_5,
object V_6,
C V_7,
object V_8)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: call ""object C.F()""
IL_000b: stloc.2
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
// sequence point: switch ... }
IL_000f: nop
// sequence point: <hidden>
IL_0010: ldloc.2
IL_0011: isinst ""int""
IL_0016: brfalse.s IL_0025
IL_0018: ldloc.2
IL_0019: unbox.any ""int""
IL_001e: stloc.3
// sequence point: <hidden>
IL_001f: ldloc.3
IL_0020: ldc.i4.1
IL_0021: beq.s IL_0087
IL_0023: br.s IL_00a1
IL_0025: ldloc.2
IL_0026: isinst ""C""
IL_002b: stloc.s V_4
IL_002d: ldloc.s V_4
IL_002f: brfalse.s IL_00a1
IL_0031: ldloc.s V_4
IL_0033: callvirt ""object C.P.get""
IL_0038: stloc.s V_5
// sequence point: <hidden>
IL_003a: ldloc.s V_5
IL_003c: isinst ""int""
IL_0041: brfalse.s IL_00a1
IL_0043: ldloc.0
IL_0044: ldloc.s V_5
IL_0046: unbox.any ""int""
IL_004b: stfld ""int C.<>c__DisplayClass0_0.<p>5__2""
// sequence point: <hidden>
IL_0050: ldloc.s V_4
IL_0052: callvirt ""object C.Q.get""
IL_0057: stloc.s V_6
// sequence point: <hidden>
IL_0059: ldloc.s V_6
IL_005b: isinst ""C""
IL_0060: stloc.s V_7
IL_0062: ldloc.s V_7
IL_0064: brfalse.s IL_00a1
IL_0066: ldloc.s V_7
IL_0068: callvirt ""object C.P.get""
IL_006d: stloc.s V_8
// sequence point: <hidden>
IL_006f: ldloc.s V_8
IL_0071: isinst ""int""
IL_0076: brfalse.s IL_00a1
IL_0078: ldloc.0
IL_0079: ldloc.s V_8
IL_007b: unbox.any ""int""
IL_0080: stfld ""int C.<>c__DisplayClass0_0.<q>5__3""
// sequence point: <hidden>
IL_0085: br.s IL_008b
// sequence point: 1
IL_0087: ldc.i4.1
IL_0088: stloc.1
IL_0089: br.s IL_00a5
// sequence point: <hidden>
IL_008b: br.s IL_008d
// sequence point: G(() => p + q)
IL_008d: ldloc.0
IL_008e: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_0094: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0099: call ""int C.G(System.Func<int>)""
IL_009e: stloc.1
IL_009f: br.s IL_00a5
// sequence point: 0
IL_00a1: ldc.i4.0
IL_00a2: stloc.1
IL_00a3: br.s IL_00a5
// sequence point: <hidden>
IL_00a5: ldc.i4.1
IL_00a6: brtrue.s IL_00a9
// sequence point: F() switch ... }
IL_00a8: nop
// sequence point: <hidden>
IL_00a9: ldloc.1
IL_00aa: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""7"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""7"" />
<slot kind=""35"" offset=""7"" ordinal=""1"" />
<slot kind=""35"" offset=""7"" ordinal=""2"" />
<slot kind=""35"" offset=""7"" ordinal=""3"" />
<slot kind=""35"" offset=""7"" ordinal=""4"" />
<slot kind=""35"" offset=""7"" ordinal=""5"" />
<slot kind=""35"" offset=""7"" ordinal=""6"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""7"" />
<lambda offset=""92"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""27"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x50"" hidden=""true"" document=""1"" />
<entry offset=""0x59"" hidden=""true"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x85"" hidden=""true"" document=""1"" />
<entry offset=""0x87"" startLine=""7"" startColumn=""14"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x8b"" hidden=""true"" document=""1"" />
<entry offset=""0x8d"" startLine=""8"" startColumn=""46"" endLine=""8"" endColumn=""60"" document=""1"" />
<entry offset=""0xa1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""15"" document=""1"" />
<entry offset=""0xa5"" hidden=""true"" document=""1"" />
<entry offset=""0xa8"" startLine=""5"" startColumn=""23"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0xa9"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xab"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xab"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody_02()
{
string source = @"
using System;
public class C
{
static Action M1(int x) => () => { _ = x; };
static Action M2(int x) => x switch { _ => () => { _ = x; } };
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M1", sequencePoints: "C.M1", source: source, expectedIL: @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass0_0.x""
// sequence point: () => { _ = x; }
IL_000d: ldloc.0
IL_000e: ldftn ""void C.<>c__DisplayClass0_0.<M1>b__0()""
IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0019: ret
}
");
verifier.VerifyIL("C.M2", sequencePoints: "C.M2", source: source, expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
System.Action V_1)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass1_0.x""
// sequence point: x switch { _ => () => { _ = x; } }
IL_000d: ldc.i4.1
IL_000e: brtrue.s IL_0011
// sequence point: switch { _ => () => { _ = x; } }
IL_0010: nop
// sequence point: <hidden>
IL_0011: br.s IL_0013
// sequence point: () => { _ = x; }
IL_0013: ldloc.0
IL_0014: ldftn ""void C.<>c__DisplayClass1_0.<M2>b__0()""
IL_001a: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: br.s IL_0022
// sequence point: <hidden>
IL_0022: ldc.i4.1
IL_0023: brtrue.s IL_0026
// sequence point: x switch { _ => () => { _ = x; } }
IL_0025: nop
// sequence point: <hidden>
IL_0026: ldloc.1
IL_0027: ret
}
");
verifier.VerifyPdb("C.M1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M1"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""9"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
verifier.VerifyPdb("C.M2", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M2"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M1"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""25"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""34"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x13"" startLine=""6"" startColumn=""48"" endLine=""6"" endColumn=""64"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SyntaxOffset_OutVarInInitializers_SwitchExpression()
{
var source =
@"class C
{
static int G(out int x) => throw null;
static int F(System.Func<int> x) => throw null;
C() { }
int y1 = G(out var z) switch { _ => F(() => z) }; // line 7
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-26"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""-26"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-26"" />
<lambda offset=""-4"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x15"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""53"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x3e"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""10"" document=""1"" />
<entry offset=""0x3f"" startLine=""5"" startColumn=""11"" endLine=""5"" endColumn=""12"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<scope startOffset=""0x0"" endOffset=""0x37"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x37"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(43468, "https://github.com/dotnet/roslyn/issues/43468")]
[Fact]
public void HiddenSequencePointAtSwitchExpressionFinalMergePoint()
{
var source =
@"class C
{
static int M(int x)
{
var y = x switch
{
1 => 2,
_ => 3,
};
return y;
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (int V_0, //y
int V_1,
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: var y = x sw ... };
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
// sequence point: switch ... }
IL_0004: nop
// sequence point: <hidden>
IL_0005: ldarg.0
IL_0006: ldc.i4.1
IL_0007: beq.s IL_000b
IL_0009: br.s IL_000f
// sequence point: 2
IL_000b: ldc.i4.2
IL_000c: stloc.1
IL_000d: br.s IL_0013
// sequence point: 3
IL_000f: ldc.i4.3
IL_0010: stloc.1
IL_0011: br.s IL_0013
// sequence point: <hidden>
IL_0013: ldc.i4.1
IL_0014: brtrue.s IL_0017
// sequence point: var y = x sw ... };
IL_0016: nop
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stloc.0
// sequence point: return y;
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_001d
// sequence point: }
IL_001d: ldloc.2
IL_001e: ret
}
");
}
[WorkItem(12378, "https://github.com/dotnet/roslyn/issues/12378")]
[WorkItem(13971, "https://github.com/dotnet/roslyn/issues/13971")]
[Fact]
public void Patterns_SwitchStatement_Constant()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static void M(object o)
{
switch (o)
{
case 1 when o == null:
case 4:
case 2 when o == null:
break;
case 1 when o != null:
case 5:
case 3 when o != null:
break;
default:
break;
case 1:
break;
}
switch (o)
{
case 1:
break;
default:
break;
}
switch (o)
{
default:
break;
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
CompileAndVerify(c).VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source,
expectedIL: @"{
// Code size 123 (0x7b)
.maxstack 2
.locals init (object V_0,
int V_1,
object V_2,
object V_3,
int V_4,
object V_5,
object V_6,
object V_7)
// sequence point: {
IL_0000: nop
// sequence point: switch (o)
IL_0001: ldarg.0
IL_0002: stloc.2
// sequence point: <hidden>
IL_0003: ldloc.2
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: ldloc.0
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_004a
IL_000d: ldloc.0
IL_000e: unbox.any ""int""
IL_0013: stloc.1
// sequence point: <hidden>
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: sub
IL_0017: switch (
IL_0032,
IL_0037,
IL_0043,
IL_003c,
IL_0048)
IL_0030: br.s IL_004a
// sequence point: when o == null
IL_0032: ldarg.0
IL_0033: brfalse.s IL_003c
// sequence point: <hidden>
IL_0035: br.s IL_003e
// sequence point: when o == null
IL_0037: ldarg.0
IL_0038: brfalse.s IL_003c
// sequence point: <hidden>
IL_003a: br.s IL_004a
// sequence point: break;
IL_003c: br.s IL_004e
// sequence point: when o != null
IL_003e: ldarg.0
IL_003f: brtrue.s IL_0048
// sequence point: <hidden>
IL_0041: br.s IL_004c
// sequence point: when o != null
IL_0043: ldarg.0
IL_0044: brtrue.s IL_0048
// sequence point: <hidden>
IL_0046: br.s IL_004a
// sequence point: break;
IL_0048: br.s IL_004e
// sequence point: break;
IL_004a: br.s IL_004e
// sequence point: break;
IL_004c: br.s IL_004e
// sequence point: switch (o)
IL_004e: ldarg.0
IL_004f: stloc.s V_5
// sequence point: <hidden>
IL_0051: ldloc.s V_5
IL_0053: stloc.3
// sequence point: <hidden>
IL_0054: ldloc.3
IL_0055: isinst ""int""
IL_005a: brfalse.s IL_006d
IL_005c: ldloc.3
IL_005d: unbox.any ""int""
IL_0062: stloc.s V_4
// sequence point: <hidden>
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: beq.s IL_006b
IL_0069: br.s IL_006d
// sequence point: break;
IL_006b: br.s IL_006f
// sequence point: break;
IL_006d: br.s IL_006f
// sequence point: switch (o)
IL_006f: ldarg.0
IL_0070: stloc.s V_7
// sequence point: <hidden>
IL_0072: ldloc.s V_7
IL_0074: stloc.s V_6
// sequence point: <hidden>
IL_0076: br.s IL_0078
// sequence point: break;
IL_0078: br.s IL_007a
// sequence point: }
IL_007a: ret
}");
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""35"" offset=""378"" />
<slot kind=""35"" offset=""378"" ordinal=""1"" />
<slot kind=""1"" offset=""378"" />
<slot kind=""35"" offset=""511"" />
<slot kind=""1"" offset=""511"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""34"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x3e"" startLine=""11"" startColumn=""20"" endLine=""11"" endColumn=""34"" document=""1"" />
<entry offset=""0x41"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""13"" startColumn=""20"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x46"" hidden=""true"" document=""1"" />
<entry offset=""0x48"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""23"" document=""1"" />
<entry offset=""0x4a"" startLine=""16"" startColumn=""17"" endLine=""16"" endColumn=""23"" document=""1"" />
<entry offset=""0x4c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""23"" document=""1"" />
<entry offset=""0x4e"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x51"" hidden=""true"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""23"" document=""1"" />
<entry offset=""0x6d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" />
<entry offset=""0x6f"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""19"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x76"" hidden=""true"" document=""1"" />
<entry offset=""0x78"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""23"" document=""1"" />
<entry offset=""0x7a"" startLine=""32"" startColumn=""5"" endLine=""32"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement_Tuple()
{
string source = WithWindowsLineBreaks(@"
public class C
{
static int F(int i)
{
switch (G())
{
case (1, 2): return 3;
default: return 0;
};
}
static (object, object) G() => (2, 3);
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
var cv = CompileAndVerify(c);
cv.VerifyIL("C.F", @"
{
// Code size 80 (0x50)
.maxstack 2
.locals init (System.ValueTuple<object, object> V_0,
object V_1,
int V_2,
object V_3,
int V_4,
System.ValueTuple<object, object> V_5,
int V_6)
IL_0000: nop
IL_0001: call ""System.ValueTuple<object, object> C.G()""
IL_0006: stloc.s V_5
IL_0008: ldloc.s V_5
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldfld ""object System.ValueTuple<object, object>.Item1""
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: isinst ""int""
IL_0018: brfalse.s IL_0048
IL_001a: ldloc.1
IL_001b: unbox.any ""int""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: ldc.i4.1
IL_0023: bne.un.s IL_0048
IL_0025: ldloc.0
IL_0026: ldfld ""object System.ValueTuple<object, object>.Item2""
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: isinst ""int""
IL_0032: brfalse.s IL_0048
IL_0034: ldloc.3
IL_0035: unbox.any ""int""
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: ldc.i4.2
IL_003f: beq.s IL_0043
IL_0041: br.s IL_0048
IL_0043: ldc.i4.3
IL_0044: stloc.s V_6
IL_0046: br.s IL_004d
IL_0048: ldc.i4.0
IL_0049: stloc.s V_6
IL_004b: br.s IL_004d
IL_004d: ldloc.s V_6
IL_004f: ret
}
");
c.VerifyPdb("C.F", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</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=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""8"" startColumn=""26"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x48"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0x4d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Tuples
[Fact]
public void SyntaxOffset_TupleDeconstruction()
{
var source = @"class C { int F() { (int a, (_, int c)) = (1, (2, 3)); return a + c; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""7"" />
<slot kind=""0"" offset=""18"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""69"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""70"" endLine=""1"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
<local name=""c"" il_index=""1"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestDeconstruction()
{
var source = @"
public class C
{
public static (int, int) F() => (1, 2);
public static void Main()
{
int x, y;
(x, y) = F();
System.Console.WriteLine(x + y);
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
// sequence point: {
IL_0000: nop
// sequence point: (x, y) = F();
IL_0001: call ""System.ValueTuple<int, int> C.F()""
IL_0006: dup
IL_0007: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_000c: stloc.0
IL_000d: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0012: stloc.1
// sequence point: System.Console.WriteLine(x + y);
IL_0013: ldloc.0
IL_0014: ldloc.1
IL_0015: add
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
// sequence point: }
IL_001c: ret
}
", sequencePoints: "C.Main", source: source);
}
[Fact]
public void SyntaxOffset_TupleParenthesized()
{
var source = @"class C { int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x10"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""103"" document=""1"" />
<entry offset=""0x31"" startLine=""1"" startColumn=""104"" endLine=""1"" endColumn=""105"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x33"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x33"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void SyntaxOffset_TupleVarDefined()
{
var source = @"class C { int F() { var x = (1, 2); return x.Item1 + x.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""36"" document=""1"" />
<entry offset=""0xa"" startLine=""1"" startColumn=""37"" endLine=""1"" endColumn=""62"" document=""1"" />
<entry offset=""0x1a"" startLine=""1"" startColumn=""63"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SyntaxOffset_TupleIgnoreDeconstructionIfVariableDeclared()
{
var source = @"class C { int F() { (int x, int y) a = (1, 2); return a.Item1 + a.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<tupleElementNames>
<local elementNames=""|x|y"" slotIndex=""0"" localName=""a"" scopeStart=""0x0"" scopeEnd=""0x0"" />
</tupleElementNames>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""47"" document=""1"" />
<entry offset=""0x9"" startLine=""1"" startColumn=""48"" endLine=""1"" endColumn=""73"" document=""1"" />
<entry offset=""0x19"" startLine=""1"" startColumn=""74"" endLine=""1"" endColumn=""75"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region OutVar
[Fact]
public void SyntaxOffset_OutVarInConstructor()
{
var source = @"
class B
{
B(out int z) { z = 2; }
}
class C
{
int F = G(out var v1);
int P => G(out var v2);
C()
: base(out var v3)
{
G(out var v4);
}
int G(out int x)
{
x = 1;
return 2;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics(
// (9,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.G(out int)'
// int F = G(out var v1);
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "G").WithArguments("C.G(out int)").WithLocation(9, 13),
// (13,7): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// : base(out var v3)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(13, 7));
}
[Fact]
public void SyntaxOffset_OutVarInMethod()
{
var source = @"class C { int G(out int x) { int z = 1; G(out var y); G(out var w); return x = y; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""0"" offset=""23"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""28"" endLine=""1"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""30"" endLine=""1"" endColumn=""40"" document=""1"" />
<entry offset=""0x3"" startLine=""1"" startColumn=""41"" endLine=""1"" endColumn=""54"" document=""1"" />
<entry offset=""0xc"" startLine=""1"" startColumn=""55"" endLine=""1"" endColumn=""68"" document=""1"" />
<entry offset=""0x15"" startLine=""1"" startColumn=""69"" endLine=""1"" endColumn=""82"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""83"" endLine=""1"" endColumn=""84"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""w"" il_index=""2"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_01()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
int x = G(out var x);
int y {get;} = G(out var y);
C() : base(G(out var z))
{
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-36"" />
<slot kind=""0"" offset=""-22"" />
<slot kind=""0"" offset=""-3"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""32"" document=""1"" />
<entry offset=""0x1a"" startLine=""7"" startColumn=""11"" endLine=""7"" endColumn=""29"" document=""1"" />
<entry offset=""0x28"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""y"" il_index=""1"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a"" endOffset=""0x2a"">
<local name=""z"" il_index=""2"" il_start=""0x1a"" il_end=""0x2a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_02()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
{
int y = 1;
y++;
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""16"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""13"" document=""1"" />
<entry offset=""0x15"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x16"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x16"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_03()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
=> G(out var y);
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""13"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""8"" endLine=""5"" endColumn=""20"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x17"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x17"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x17"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x17"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_04()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
C()
{
}
#line 2000
int y1 = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""40"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x30"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x31"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x32"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass2_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_05()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 { get; } = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>5</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""23"" endLine=""2000"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x31"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass5_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass5_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""46"" endLine=""2000"" endColumn=""47"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_06()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 = G(out var z) + F(() => z), y2 = G(out var u) + F(() => u);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C..ctor", sequencePoints: "C..ctor", expectedIL: @"
{
// Code size 90 (0x5a)
.maxstack 4
.locals init (C.<>c__DisplayClass4_0 V_0, //CS$<>8__locals0
C.<>c__DisplayClass4_1 V_1) //CS$<>8__locals1
~IL_0000: newobj ""C.<>c__DisplayClass4_0..ctor()""
IL_0005: stloc.0
-IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass4_0.z""
IL_000d: call ""int C.G(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass4_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.F(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.y1""
~IL_0029: newobj ""C.<>c__DisplayClass4_1..ctor()""
IL_002e: stloc.1
-IL_002f: ldarg.0
IL_0030: ldloc.1
IL_0031: ldflda ""int C.<>c__DisplayClass4_1.u""
IL_0036: call ""int C.G(out int)""
IL_003b: ldloc.1
IL_003c: ldftn ""int C.<>c__DisplayClass4_1.<.ctor>b__1()""
IL_0042: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0047: call ""int C.F(System.Func<int>)""
IL_004c: add
IL_004d: stfld ""int C.y2""
IL_0052: ldarg.0
IL_0053: call ""object..ctor()""
IL_0058: nop
IL_0059: ret
}
");
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-52"" />
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<closure offset=""-52"" />
<closure offset=""-25"" />
<lambda offset=""-29"" closure=""0"" />
<lambda offset=""-2"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""39"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""2000"" startColumn=""41"" endLine=""2000"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x5a"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
<scope startOffset=""0x29"" endOffset=""0x52"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x29"" il_end=""0x52"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_1.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_1"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""69"" endLine=""2000"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_07()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
#line 2000
C() : base(G(out var z)+ F(() => z))
{
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""-1"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""-1"" />
<lambda offset=""-3"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""11"" endLine=""2000"" endColumn=""41"" document=""1"" />
<entry offset=""0x2a"" startLine=""2001"" startColumn=""5"" endLine=""2001"" endColumn=""6"" document=""1"" />
<entry offset=""0x2b"" startLine=""2002"" startColumn=""5"" endLine=""2002"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2c"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x2c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""38"" endLine=""2000"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_01()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
{
var q = from a in new [] {1}
where
G(out var x1) > a
select a;
}
static int G(out int x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""88"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""98"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""40"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""x1"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_02()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
#line 2000
{
var q = from a in new [] {1}
where
G(out var x1) > F(() => x1)
select a;
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""88"" />
<lambda offset=""88"" />
<lambda offset=""112"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""2001"" startColumn=""9"" endLine=""2004"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""2005"" startColumn=""5"" endLine=""2005"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""88"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2003"" startColumn=""23"" endLine=""2003"" endColumn=""50"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x25"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2003"" startColumn=""47"" endLine=""2003"" endColumn=""49"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInSwitchExpression()
{
var source = @"class C { static object G() => N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; static object N(out int x) { x = 1; return null; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""16"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""1"" startColumn=""64"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""1"" startColumn=""78"" endLine=""1"" endColumn=""79"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""86"" endLine=""1"" endColumn=""87"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x27"" startLine=""1"" startColumn=""62"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x2b"" startLine=""1"" startColumn=""96"" endLine=""1"" endColumn=""97"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
#endregion
[WorkItem(4370, "https://github.com/dotnet/roslyn/issues/4370")]
[Fact]
public void HeadingHiddenSequencePointsPickUpDocumentFromVisibleSequencePoint()
{
var source = WithWindowsLineBreaks(
@"#line 1 ""C:\Async.cs""
#pragma checksum ""C:\Async.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""DBEB2A067B2F0E0D678A002C587A2806056C3DCE""
using System.Threading.Tasks;
public class C
{
public async void M1()
{
}
}
");
var tree = SyntaxFactory.ParseSyntaxTree(source, encoding: Encoding.UTF8, path: "HIDDEN.cs");
var c = CSharpCompilation.Create("Compilation", new[] { tree }, new[] { MscorlibRef_v46 }, options: TestOptions.DebugDll.WithDebugPlusMode(true));
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
<file id=""2"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
</files>
<methods>
<method containingType=""C"" name=""M1"">
<customDebugInfo>
<forwardIterator name=""<M1>d__0"" />
</customDebugInfo>
</method>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
<file id=""2"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
</files>
<methods>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""2"" />
<entry offset=""0xa"" hidden=""true"" document=""2"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""2"" />
<entry offset=""0x2a"" hidden=""true"" document=""2"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(12923, "https://github.com/dotnet/roslyn/issues/12923")]
[Fact]
public void SequencePointsForConstructorWithHiddenInitializer()
{
string initializerSource = WithWindowsLineBreaks(@"
#line hidden
partial class C
{
int i = 42;
}
");
string constructorSource = WithWindowsLineBreaks(@"
partial class C
{
C()
{
}
}
");
var c = CreateCompilation(
new[] { Parse(initializerSource, "initializer.cs"), Parse(constructorSource, "constructor.cs") },
options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
<file id=""2"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
<file id=""2"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""2"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""2"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")]
[Fact]
public void LocalFunctionSequencePoints()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static int Main(string[] args)
{ // 4
int Local1(string[] a)
=>
a.Length; // 7
int Local2(string[] a)
{ // 9
return a.Length; // 10
} // 11
return Local1(args) + Local2(args); // 12
} // 13
}");
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=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""115"" />
<lambda offset=""202"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""44"" document=""1"" />
<entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local1|0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local2|0_1"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""202"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void SwitchInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
switch (i)
{
case 1:
break;
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (int V_0,
int V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: switch (i)
IL_000f: ldarg.0
IL_0010: ldarg.0
IL_0011: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0016: stloc.1
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stfld ""int Program.<Test>d__0.<>s__2""
// sequence point: <hidden>
IL_001d: ldarg.0
IL_001e: ldfld ""int Program.<Test>d__0.<>s__2""
IL_0023: ldc.i4.1
IL_0024: beq.s IL_0028
IL_0026: br.s IL_002a
// sequence point: break;
IL_0028: br.s IL_002a
// sequence point: <hidden>
IL_002a: leave.s IL_0044
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_002c: stloc.2
IL_002d: ldarg.0
IL_002e: ldc.i4.s -2
IL_0030: stfld ""int Program.<Test>d__0.<>1__state""
IL_0035: ldarg.0
IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_003b: ldloc.2
IL_003c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0041: nop
IL_0042: leave.s IL_0058
}
// sequence point: }
IL_0044: ldarg.0
IL_0045: ldc.i4.s -2
IL_0047: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_004c: ldarg.0
IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0052: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0057: nop
IL_0058: ret
}", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void WhileInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
while (i == 1)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 83 (0x53)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0017
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: while (i == 1)
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: ldc.i4.1
IL_001e: ceq
IL_0020: stloc.1
// sequence point: <hidden>
IL_0021: ldloc.1
IL_0022: brtrue.s IL_0011
IL_0024: leave.s IL_003e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldc.i4.s -2
IL_002a: stfld ""int Program.<Test>d__0.<>1__state""
IL_002f: ldarg.0
IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0035: ldloc.2
IL_0036: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_003b: nop
IL_003c: leave.s IL_0052
}
// sequence point: }
IL_003e: ldarg.0
IL_003f: ldc.i4.s -2
IL_0041: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0046: ldarg.0
IL_0047: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0051: nop
IL_0052: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = 0; i > 1; i--)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0027
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: i--
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: stloc.1
IL_001e: ldarg.0
IL_001f: ldloc.1
IL_0020: ldc.i4.1
IL_0021: sub
IL_0022: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0027: ldarg.0
IL_0028: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_002d: ldc.i4.1
IL_002e: cgt
IL_0030: stloc.2
// sequence point: <hidden>
IL_0031: ldloc.2
IL_0032: brtrue.s IL_0011
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.3
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.3
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForWithInnerLocalsInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = M(out var x); i > 1; i--)
Console.WriteLine();
}
public static int M(out int x) { x = 0; return 0; }
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = M(out var x)
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: ldflda ""int Program.<Test>d__0.<x>5__2""
IL_000f: call ""int Program.M(out int)""
IL_0014: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_0019: br.s IL_0031
// sequence point: Console.WriteLine();
IL_001b: call ""void System.Console.WriteLine()""
IL_0020: nop
// sequence point: i--
IL_0021: ldarg.0
IL_0022: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0027: stloc.1
IL_0028: ldarg.0
IL_0029: ldloc.1
IL_002a: ldc.i4.1
IL_002b: sub
IL_002c: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0031: ldarg.0
IL_0032: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0037: ldc.i4.1
IL_0038: cgt
IL_003a: stloc.2
// sequence point: <hidden>
IL_003b: ldloc.2
IL_003c: brtrue.s IL_001b
IL_003e: leave.s IL_0058
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0040: stloc.3
IL_0041: ldarg.0
IL_0042: ldc.i4.s -2
IL_0044: stfld ""int Program.<Test>d__0.<>1__state""
IL_0049: ldarg.0
IL_004a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004f: ldloc.3
IL_0050: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0055: nop
IL_0056: leave.s IL_006c
}
// sequence point: }
IL_0058: ldarg.0
IL_0059: ldc.i4.s -2
IL_005b: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0060: ldarg.0
IL_0061: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0066: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_006b: nop
IL_006c: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
public void InvalidCharacterInPdbPath()
{
using (var outStream = Temp.CreateFile().Open())
{
var compilation = CreateCompilation("");
var result = compilation.Emit(outStream, options: new EmitOptions(pdbFilePath: "test\\?.pdb", debugInformationFormat: DebugInformationFormat.Embedded));
// This is fine because EmitOptions just controls what is written into the PE file and it's
// valid for this to be an illegal file name (path map can easily create these).
Assert.True(result.Success);
}
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void FilesOneWithNoMethodBody()
{
string source1 = WithWindowsLineBreaks(@"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
");
string source2 = WithWindowsLineBreaks(@"
// no code
");
var tree1 = Parse(source1, "f:/build/goo.cs");
var tree2 = Parse(source2, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree1, tree2 }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/goo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""5D-7D-CF-1B-79-12-0E-0A-80-13-E0-98-7E-5C-AA-3B-63-D8-7E-4F"" />
<file id=""2"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void SingleFileWithNoMethodBody()
{
string source = WithWindowsLineBreaks(@"
// no code
");
var tree = Parse(source, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<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 System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBTests : CSharpPDBTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
#region General
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding1()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { }", encoding: null, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class C { }", encoding: null), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree("class D { }", encoding: Encoding.UTF8, path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify(
// Foo.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class A { }").WithLocation(1, 1),
// Bar.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class C { }").WithLocation(1, 1));
Assert.False(result.Success);
}
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding2()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { public void F() { } }", encoding: Encoding.Unicode, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { public void F() { } }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree("class C { public void F() { } }", encoding: new UTF8Encoding(true, false), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class D { public void F() { } }", new UTF8Encoding(false, false)), path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify();
Assert.True(result.Success);
var hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray();
var hash3 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(true, false).GetBytesWithPreamble(tree3.ToString())).ToArray();
var hash4 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(false, false).GetBytesWithPreamble(tree4.ToString())).ToArray();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""Foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash1) + @""" />
<file id=""2"" name="""" language=""C#"" />
<file id=""3"" name=""Bar.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash3) + @""" />
<file id=""4"" name=""Baz.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash4) + @""" />
</files>
</symbols>", options: PdbValidationOptions.ExcludeMethods);
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(WindowsOnly))]
public void RelativePathForExternalSource_Sha1_Windows()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""..\Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""..\Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"C:\Folder1\Folder2\Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""C:\Folder1\Folder2\Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""40-A6-20-02-2E-60-7D-4F-2D-A8-F4-A6-ED-2E-0E-49-8D-9F-D7-EB"" />
<file id=""2"" name=""C:\Folder1\Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(UnixLikeOnly))]
public void RelativePathForExternalSource_Sha1_Unix()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""../Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""../Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"/Folder1/Folder2/Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""/Folder1/Folder2/Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""82-08-07-BA-BA-52-02-D8-1D-1F-7C-E7-95-8A-6C-04-64-FF-50-31"" />
<file id=""2"" name=""/Folder1/Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors2()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'The version of Windows PDB writer is older than required: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterOlderVersionThanRequired, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors3()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll.WithDeterministic(true));
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Windows PDB writer doesn't support deterministic compilation: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterNotDeterministic, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors4()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => throw new DllNotFoundException("xxx") });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'xxx'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("xxx"));
Assert.False(result.Success);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressDynamicAndEncCDIForWinRT()
{
var source = @"
public class C
{
public static void F()
{
dynamic a = 1;
int b = 2;
foreach (var x in new[] { 1,2,3 })
{
System.Console.WriteLine(a * b);
}
}
}
";
var debug = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugWinMD);
debug.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0xb"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xe6"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xe7"" hidden=""true"" document=""1"" />
<entry offset=""0xeb"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xf4"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xf5"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<scope startOffset=""0x24"" endOffset=""0xe7"">
<local name=""x"" il_index=""4"" il_start=""0x24"" il_end=""0xe7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x9"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x26"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xdd"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xea"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xeb"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressTupleElementNamesCDIForWinRT()
{
var source =
@"class C
{
static void F()
{
(int A, int B) o = (1, 2);
}
}";
var debug = CreateCompilation(source, options: TestOptions.DebugWinMD);
debug.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""35"" document=""1"" />
<entry offset=""0x9"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void DuplicateDocuments()
{
var source1 = @"class C { static void F() { } }";
var source2 = @"class D { static void F() { } }";
var tree1 = Parse(source1, @"foo.cs");
var tree2 = Parse(source2, @"foo.cs");
var comp = CreateCompilation(new[] { tree1, tree2 });
// the first file wins (checksum CB 22 ...)
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""CB-22-D8-03-D3-27-32-64-2C-BC-7D-67-5D-E3-CB-AC-D1-64-25-83"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""D"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void CustomDebugEntryPoint_DLL()
{
var source = @"class C { static void F() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
Assert.Equal(0, peEntryPointToken);
}
[Fact]
public void CustomDebugEntryPoint_EXE()
{
var source = @"class M { static void Main() { } } class C { static void F<S>() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugExe);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
var mdReader = peReader.GetMetadataReader();
var methodDef = mdReader.GetMethodDefinition((MethodDefinitionHandle)MetadataTokens.Handle(peEntryPointToken));
Assert.Equal("Main", mdReader.GetString(methodDef.Name));
}
[Fact]
public void CustomDebugEntryPoint_Errors()
{
var source1 = @"class C { static void F() { } } class D<T> { static void G<S>() {} }";
var source2 = @"class C { static void F() { } }";
var c1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var c2 = CreateCompilation(source2, options: TestOptions.DebugDll);
var f1 = c1.GetMember<MethodSymbol>("C.F");
var f2 = c2.GetMember<MethodSymbol>("C.F");
var g = c1.GetMember<MethodSymbol>("D.G");
var d = c1.GetMember<NamedTypeSymbol>("D");
Assert.NotNull(f1);
Assert.NotNull(f2);
Assert.NotNull(g);
Assert.NotNull(d);
var stInt = c1.GetSpecialType(SpecialType.System_Int32);
var d_t_g_int = g.Construct(stInt);
var d_int = d.Construct(stInt);
var d_int_g = d_int.GetMember<MethodSymbol>("G");
var d_int_g_int = d_int_g.Construct(stInt);
var result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: f2.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_t_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
}
[Fact]
[WorkItem(768862, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/768862")]
public void TestLargeLineDelta()
{
var verbatim = string.Join("\r\n", Enumerable.Repeat("x", 1000));
var source = $@"
class C {{ public static void Main() => System.Console.WriteLine(@""{verbatim}""); }}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""2"" startColumn=""40"" endLine=""1001"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.PortablePdb);
// Native PDBs only support spans with line delta <= 127 (7 bit)
// https://github.com/Microsoft/microsoft-pdb/blob/main/include/cvinfo.h#L4621
c.VerifyPdb("C.Main", @"
<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=""2"" startColumn=""40"" endLine=""129"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_SameLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""5"" startColumn=""65533"" endLine=""5"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_DifferentLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(
""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""5"" startColumn=""65534"" endLine=""6"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
#endregion
#region Method Bodies
[Fact]
public void TestBasic()
{
var source = WithWindowsLineBreaks(@"
class Program
{
Program() { }
static void Main(string[] args)
{
Program p = new Program();
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Program"" methodName="".ctor"" />
<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=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""p"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSimpleLocals()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{ //local at method scope
object version = 6;
System.Console.WriteLine(""version {0}"", version);
{
//a scope that defines no locals
{
//a nested local
object foob = 1;
System.Console.WriteLine(""foob {0}"", foob);
}
{
//a nested local
int foob1 = 1;
System.Console.WriteLine(""foob1 {0}"", foob1);
}
System.Console.WriteLine(""Eva"");
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""44"" />
<slot kind=""0"" offset=""246"" />
<slot kind=""0"" offset=""402"" />
</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=""28"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""58"" document=""1"" />
<entry offset=""0x14"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""12"" startColumn=""17"" endLine=""12"" endColumn=""33"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""60"" document=""1"" />
<entry offset=""0x29"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x2a"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""17"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""62"" document=""1"" />
<entry offset=""0x3e"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x3f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x4a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x4b"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4c"">
<local name=""version"" il_index=""0"" il_start=""0x0"" il_end=""0x4c"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x2a"">
<local name=""foob"" il_index=""1"" il_start=""0x15"" il_end=""0x2a"" attributes=""0"" />
</scope>
<scope startOffset=""0x2a"" endOffset=""0x3f"">
<local name=""foob1"" il_index=""2"" il_start=""0x2a"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
public void ConstructorsWithoutInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<scope startOffset=""0x7"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""1"" />
<entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<scope startOffset=""0x7"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x7"" il_end=""0xb"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
[Fact]
public void ConstructorsWithInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
static object G = 1;
object F = G;
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x12"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<scope startOffset=""0x12"" endOffset=""0x14"">
<local name=""o"" il_index=""0"" il_start=""0x12"" il_end=""0x14"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""16"" document=""1"" />
<entry offset=""0x12"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<scope startOffset=""0x12"" endOffset=""0x16"">
<local name=""y"" il_index=""0"" il_start=""0x12"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Although the debugging info attached to DebuggerHidden method is not used by the debugger
/// (the debugger doesn't ever stop in the method) Dev11 emits the info and so do we.
///
/// StepThrough method needs the information if JustMyCode is disabled and a breakpoint is set within the method.
/// NonUserCode method needs the information if JustMyCode is disabled.
///
/// It's up to the tool that consumes the debugging information, not the compiler to decide whether to ignore the info or not.
/// BTW, the information can actually be retrieved at runtime from the PDB file via Reflection StackTrace.
/// </summary>
[Fact]
public void MethodsWithDebuggerAttributes()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.Diagnostics;
class Program
{
[DebuggerHidden]
static void Hidden()
{
int x = 1;
Console.WriteLine(x);
}
[DebuggerStepThrough]
static void StepThrough()
{
int y = 1;
Console.WriteLine(y);
}
[DebuggerNonUserCode]
static void NonUserCode()
{
int z = 1;
Console.WriteLine(z);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Hidden"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<namespace name=""System"" />
<namespace name=""System.Diagnostics"" />
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""StepThrough"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""NonUserCode"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
/// <summary>
/// If a synthesized method contains any user code,
/// the method must have a sequence point at
/// offset 0 for correct stepping behavior.
/// </summary>
[WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")]
[Fact]
public void SequencePointAtOffset0()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static Func<object, int> F = x =>
{
Func<object, int> f = o => 1;
Func<Func<object, int>, Func<object, int>> g = h => y => h(y);
return g(f)(null);
};
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-45"" />
<lambda offset=""-147"" />
<lambda offset=""-109"" />
<lambda offset=""-45"" />
<lambda offset=""-40"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""9"" endColumn=""7"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.cctor>b__3"" parameterNames=""y"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""66"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""-118"" />
<slot kind=""0"" offset=""-54"" />
<slot kind=""21"" offset=""-147"" />
</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=""38"" document=""1"" />
<entry offset=""0x21"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""71"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x51"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x53"">
<local name=""f"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
<local name=""g"" il_index=""1"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
</scope>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_1"" parameterNames=""o"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""36"" endLine=""6"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_2"" parameterNames=""h"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-45"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""7"" startColumn=""61"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading trivia is not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Methods()
{
string source = @"
class C
{
public static void Main1() /*Comment1*/{/*Comment2*/int a = 1;/*Comment3*/}/*Comment4*/
public static void Main2() {/*Comment2*/int a = 2;/*Comment3*/}/*Comment4*/
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that both syntax offsets are the same
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main1"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""44"" endLine=""4"" endColumn=""45"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""57"" endLine=""4"" endColumn=""67"" document=""1"" />
<entry offset=""0x3"" startLine=""4"" startColumn=""79"" endLine=""4"" endColumn=""80"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
<method containingType=""C"" name=""Main2"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""33"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""45"" endLine=""5"" endColumn=""55"" document=""1"" />
<entry offset=""0x3"" startLine=""5"" startColumn=""67"" endLine=""5"" endColumn=""68"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading and trailing trivia are not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Initializers()
{
string source = @"
using System;
class C1
{
public static Func<int> e=() => 0;
public static Func<int> f/*Comment0*/=/*Comment1*/() => 1;/*Comment2*/
public static Func<int> g=() => 2;
}
class C2
{
public static Func<int> e=() => 0;
public static Func<int> f=/*Comment1*/() => 1;
public static Func<int> g=() => 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that syntax offsets of both .cctor's are the same
c.VerifyPdb("C1..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C1"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""63"" document=""1"" />
<entry offset=""0x2a"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""39"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
c.VerifyPdb("C2..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C2"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""C1"" methodName="".cctor"" />
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""51"" document=""1"" />
<entry offset=""0x2a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Method1()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static int Main()
{
return 1;
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("Program.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</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=""18"" document=""1"" />
<entry offset=""0x5"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Property1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static int P
{
get { return 1; }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("C.P.get", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "C.get_P");
v.VerifyPdb("C.get_P", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""14"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""15"" endLine=""6"" endColumn=""24"" document=""1"" />
<entry offset=""0x5"" startLine=""6"" startColumn=""25"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Void1()
{
var source = @"
class Program
{
static void Main()
{
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 4 (0x4)
.maxstack 0
-IL_0000: nop
-IL_0001: br.s IL_0003
-IL_0003: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_ExpressionBodied1()
{
var source = @"
class Program
{
static int Main() => 1;
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 2 (0x2)
.maxstack 1
-IL_0000: ldc.i4.1
IL_0001: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_FromExceptionHandler1()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
static int Main()
{
try
{
Console.WriteLine();
return 1;
}
catch (Exception)
{
return 2;
}
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: call ""void System.Console.WriteLine()""
IL_0007: nop
-IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: leave.s IL_0012
}
catch System.Exception
{
-IL_000c: pop
-IL_000d: nop
-IL_000e: ldc.i4.2
IL_000f: stloc.0
IL_0010: leave.s IL_0012
}
-IL_0012: ldloc.0
IL_0013: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</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=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""33"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""22"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region IfStatement
[Fact]
public void IfStatement()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{
bool b = true;
if (b)
{
string s = ""true"";
System.Console.WriteLine(s);
}
else
{
string s = ""false"";
int i = 1;
while (i < 100)
{
int j = i, k = 1;
System.Console.WriteLine(j);
i = j + k;
}
i = i + 1;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""1"" offset=""38"" />
<slot kind=""0"" offset=""76"" />
<slot kind=""0"" offset=""188"" />
<slot kind=""0"" offset=""218"" />
<slot kind=""0"" offset=""292"" />
<slot kind=""0"" offset=""299"" />
<slot kind=""1"" offset=""240"" />
</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=""23"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x9"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""32"" document=""1"" />
<entry offset=""0x20"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""23"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x2a"" startLine=""19"" startColumn=""28"" endLine=""19"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x35"" startLine=""21"" startColumn=""17"" endLine=""21"" endColumn=""27"" document=""1"" />
<entry offset=""0x3c"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""14"" document=""1"" />
<entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x49"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""23"" document=""1"" />
<entry offset=""0x4f"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x50"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<local name=""b"" il_index=""0"" il_start=""0x0"" il_end=""0x51"" attributes=""0"" />
<scope startOffset=""0x8"" endOffset=""0x17"">
<local name=""s"" il_index=""2"" il_start=""0x8"" il_end=""0x17"" attributes=""0"" />
</scope>
<scope startOffset=""0x19"" endOffset=""0x50"">
<local name=""s"" il_index=""3"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<local name=""i"" il_index=""4"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<scope startOffset=""0x25"" endOffset=""0x3d"">
<local name=""j"" il_index=""5"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
<local name=""k"" il_index=""6"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region WhileStatement
[WorkItem(538299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538299")]
[Fact]
public void WhileStatement()
{
var source = @"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
while (p > 0) // SeqPt should be generated at the end of loop
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
int x = p;
field = x;
}
else
{
int x = p;
Console.WriteLine(x);
break;
}
}
field = -1;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Offset 0x01 should be:
// <entry offset=""0x1"" hidden=""true"" document=""1"" />
// Move original offset 0x01 to 0x33
// <entry offset=""0x33"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
//
// Note: 16707566 == 0x00FEEFEE
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""SeqPointForWhile"" methodName=""Main"" />
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0xf"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x10"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xc"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x13"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""27"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""27"" document=""1"" />
<entry offset=""0x1d"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""38"" document=""1"" />
<entry offset=""0x22"" startLine=""31"" startColumn=""17"" endLine=""31"" endColumn=""23"" document=""1"" />
<entry offset=""0x24"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
<entry offset=""0x28"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""20"" document=""1"" />
<entry offset=""0x2f"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x30"">
<scope startOffset=""0x11"" endOffset=""0x1a"">
<local name=""x"" il_index=""0"" il_start=""0x11"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForStatement
[Fact]
public void ForStatement1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static bool F(int i) { return true; }
static void G(int i) { }
static void M()
{
for (int i = 1; F(i); G(i))
{
System.Console.WriteLine(1);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""i"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" 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=""11"" startColumn=""13"" endLine=""11"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""9"" startColumn=""31"" endLine=""9"" endColumn=""35"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x20"">
<scope startOffset=""0x1"" endOffset=""0x1f"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x1f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForStatement2()
{
var source = @"
class C
{
static void M()
{
for (;;)
{
System.Console.WriteLine(1);
}
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForStatement3()
{
var source = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int i = 0;
for (;;i++)
{
System.Console.WriteLine(i);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</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=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x6"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForEachStatement
[Fact]
public void ForEachStatement_String()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var c in ""hello"")
{
System.Console.WriteLine(c);
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) '"hello"'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""34"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x23"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForEachStatement_Array()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static void Main()
{
foreach (var x in new int[2])
{
System.Console.WriteLine(x);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
</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=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""37"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x19"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""x"" il_index=""2"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArray()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new int[2, 3])
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2, 3]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 88 (0x58)
.maxstack 3
.locals init (int[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4,
int V_5) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: ldc.i4.2
IL_0003: ldc.i4.3
IL_0004: newobj ""int[*,*]..ctor""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.0
IL_000c: callvirt ""int System.Array.GetUpperBound(int)""
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldc.i4.1
IL_0014: callvirt ""int System.Array.GetUpperBound(int)""
IL_0019: stloc.2
IL_001a: ldloc.0
IL_001b: ldc.i4.0
IL_001c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0021: stloc.3
~IL_0022: br.s IL_0053
IL_0024: ldloc.0
IL_0025: ldc.i4.1
IL_0026: callvirt ""int System.Array.GetLowerBound(int)""
IL_002b: stloc.s V_4
~IL_002d: br.s IL_004a
-IL_002f: ldloc.0
IL_0030: ldloc.3
IL_0031: ldloc.s V_4
IL_0033: call ""int[*,*].Get""
IL_0038: stloc.s V_5
-IL_003a: nop
-IL_003b: ldloc.s V_5
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldloc.s V_4
IL_0046: ldc.i4.1
IL_0047: add
IL_0048: stloc.s V_4
-IL_004a: ldloc.s V_4
IL_004c: ldloc.2
IL_004d: ble.s IL_002f
~IL_004f: ldloc.3
IL_0050: ldc.i4.1
IL_0051: add
IL_0052: stloc.3
-IL_0053: ldloc.3
IL_0054: ldloc.1
IL_0055: ble.s IL_0024
-IL_0057: ret
}
", sequencePoints: "C.Main");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: <hidden>
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x51"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" 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=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x24"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalBeforeLocalFunction()
{
var source = @"
class C
{
void M()
{
int i = 0;
if (i != 0)
{
return;
}
string local()
{
throw null;
}
System.Console.Write(1);
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_000e
// sequence point: {
IL_000b: nop
// sequence point: return;
IL_000c: br.s IL_0016
// sequence point: <hidden>
IL_000e: nop
// sequence point: System.Console.Write(1);
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: nop
// sequence point: }
IL_0016: ret
}
", sequencePoints: "C.M", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethodWithExplicitReturn()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: return;
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInSimpleMethod()
{
var source = @"
using System;
class Program
{
public static void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_0011
// sequence point: Console.WriteLine();
IL_000b: call ""void System.Console.WriteLine()""
IL_0010: nop
// sequence point: }
IL_0011: ret
}
", sequencePoints: "Program.Test", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ElseConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine(""one"");
else
Console.WriteLine(""other"");
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0029
// sequence point: Console.WriteLine(""one"");
IL_001c: ldstr ""one""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: nop
// sequence point: <hidden>
IL_0027: br.s IL_0034
// sequence point: Console.WriteLine(""other"");
IL_0029: ldstr ""other""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: nop
// sequence point: <hidden>
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.2
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.2
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x63"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" 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=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""38"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""40"" document=""1"" />
<entry offset=""0x34"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x63"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x36"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInTry()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static void Test()
{
try
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
catch { }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
.try
{
// sequence point: {
IL_0001: nop
// sequence point: int i = 0;
IL_0002: ldc.i4.0
IL_0003: stloc.0
// sequence point: if (i != 0)
IL_0004: ldloc.0
IL_0005: ldc.i4.0
IL_0006: cgt.un
IL_0008: stloc.1
// sequence point: <hidden>
IL_0009: ldloc.1
IL_000a: brfalse.s IL_0012
// sequence point: Console.WriteLine();
IL_000c: call ""void System.Console.WriteLine()""
IL_0011: nop
// sequence point: }
IL_0012: nop
IL_0013: leave.s IL_001a
}
catch object
{
// sequence point: catch
IL_0015: pop
// sequence point: {
IL_0016: nop
// sequence point: }
IL_0017: nop
IL_0018: leave.s IL_001a
}
// sequence point: }
IL_001a: ret
}
", sequencePoints: "Program.Test", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""43"" />
<slot kind=""1"" offset=""65"" />
</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=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x4"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""37"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""15"" startColumn=""15"" endLine=""15"" endColumn=""16"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""17"" endLine=""15"" endColumn=""18"" document=""1"" />
<entry offset=""0x1a"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x13"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x13"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArrayBreakAndContinue()
{
var source = @"
using System;
class C
{
static void Main()
{
int[, ,] array = new[,,]
{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} },
};
foreach (int i in array)
{
if (i % 2 == 1) continue;
if (i > 4) break;
Console.WriteLine(i);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithModuleName("MODULE"));
// Stepping:
// After "continue", step to "in".
// After "break", step to first sequence point following loop body (in this case, method close brace).
v.VerifyIL("C.Main", @"
{
// Code size 169 (0xa9)
.maxstack 4
.locals init (int[,,] V_0, //array
int[,,] V_1,
int V_2,
int V_3,
int V_4,
int V_5,
int V_6,
int V_7,
int V_8, //i
bool V_9,
bool V_10)
-IL_0000: nop
-IL_0001: ldc.i4.2
IL_0002: ldc.i4.2
IL_0003: ldc.i4.2
IL_0004: newobj ""int[*,*,*]..ctor""
IL_0009: dup
IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>.8B4B2444E57AED8C2D05A1293255DA1B048C63224317D4666230760935FA4A18""
IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ldc.i4.0
IL_001a: callvirt ""int System.Array.GetUpperBound(int)""
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: callvirt ""int System.Array.GetUpperBound(int)""
IL_0027: stloc.3
IL_0028: ldloc.1
IL_0029: ldc.i4.2
IL_002a: callvirt ""int System.Array.GetUpperBound(int)""
IL_002f: stloc.s V_4
IL_0031: ldloc.1
IL_0032: ldc.i4.0
IL_0033: callvirt ""int System.Array.GetLowerBound(int)""
IL_0038: stloc.s V_5
~IL_003a: br.s IL_00a3
IL_003c: ldloc.1
IL_003d: ldc.i4.1
IL_003e: callvirt ""int System.Array.GetLowerBound(int)""
IL_0043: stloc.s V_6
~IL_0045: br.s IL_0098
IL_0047: ldloc.1
IL_0048: ldc.i4.2
IL_0049: callvirt ""int System.Array.GetLowerBound(int)""
IL_004e: stloc.s V_7
~IL_0050: br.s IL_008c
-IL_0052: ldloc.1
IL_0053: ldloc.s V_5
IL_0055: ldloc.s V_6
IL_0057: ldloc.s V_7
IL_0059: call ""int[*,*,*].Get""
IL_005e: stloc.s V_8
-IL_0060: nop
-IL_0061: ldloc.s V_8
IL_0063: ldc.i4.2
IL_0064: rem
IL_0065: ldc.i4.1
IL_0066: ceq
IL_0068: stloc.s V_9
~IL_006a: ldloc.s V_9
IL_006c: brfalse.s IL_0070
-IL_006e: br.s IL_0086
-IL_0070: ldloc.s V_8
IL_0072: ldc.i4.4
IL_0073: cgt
IL_0075: stloc.s V_10
~IL_0077: ldloc.s V_10
IL_0079: brfalse.s IL_007d
-IL_007b: br.s IL_00a8
-IL_007d: ldloc.s V_8
IL_007f: call ""void System.Console.WriteLine(int)""
IL_0084: nop
-IL_0085: nop
~IL_0086: ldloc.s V_7
IL_0088: ldc.i4.1
IL_0089: add
IL_008a: stloc.s V_7
-IL_008c: ldloc.s V_7
IL_008e: ldloc.s V_4
IL_0090: ble.s IL_0052
~IL_0092: ldloc.s V_6
IL_0094: ldc.i4.1
IL_0095: add
IL_0096: stloc.s V_6
-IL_0098: ldloc.s V_6
IL_009a: ldloc.3
IL_009b: ble.s IL_0047
~IL_009d: ldloc.s V_5
IL_009f: ldc.i4.1
IL_00a0: add
IL_00a1: stloc.s V_5
-IL_00a3: ldloc.s V_5
IL_00a5: ldloc.2
IL_00a6: ble.s IL_003c
-IL_00a8: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void ForEachStatement_Enumerator()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new System.Collections.Generic.List<int>())
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new System.Collections.Generic.List<int>()'
// 4) Hidden initial jump (of while loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) hidden point in Finally
// 11) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 59 (0x3b)
.maxstack 1
.locals init (System.Collections.Generic.List<int>.Enumerator V_0,
int V_1) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_0007: call ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()""
IL_000c: stloc.0
.try
{
~IL_000d: br.s IL_0020
-IL_000f: ldloca.s V_0
IL_0011: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get""
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: nop
-IL_001f: nop
-IL_0020: ldloca.s V_0
IL_0022: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()""
IL_0027: brtrue.s IL_000f
IL_0029: leave.s IL_003a
}
finally
{
~IL_002b: ldloca.s V_0
IL_002d: constrained. ""System.Collections.Generic.List<int>.Enumerator""
IL_0033: callvirt ""void System.IDisposable.Dispose()""
IL_0038: nop
IL_0039: endfinally
}
-IL_003a: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(718501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718501")]
[Fact]
public void ForEachNops()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
foreach (var i in l.AsEnumerable())
{
switch (i.Count)
{
case 1:
break;
default:
if (i.Count != 0)
{
}
break;
}
}
}
}
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<encLocalSlotMap>
<slot kind=""5"" offset=""15"" />
<slot kind=""0"" offset=""15"" />
<slot kind=""35"" offset=""83"" />
<slot kind=""1"" offset=""83"" />
<slot kind=""1"" offset=""237"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""20"" document=""1"" />
<entry offset=""0x2"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""47"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""12"" startColumn=""22"" endLine=""12"" endColumn=""27"" document=""1"" />
<entry offset=""0x1b"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""25"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""25"" endLine=""20"" endColumn=""42"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""21"" startColumn=""25"" endLine=""21"" endColumn=""26"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""25"" endLine=""22"" endColumn=""26"" document=""1"" />
<entry offset=""0x3e"" startLine=""24"" startColumn=""25"" endLine=""24"" endColumn=""31"" document=""1"" />
<entry offset=""0x40"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" document=""1"" />
<entry offset=""0x41"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x4b"" hidden=""true"" document=""1"" />
<entry offset=""0x55"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x57"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<namespace name=""System.Linq"" />
<scope startOffset=""0x14"" endOffset=""0x41"">
<local name=""i"" il_index=""1"" il_start=""0x14"" il_end=""0x41"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void ForEachStatement_Deconstruction()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void Main()
{
foreach (var (c, (d, e)) in F())
{
System.Console.WriteLine(c);
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //c
bool V_3, //d
double V_4, //e
System.ValueTuple<bool, double> V_5)
// sequence point: {
IL_0000: nop
// sequence point: foreach
IL_0001: nop
// sequence point: F()
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
// sequence point: <hidden>
IL_000a: br.s IL_003f
// sequence point: var (c, (d, e))
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
// sequence point: {
IL_0032: nop
// sequence point: System.Console.WriteLine(c);
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
// sequence point: }
IL_003a: nop
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
// sequence point: in
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
// sequence point: }
IL_0045: ret
}
", sequencePoints: "C.Main", source: source);
v.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""50"" endLine=""4"" endColumn=""76"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""25"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""32"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""40"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x32"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x3a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""34"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x45"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x46"">
<scope startOffset=""0xc"" endOffset=""0x3b"">
<local name=""c"" il_index=""2"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""d"" il_index=""3"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""e"" il_index=""4"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Switch
[Fact]
public void SwitchWithPattern_01()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static string Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""59"" />
<slot kind=""0"" offset=""163"" />
<slot kind=""0"" offset=""250"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x2e"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""57"" document=""1"" />
<entry offset=""0x4f"" hidden=""true"" document=""1"" />
<entry offset=""0x53"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""57"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x74"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""59"" document=""1"" />
<entry offset=""0x93"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""43"" document=""1"" />
<entry offset=""0xa7"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xaa"">
<scope startOffset=""0x1d"" endOffset=""0x4f"">
<local name=""s"" il_index=""0"" il_start=""0x1d"" il_end=""0x4f"" attributes=""0"" />
</scope>
<scope startOffset=""0x4f"" endOffset=""0x72"">
<local name=""s"" il_index=""1"" il_start=""0x4f"" il_end=""0x72"" attributes=""0"" />
</scope>
<scope startOffset=""0x72"" endOffset=""0x93"">
<local name=""t"" il_index=""2"" il_start=""0x72"" il_end=""0x93"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPattern_02()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return () => $""Teacher {t.Name} of {t.Subject}"";
default:
return () => $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""109"" closure=""1"" />
<lambda offset=""202"" closure=""1"" />
<lambda offset=""295"" closure=""1"" />
<lambda offset=""383"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x5f"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""63"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""63"" document=""1"" />
<entry offset=""0x8d"" hidden=""true"" document=""1"" />
<entry offset=""0x8f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""65"" document=""1"" />
<entry offset=""0x9f"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""49"" document=""1"" />
<entry offset=""0xaf"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb2"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb2"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xaf"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xaf"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPatternAndLocalFunctions()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
string f1() => $""Student {s.Name} ({s.GPA:N1})"";
return f1;
case Student s:
string f2() => $""Student {s.Name} ({s.GPA:N1})"";
return f2;
case Teacher t:
string f3() => $""Teacher {t.Name} of {t.Subject}"";
return f3;
default:
string f4() => $""Person {p.Name}"";
return f4;
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""111"" closure=""1"" />
<lambda offset=""234"" closure=""1"" />
<lambda offset=""357"" closure=""1"" />
<lambda offset=""475"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x60"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""27"" document=""1"" />
<entry offset=""0x8f"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""27"" document=""1"" />
<entry offset=""0xa2"" hidden=""true"" document=""1"" />
<entry offset=""0xa3"" startLine=""33"" startColumn=""17"" endLine=""33"" endColumn=""27"" document=""1"" />
<entry offset=""0xb3"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb6"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb6"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xb3"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xb3"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(17090, "https://github.com/dotnet/roslyn/issues/17090"), WorkItem(19731, "https://github.com/dotnet/roslyn/issues/19731")]
[Fact]
public void SwitchWithConstantPattern()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1();
M2();
}
static void M1()
{
switch
(1)
{
case 0 when true:
;
case 1:
Console.Write(1);
break;
case 2:
;
}
}
static void M2()
{
switch
(nameof(M2))
{
case nameof(M1) when true:
;
case nameof(M2):
Console.Write(nameof(M2));
break;
case nameof(Main):
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL(qualifiedMethodName: "Program.M1", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (int V_0,
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (1
IL_0001: ldc.i4.1
IL_0002: stloc.1
IL_0003: ldc.i4.1
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (string V_0,
string V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (nameof(M2)
IL_0001: ldstr ""M2""
IL_0006: stloc.1
IL_0007: ldstr ""M2""
IL_000c: stloc.0
// sequence point: <hidden>
IL_000d: br.s IL_000f
// sequence point: Console.Write(nameof(M2));
IL_000f: ldstr ""M2""
IL_0014: call ""void System.Console.Write(string)""
IL_0019: nop
// sequence point: break;
IL_001a: br.s IL_001c
// sequence point: }
IL_001c: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL("Program.M1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
verifier.VerifyIL("Program.M2",
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""M2""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_01()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1<int>(); // 1
M1<long>(); // 2
M2<string>(); // 3
M2<int>(); // 4
}
static void M1<T>()
{
switch (1)
{
case T t:
Console.Write(1);
break;
case int i:
Console.Write(2);
break;
}
}
static void M2<T>()
{
switch (nameof(M2))
{
case T t:
Console.Write(3);
break;
case string s:
Console.Write(4);
break;
case null:
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL(qualifiedMethodName: "Program.M1<T>", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 60 (0x3c)
.maxstack 1
.locals init (T V_0, //t
int V_1, //i
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (1)
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldc.i4.1
IL_0004: stloc.1
// sequence point: <hidden>
IL_0005: ldloc.1
IL_0006: box ""int""
IL_000b: isinst ""T""
IL_0010: brfalse.s IL_0030
IL_0012: ldloc.1
IL_0013: box ""int""
IL_0018: isinst ""T""
IL_001d: unbox.any ""T""
IL_0022: stloc.0
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: <hidden>
IL_0025: br.s IL_0027
// sequence point: Console.Write(1);
IL_0027: ldc.i4.1
IL_0028: call ""void System.Console.Write(int)""
IL_002d: nop
// sequence point: break;
IL_002e: br.s IL_003b
// sequence point: <hidden>
IL_0030: br.s IL_0032
// sequence point: Console.Write(2);
IL_0032: ldc.i4.2
IL_0033: call ""void System.Console.Write(int)""
IL_0038: nop
// sequence point: break;
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 58 (0x3a)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (nameof(M2))
IL_0001: ldstr ""M2""
IL_0006: stloc.2
IL_0007: ldstr ""M2""
IL_000c: stloc.1
// sequence point: <hidden>
IL_000d: ldloc.1
IL_000e: isinst ""T""
IL_0013: brfalse.s IL_002e
IL_0015: ldloc.1
IL_0016: isinst ""T""
IL_001b: unbox.any ""T""
IL_0020: stloc.0
// sequence point: <hidden>
IL_0021: br.s IL_0023
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: Console.Write(3);
IL_0025: ldc.i4.3
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: <hidden>
IL_002e: br.s IL_0030
// sequence point: Console.Write(4);
IL_0030: ldc.i4.4
IL_0031: call ""void System.Console.Write(int)""
IL_0036: nop
// sequence point: break;
IL_0037: br.s IL_0039
// sequence point: }
IL_0039: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL("Program.M1<T>",
@"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (int V_0) //i
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""int""
IL_0008: isinst ""T""
IL_000d: brfalse.s IL_0016
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldc.i4.2
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ret
}");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 28 (0x1c)
.maxstack 1
.locals init (string V_0) //s
IL_0000: ldstr ""M2""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: isinst ""T""
IL_000c: brfalse.s IL_0015
IL_000e: ldc.i4.3
IL_000f: call ""void System.Console.Write(int)""
IL_0014: ret
IL_0015: ldc.i4.4
IL_0016: call ""void System.Console.Write(int)""
IL_001b: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_02()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M2<string>(); // 6
M2<int>(); // 6
}
static void M2<T>()
{
const string x = null;
switch (x)
{
case T t:
;
case string s:
;
case null:
Console.Write(6);
break;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: switch (x)
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldnull
IL_0004: stloc.2
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(6);
IL_0007: ldc.i4.6
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.6
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
}
[Fact]
[WorkItem(31665, "https://github.com/dotnet/roslyn/issues/31665")]
public void TestSequencePoints_31665()
{
var source = @"
using System;
internal class Program
{
private static void Main(string[] args)
{
var s = ""1"";
if (true)
switch (s)
{
case ""1"":
Console.Out.WriteLine(""Input was 1"");
break;
default:
throw new Exception(""Default case"");
}
else
Console.Out.WriteLine(""Too many inputs"");
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main(string[])", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (string V_0, //s
bool V_1,
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: var s = ""1"";
IL_0001: ldstr ""1""
IL_0006: stloc.0
// sequence point: if (true)
IL_0007: ldc.i4.1
IL_0008: stloc.1
// sequence point: switch (s)
IL_0009: ldloc.0
IL_000a: stloc.3
// sequence point: <hidden>
IL_000b: ldloc.3
IL_000c: stloc.2
// sequence point: <hidden>
IL_000d: ldloc.2
IL_000e: ldstr ""1""
IL_0013: call ""bool string.op_Equality(string, string)""
IL_0018: brtrue.s IL_001c
IL_001a: br.s IL_002e
// sequence point: Console.Out.WriteLine(""Input was 1"");
IL_001c: call ""System.IO.TextWriter System.Console.Out.get""
IL_0021: ldstr ""Input was 1""
IL_0026: callvirt ""void System.IO.TextWriter.WriteLine(string)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: throw new Exception(""Default case"");
IL_002e: ldstr ""Default case""
IL_0033: newobj ""System.Exception..ctor(string)""
IL_0038: throw
// sequence point: <hidden>
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}
", sequencePoints: "Program.Main", source: source);
}
[Fact]
[WorkItem(17076, "https://github.com/dotnet/roslyn/issues/17076")]
public void TestSequencePoints_17076()
{
var source = @"
using System.Threading.Tasks;
internal class Program
{
private static void Main(string[] args)
{
M(new Node()).GetAwaiter().GetResult();
}
static async Task M(Node node)
{
while (node != null)
{
if (node is A a)
{
await Task.Yield();
return;
}
else if (node is B b)
{
await Task.Yield();
return;
}
node = node.Parent;
}
}
}
class Node
{
public Node Parent = null;
}
class A : Node { }
class B : Node { }
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 403 (0x193)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Program.<M>d__1 V_4,
bool V_5,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_6,
bool V_7,
System.Exception V_8)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<M>d__1.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_007e
IL_0014: br IL_0109
// sequence point: {
IL_0019: nop
// sequence point: <hidden>
IL_001a: br IL_0150
// sequence point: {
IL_001f: nop
// sequence point: if (node is A a)
IL_0020: ldarg.0
IL_0021: ldarg.0
IL_0022: ldfld ""Node Program.<M>d__1.node""
IL_0027: isinst ""A""
IL_002c: stfld ""A Program.<M>d__1.<a>5__1""
IL_0031: ldarg.0
IL_0032: ldfld ""A Program.<M>d__1.<a>5__1""
IL_0037: ldnull
IL_0038: cgt.un
IL_003a: stloc.1
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: brfalse.s IL_00a7
// sequence point: {
IL_003e: nop
// sequence point: await Task.Yield();
IL_003f: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0044: stloc.3
IL_0045: ldloca.s V_3
IL_0047: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_004c: stloc.2
// sequence point: <hidden>
IL_004d: ldloca.s V_2
IL_004f: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0054: brtrue.s IL_009a
IL_0056: ldarg.0
IL_0057: ldc.i4.0
IL_0058: dup
IL_0059: stloc.0
IL_005a: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_005f: ldarg.0
IL_0060: ldloc.2
IL_0061: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0066: ldarg.0
IL_0067: stloc.s V_4
IL_0069: ldarg.0
IL_006a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_006f: ldloca.s V_2
IL_0071: ldloca.s V_4
IL_0073: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0078: nop
IL_0079: leave IL_0192
// async: resume
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<M>d__1.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00a1: nop
// sequence point: return;
IL_00a2: leave IL_017e
// sequence point: if (node is B b)
IL_00a7: ldarg.0
IL_00a8: ldarg.0
IL_00a9: ldfld ""Node Program.<M>d__1.node""
IL_00ae: isinst ""B""
IL_00b3: stfld ""B Program.<M>d__1.<b>5__2""
IL_00b8: ldarg.0
IL_00b9: ldfld ""B Program.<M>d__1.<b>5__2""
IL_00be: ldnull
IL_00bf: cgt.un
IL_00c1: stloc.s V_5
// sequence point: <hidden>
IL_00c3: ldloc.s V_5
IL_00c5: brfalse.s IL_0130
// sequence point: {
IL_00c7: nop
// sequence point: await Task.Yield();
IL_00c8: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00cd: stloc.3
IL_00ce: ldloca.s V_3
IL_00d0: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00d5: stloc.s V_6
// sequence point: <hidden>
IL_00d7: ldloca.s V_6
IL_00d9: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00de: brtrue.s IL_0126
IL_00e0: ldarg.0
IL_00e1: ldc.i4.1
IL_00e2: dup
IL_00e3: stloc.0
IL_00e4: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_00e9: ldarg.0
IL_00ea: ldloc.s V_6
IL_00ec: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_00f1: ldarg.0
IL_00f2: stloc.s V_4
IL_00f4: ldarg.0
IL_00f5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_00fa: ldloca.s V_6
IL_00fc: ldloca.s V_4
IL_00fe: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0103: nop
IL_0104: leave IL_0192
// async: resume
IL_0109: ldarg.0
IL_010a: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_010f: stloc.s V_6
IL_0111: ldarg.0
IL_0112: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0117: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_011d: ldarg.0
IL_011e: ldc.i4.m1
IL_011f: dup
IL_0120: stloc.0
IL_0121: stfld ""int Program.<M>d__1.<>1__state""
IL_0126: ldloca.s V_6
IL_0128: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_012d: nop
// sequence point: return;
IL_012e: leave.s IL_017e
// sequence point: <hidden>
IL_0130: ldarg.0
IL_0131: ldnull
IL_0132: stfld ""B Program.<M>d__1.<b>5__2""
// sequence point: node = node.Parent;
IL_0137: ldarg.0
IL_0138: ldarg.0
IL_0139: ldfld ""Node Program.<M>d__1.node""
IL_013e: ldfld ""Node Node.Parent""
IL_0143: stfld ""Node Program.<M>d__1.node""
// sequence point: }
IL_0148: nop
IL_0149: ldarg.0
IL_014a: ldnull
IL_014b: stfld ""A Program.<M>d__1.<a>5__1""
// sequence point: while (node != null)
IL_0150: ldarg.0
IL_0151: ldfld ""Node Program.<M>d__1.node""
IL_0156: ldnull
IL_0157: cgt.un
IL_0159: stloc.s V_7
// sequence point: <hidden>
IL_015b: ldloc.s V_7
IL_015d: brtrue IL_001f
IL_0162: leave.s IL_017e
}
catch System.Exception
{
// sequence point: <hidden>
IL_0164: stloc.s V_8
IL_0166: ldarg.0
IL_0167: ldc.i4.s -2
IL_0169: stfld ""int Program.<M>d__1.<>1__state""
IL_016e: ldarg.0
IL_016f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_0174: ldloc.s V_8
IL_0176: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_017b: nop
IL_017c: leave.s IL_0192
}
// sequence point: }
IL_017e: ldarg.0
IL_017f: ldc.i4.s -2
IL_0181: stfld ""int Program.<M>d__1.<>1__state""
// sequence point: <hidden>
IL_0186: ldarg.0
IL_0187: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_018c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0191: nop
IL_0192: ret
}
", sequencePoints: "Program+<M>d__1.MoveNext", source: source);
}
[Fact]
[WorkItem(28288, "https://github.com/dotnet/roslyn/issues/28288")]
public void TestSequencePoints_28288()
{
var source = @"
using System.Threading.Tasks;
public class C
{
public static async Task Main()
{
object o = new C();
switch (o)
{
case C c:
System.Console.Write(1);
break;
default:
return;
}
if (M() != null)
{
}
}
private static object M()
{
return new C();
}
}";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 162 (0xa2)
.maxstack 2
.locals init (int V_0,
object V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: object o = new C();
IL_0008: ldarg.0
IL_0009: newobj ""C..ctor()""
IL_000e: stfld ""object C.<Main>d__0.<o>5__1""
// sequence point: switch (o)
IL_0013: ldarg.0
IL_0014: ldarg.0
IL_0015: ldfld ""object C.<Main>d__0.<o>5__1""
IL_001a: stloc.1
// sequence point: <hidden>
IL_001b: ldloc.1
IL_001c: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: <hidden>
IL_0021: ldarg.0
IL_0022: ldarg.0
IL_0023: ldfld ""object C.<Main>d__0.<>s__3""
IL_0028: isinst ""C""
IL_002d: stfld ""C C.<Main>d__0.<c>5__2""
IL_0032: ldarg.0
IL_0033: ldfld ""C C.<Main>d__0.<c>5__2""
IL_0038: brtrue.s IL_003c
IL_003a: br.s IL_0047
// sequence point: <hidden>
IL_003c: br.s IL_003e
// sequence point: System.Console.Write(1);
IL_003e: ldc.i4.1
IL_003f: call ""void System.Console.Write(int)""
IL_0044: nop
// sequence point: break;
IL_0045: br.s IL_0049
// sequence point: return;
IL_0047: leave.s IL_0086
// sequence point: <hidden>
IL_0049: ldarg.0
IL_004a: ldnull
IL_004b: stfld ""C C.<Main>d__0.<c>5__2""
IL_0050: ldarg.0
IL_0051: ldnull
IL_0052: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: if (M() != null)
IL_0057: call ""object C.M()""
IL_005c: ldnull
IL_005d: cgt.un
IL_005f: stloc.2
// sequence point: <hidden>
IL_0060: ldloc.2
IL_0061: brfalse.s IL_0065
// sequence point: {
IL_0063: nop
// sequence point: }
IL_0064: nop
// sequence point: <hidden>
IL_0065: leave.s IL_0086
}
catch System.Exception
{
// sequence point: <hidden>
IL_0067: stloc.3
IL_0068: ldarg.0
IL_0069: ldc.i4.s -2
IL_006b: stfld ""int C.<Main>d__0.<>1__state""
IL_0070: ldarg.0
IL_0071: ldnull
IL_0072: stfld ""object C.<Main>d__0.<o>5__1""
IL_0077: ldarg.0
IL_0078: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_007d: ldloc.3
IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0083: nop
IL_0084: leave.s IL_00a1
}
// sequence point: }
IL_0086: ldarg.0
IL_0087: ldc.i4.s -2
IL_0089: stfld ""int C.<Main>d__0.<>1__state""
// sequence point: <hidden>
IL_008e: ldarg.0
IL_008f: ldnull
IL_0090: stfld ""object C.<Main>d__0.<o>5__1""
IL_0095: ldarg.0
IL_0096: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a0: nop
IL_00a1: ret
}
", sequencePoints: "C+<Main>d__0.MoveNext", source: source);
}
[Fact]
public void SwitchExpressionWithPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
static string M(object o)
{
return o switch
{
int i => $""Number: {i}"",
_ => ""Don't know""
};
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""55"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x4"" startLine=""6"" startColumn=""18"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x2b"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x37"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3d"">
<scope startOffset=""0x16"" endOffset=""0x2b"">
<local name=""i"" il_index=""0"" il_start=""0x16"" il_end=""0x2b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region DoStatement
[Fact]
public void DoStatement()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
do
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
field = 1;
}
else
{
break;
}
} while (p > 0); // SeqPt should be generated for [while (p > 0);]
field = -1;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""28"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0x13"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""71"" />
<slot kind=""1"" offset=""159"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xd"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""26"" document=""1"" />
<entry offset=""0x13"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x24"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""14"" document=""1"" />
<entry offset=""0x28"" startLine=""28"" startColumn=""17"" endLine=""28"" endColumn=""23"" document=""1"" />
<entry offset=""0x2a"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" />
<entry offset=""0x2b"" startLine=""30"" startColumn=""11"" endLine=""30"" endColumn=""25"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""20"" document=""1"" />
<entry offset=""0x3a"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Constructor
[WorkItem(538317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538317")]
[Fact]
public void ConstructorSequencePoints1()
{
var source = WithWindowsLineBreaks(
@"namespace NS
{
public class MyClass
{
int intTest;
public MyClass()
{
intTest = 123;
}
public MyClass(params int[] values)
{
intTest = values[0] + values[1] + values[2];
}
public static int Main()
{
int intI = 1, intJ = 8;
int intK = 3;
// Can't step into Ctor
MyClass mc = new MyClass();
// Can't step into Ctor
mc = new MyClass(intI, intJ, intK);
return mc.intTest - 12;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Dev10 vs. Roslyn
//
// Default Ctor (no param)
// Dev10 Roslyn
// ======================================================================================
// Code size 18 (0x12) // Code size 16 (0x10)
// .maxstack 8 .maxstack 8
//* IL_0000: ldarg.0 *IL_0000: ldarg.0
// IL_0001: call IL_0001: callvirt
// instance void [mscorlib]System.Object::.ctor() instance void [mscorlib]System.Object::.ctor()
// IL_0006: nop *IL_0006: nop
//* IL_0007: nop
//* IL_0008: ldarg.0 *IL_0007: ldarg.0
// IL_0009: ldc.i4.s 123 IL_0008: ldc.i4.s 123
// IL_000b: stfld int32 NS.MyClass::intTest IL_000a: stfld int32 NS.MyClass::intTest
// IL_0010: nop
//* IL_0011: ret *IL_000f: ret
// -----------------------------------------------------------------------------------------
// SeqPoint: 0, 7 ,8, 0x10 0, 6, 7, 0xf
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""NS.MyClass"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""25"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name="".ctor"" parameterNames=""values"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""44"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""57"" document=""1"" />
<entry offset=""0x19"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name=""Main"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""56"" />
<slot kind=""0"" offset=""126"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""27"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0x5"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""40"" document=""1"" />
<entry offset=""0xd"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""48"" document=""1"" />
<entry offset=""0x25"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""36"" document=""1"" />
<entry offset=""0x32"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<local name=""intI"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intJ"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intK"" il_index=""2"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""mc"" il_index=""3"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ConstructorSequencePoints2()
{
TestSequencePoints(
@"using System;
class D
{
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class D
{
static D()
[|{|]
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D()
: [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class C { }
class D
{
[A]
[|public D()|]
{
}
}", TestOptions.DebugDll);
}
#endregion
#region Destructor
[Fact]
public void Destructors()
{
var source = @"
using System;
public class Base
{
~Base()
{
Console.WriteLine();
}
}
public class Derived : Base
{
~Derived()
{
Console.WriteLine();
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Base"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x13"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Derived"" name=""Finalize"">
<customDebugInfo>
<forward declaringType=""Base"" methodName=""Finalize"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Field and Property Initializers
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializers()
{
var text1 = WithWindowsLineBreaks(@"
public partial class C
{
int x = 1;
}
");
var text2 = WithWindowsLineBreaks(@"
public partial class C
{
int y = 1;
static void Main()
{
C c = new C();
}
}
");
// Having a unique name here may be important. The infrastructure of the pdb to xml conversion
// loads the assembly into the ReflectionOnlyLoadFrom context.
// So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new SyntaxTree[] { Parse(text1, "a.cs"), Parse(text2, "b.cs") });
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
<file id=""2"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializersWithLineDirectives()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int x = 1;
#line 12 ""foo.cs""
int z = Math.Abs(-3);
int w = Math.Abs(4);
#line 17 ""bar.cs""
double zed = Math.Sin(5);
}
#pragma checksum ""mah.cs"" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" ""ab007f1d23d9""
");
var text2 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int y = 1;
int x2 = 1;
#line 12 ""foo2.cs""
int z2 = Math.Abs(-3);
int w2 = Math.Abs(4);
}
");
var text3 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
#line 112 ""mah.cs""
int y3 = 1;
int x3 = 1;
int z3 = Math.Abs(-3);
#line default
int w3 = Math.Abs(4);
double zed3 = Math.Sin(5);
C() {
Console.WriteLine(""hi"");
}
static void Main()
{
C c = new C();
}
}
");
//Having a unique name here may be important. The infrastructure of the pdb to xml conversion
//loads the assembly into the ReflectionOnlyLoadFrom context.
//So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new[] { Parse(text1, "a.cs"), Parse(text2, "b.cs"), Parse(text3, "a.cs") }, options: TestOptions.DebugDll);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""E2-3B-47-02-DC-E4-8D-B4-FF-00-67-90-31-68-74-C0-06-D7-39-0E"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-CE-E5-E9-CB-53-E5-EF-C1-7F-2C-53-EC-02-FE-5C-34-2C-EF-94"" />
<file id=""3"" name=""foo.cs"" language=""C#"" />
<file id=""4"" name=""bar.cs"" language=""C#"" />
<file id=""5"" name=""foo2.cs"" language=""C#"" />
<file id=""6"" name=""mah.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""AB-00-7F-1D-23-D9"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""26"" document=""3"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""25"" document=""3"" />
<entry offset=""0x20"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""30"" document=""4"" />
<entry offset=""0x34"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""2"" />
<entry offset=""0x3b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""16"" document=""2"" />
<entry offset=""0x42"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""27"" document=""5"" />
<entry offset=""0x4f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""26"" document=""5"" />
<entry offset=""0x5b"" startLine=""112"" startColumn=""5"" endLine=""112"" endColumn=""16"" document=""6"" />
<entry offset=""0x62"" startLine=""113"" startColumn=""5"" endLine=""113"" endColumn=""16"" document=""6"" />
<entry offset=""0x69"" startLine=""114"" startColumn=""5"" endLine=""114"" endColumn=""27"" document=""6"" />
<entry offset=""0x76"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""26"" document=""1"" />
<entry offset=""0x82"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x96"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x9d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x9e"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0xa9"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(543313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543313")]
[Fact]
public void TestFieldInitializerExpressionLambda()
{
var source = @"
class C
{
int x = ((System.Func<int, int>)(z => z))(1);
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset=""-6"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""50"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__1_0"" parameterNames=""z"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""43"" endLine=""4"" endColumn=""44"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FieldInitializerSequencePointSpans()
{
var source = @"
class C
{
int x = 1, y = 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""14"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""16"" endLine=""4"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Auto-Property
[WorkItem(820806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820806")]
[Fact]
public void BreakpointForAutoImplementedProperty()
{
var source = @"
public class C
{
public static int AutoProp1 { get; private set; }
internal string AutoProp2 { get; set; }
internal protected C AutoProp3 { internal get; set; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_AutoProp1"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""35"" endLine=""4"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp1"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""40"" endLine=""4"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp2"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""33"" endLine=""5"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp2"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""38"" endLine=""5"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp3"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""38"" endLine=""6"" endColumn=""51"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp3"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""52"" endLine=""6"" endColumn=""56"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void PropertyDeclaration()
{
TestSequencePoints(
@"using System;
public class C
{
int P { [|get;|] set; }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; [|set;|] }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get [|{|] return 0; } }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; } = [|int.Parse(""42"")|];
}", TestOptions.DebugDll, TestOptions.Regular);
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Implicit()
{
var source = @"class C
{
static void Main()
{
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Explicit()
{
var source = @"class C
{
static void Main()
{
return;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<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=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(538298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538298")]
[Fact]
public void RegressSeqPtEndOfMethodAfterReturn()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointAfterReturn
{
public static int Main()
{
int ret = 0;
ReturnVoid(100);
if (field != ""Even"")
ret = 1;
ReturnVoid(99);
if (field != ""Odd"")
ret = ret + 1;
string rets = ReturnValue(101);
if (rets != ""Odd"")
ret = ret + 1;
rets = ReturnValue(102);
if (rets != ""Even"")
ret = ret + 1;
return ret;
}
static string field;
public static void ReturnVoid(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
field = ""Even"";
}
else
{
field = ""Odd"";
}
}
public static string ReturnValue(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
return ""Even"";
}
else
{
return ""Odd"";
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Expected are current actual output plus Two extra expected SeqPt:
// <entry offset=""0x73"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
// <entry offset=""0x22"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
//
// Note: NOT include other differences between Roslyn and Dev10, as they are filed in separated bugs
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointAfterReturn"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""204"" />
<slot kind=""1"" offset=""59"" />
<slot kind=""1"" offset=""138"" />
<slot kind=""1"" offset=""238"" />
<slot kind=""1"" offset=""330"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""21"" document=""1"" />
<entry offset=""0x20"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x28"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""28"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""27"" document=""1"" />
<entry offset=""0x3f"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""40"" document=""1"" />
<entry offset=""0x47"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""27"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x58"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""27"" document=""1"" />
<entry offset=""0x5c"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x64"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""28"" document=""1"" />
<entry offset=""0x71"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""27"" document=""1"" />
<entry offset=""0x79"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""20"" document=""1"" />
<entry offset=""0x7e"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x81"">
<namespace name=""System"" />
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
<local name=""rets"" il_index=""1"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnVoid"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""33"" startColumn=""13"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x18"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" />
<entry offset=""0x1c"" startLine=""37"" startColumn=""13"" endLine=""37"" endColumn=""27"" document=""1"" />
<entry offset=""0x26"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""39"" startColumn=""5"" endLine=""39"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnValue"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""42"" startColumn=""5"" endLine=""42"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""43"" startColumn=""9"" endLine=""43"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""45"" startColumn=""9"" endLine=""45"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""27"" document=""1"" />
<entry offset=""0x16"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""50"" startColumn=""13"" endLine=""50"" endColumn=""26"" document=""1"" />
<entry offset=""0x1f"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Exception Handling
[WorkItem(542064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542064")]
[Fact]
public void ExceptionHandling()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static int Main()
{
int ret = 0; // stop 1
try
{ // stop 2
throw new System.Exception(); // stop 3
}
catch (System.Exception e) // stop 4
{ // stop 5
ret = 1; // stop 6
}
try
{ // stop 7
throw new System.Exception(); // stop 8
}
catch // stop 9
{ // stop 10
return ret; // stop 11
}
}
}
");
// Dev12 inserts an additional sequence point on catch clause, just before
// the exception object is assigned to the variable. We don't place that sequence point.
// Also the scope of he exception variable is different.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""147"" />
<slot kind=""21"" offset=""0"" />
</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=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""42"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""35"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""42"" document=""1"" />
<entry offset=""0x19"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""24"" document=""1"" />
<entry offset=""0x1f"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<scope startOffset=""0xa"" endOffset=""0x11"">
<local name=""e"" il_index=""1"" il_start=""0xa"" il_end=""0x11"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug1()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class Test
{
static string filter(Exception e)
{
return null;
}
static void Main()
{
try
{
throw new InvalidOperationException();
}
catch (IOException e) when (filter(e) != null)
{
Console.WriteLine();
}
catch (Exception e) when (filter(e) != null)
{
Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0023
IL_0014: stloc.0
-IL_0015: ldloc.0
IL_0016: call ""string Test.filter(System.Exception)""
IL_001b: ldnull
IL_001c: cgt.un
IL_001e: stloc.1
~IL_001f: ldloc.1
IL_0020: ldc.i4.0
IL_0021: cgt.un
IL_0023: endfilter
} // end filter
{ // handler
~IL_0025: pop
-IL_0026: nop
-IL_0027: call ""void System.Console.WriteLine()""
IL_002c: nop
-IL_002d: nop
IL_002e: leave.s IL_0058
}
filter
{
~IL_0030: isinst ""System.Exception""
IL_0035: dup
IL_0036: brtrue.s IL_003c
IL_0038: pop
IL_0039: ldc.i4.0
IL_003a: br.s IL_004b
IL_003c: stloc.2
-IL_003d: ldloc.2
IL_003e: call ""string Test.filter(System.Exception)""
IL_0043: ldnull
IL_0044: cgt.un
IL_0046: stloc.3
~IL_0047: ldloc.3
IL_0048: ldc.i4.0
IL_0049: cgt.un
IL_004b: endfilter
} // end filter
{ // handler
~IL_004d: pop
-IL_004e: nop
-IL_004f: call ""void System.Console.WriteLine()""
IL_0054: nop
-IL_0055: nop
IL_0056: leave.s IL_0058
}
-IL_0058: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""filter"" parameterNames=""e"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""104"" />
<slot kind=""1"" offset=""120"" />
<slot kind=""0"" offset=""216"" />
<slot kind=""1"" offset=""230"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""51"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" startLine=""18"" startColumn=""31"" endLine=""18"" endColumn=""55"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""29"" endLine=""22"" endColumn=""53"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""10"" document=""1"" />
<entry offset=""0x4f"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""33"" document=""1"" />
<entry offset=""0x55"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x58"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x59"">
<scope startOffset=""0x8"" endOffset=""0x30"">
<local name=""e"" il_index=""0"" il_start=""0x8"" il_end=""0x30"" attributes=""0"" />
</scope>
<scope startOffset=""0x30"" endOffset=""0x58"">
<local name=""e"" il_index=""2"" il_start=""0x30"" il_end=""0x58"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug2()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static void Main()
{
try
{
throw new System.Exception();
}
catch when (F())
{
System.Console.WriteLine();
}
}
private static bool F()
{
return true;
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: call ""bool Test.F()""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""10"" startColumn=""15"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug3()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: ldsfld ""bool Test.a""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</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=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Release3()
{
var source = @"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll));
v.VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.try
{
-IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
filter
{
~IL_0006: pop
-IL_0007: ldsfld ""bool Test.a""
IL_000c: ldc.i4.0
IL_000d: cgt.un
IL_000f: endfilter
} // end filter
{ // handler
~IL_0011: pop
-IL_0012: call ""void System.Console.WriteLine()""
-IL_0017: leave.s IL_0019
}
-IL_0019: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x6"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(778655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778655")]
[Fact]
public void BranchToStartOfTry()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string str = null;
bool isEmpty = string.IsNullOrEmpty(str);
// isEmpty is always true here, so it should never go thru this if statement.
if (!isEmpty)
{
throw new Exception();
}
try
{
Console.WriteLine();
}
catch
{
}
}
}
");
// Note the hidden sequence point @IL_0019.
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=""18"" />
<slot kind=""0"" offset=""44"" />
<slot kind=""1"" offset=""177"" />
</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=""27"" document=""1"" />
<entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""50"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""22"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""35"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""33"" document=""1"" />
<entry offset=""0x21"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x24"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x29"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""str"" il_index=""0"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
<local name=""isEmpty"" il_index=""1"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region UsingStatement
[Fact]
public void UsingStatement_EmbeddedStatement()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass a = new DisposableClass(1), b = new DisposableClass(2))
System.Console.WriteLine(""First"");
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 53 (0x35)
.maxstack 1
.locals init (DisposableClass V_0, //a
DisposableClass V_1) //b
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass a = new DisposableClass(1)
IL_0001: ldc.i4.1
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: b = new DisposableClass(2)
IL_0008: ldc.i4.2
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: System.Console.WriteLine(""First"");
IL_000f: ldstr ""First""
IL_0014: call ""void System.Console.WriteLine(string)""
IL_0019: nop
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.1
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: <hidden>
IL_0027: leave.s IL_0034
}
finally
{
// sequence point: <hidden>
IL_0029: ldloc.0
IL_002a: brfalse.s IL_0033
IL_002c: ldloc.0
IL_002d: callvirt ""void System.IDisposable.Dispose()""
IL_0032: nop
// sequence point: <hidden>
IL_0033: endfinally
}
// sequence point: }
IL_0034: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""47"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<scope startOffset=""0x1"" endOffset=""0x34"">
<local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UsingStatement_Block()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass c = new DisposableClass(3), d = new DisposableClass(4))
{
System.Console.WriteLine(""Second"");
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 55 (0x37)
.maxstack 1
.locals init (DisposableClass V_0, //c
DisposableClass V_1) //d
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass c = new DisposableClass(3)
IL_0001: ldc.i4.3
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: d = new DisposableClass(4)
IL_0008: ldc.i4.4
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: {
IL_000f: nop
// sequence point: System.Console.WriteLine(""Second"");
IL_0010: ldstr ""Second""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: nop
// sequence point: }
IL_001b: nop
IL_001c: leave.s IL_0029
}
finally
{
// sequence point: <hidden>
IL_001e: ldloc.1
IL_001f: brfalse.s IL_0028
IL_0021: ldloc.1
IL_0022: callvirt ""void System.IDisposable.Dispose()""
IL_0027: nop
// sequence point: <hidden>
IL_0028: endfinally
}
// sequence point: <hidden>
IL_0029: leave.s IL_0036
}
finally
{
// sequence point: <hidden>
IL_002b: ldloc.0
IL_002c: brfalse.s IL_0035
IL_002e: ldloc.0
IL_002f: callvirt ""void System.IDisposable.Dispose()""
IL_0034: nop
// sequence point: <hidden>
IL_0035: endfinally
}
// sequence point: }
IL_0036: ret
}
"
);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x10"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""48"" document=""1"" />
<entry offset=""0x1b"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x28"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<scope startOffset=""0x1"" endOffset=""0x36"">
<local name=""c"" il_index=""0"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
<local name=""d"" il_index=""1"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
value = false;
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_0018
// sequence point: value = false;
IL_0016: ldc.i4.0
IL_0017: stloc.1
// sequence point: <hidden>
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.2
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.2
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: return value;
IL_0025: ldloc.1
IL_0026: stloc.s V_4
IL_0028: br.s IL_002a
// sequence point: }
IL_002a: ldloc.s V_4
IL_002c: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional2()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
{
value = false;
}
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 47 (0x2f)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_001a
// sequence point: {
IL_0016: nop
// sequence point: value = false;
IL_0017: ldc.i4.0
IL_0018: stloc.1
// sequence point: }
IL_0019: nop
// sequence point: <hidden>
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.2
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.2
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: return value;
IL_0027: ldloc.1
IL_0028: stloc.s V_4
IL_002a: br.s IL_002c
// sequence point: }
IL_002c: ldloc.s V_4
IL_002e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedWhile()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
while (x)
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: while (x)
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedFor()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
for ( ; x == true; )
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: x == true
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void LockStatement_EmbeddedIf()
{
var source = @"
class C
{
void F(bool x)
{
string y = """";
lock (y)
if (!x)
System.Console.Write(1);
else
System.Console.Write(2);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (string V_0, //y
string V_1,
bool V_2,
bool V_3)
// sequence point: {
IL_0000: nop
// sequence point: string y = """";
IL_0001: ldstr """"
IL_0006: stloc.0
// sequence point: lock (y)
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldc.i4.0
IL_000a: stloc.2
.try
{
IL_000b: ldloc.1
IL_000c: ldloca.s V_2
IL_000e: call ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_0013: nop
// sequence point: if (!x)
IL_0014: ldarg.1
IL_0015: ldc.i4.0
IL_0016: ceq
IL_0018: stloc.3
// sequence point: <hidden>
IL_0019: ldloc.3
IL_001a: brfalse.s IL_0025
// sequence point: System.Console.Write(1);
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.Write(int)""
IL_0022: nop
// sequence point: <hidden>
IL_0023: br.s IL_002c
// sequence point: System.Console.Write(2);
IL_0025: ldc.i4.2
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: <hidden>
IL_002c: leave.s IL_0039
}
finally
{
// sequence point: <hidden>
IL_002e: ldloc.2
IL_002f: brfalse.s IL_0038
IL_0031: ldloc.1
IL_0032: call ""void System.Threading.Monitor.Exit(object)""
IL_0037: nop
// sequence point: <hidden>
IL_0038: endfinally
}
// sequence point: }
IL_0039: ret
}
", sequencePoints: "C.F", source: source);
}
#endregion
#region Using Declaration
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static void Main()
{
using MemoryStream m = new MemoryStream(), n = new MemoryStream();
Console.WriteLine(1);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
System.IO.MemoryStream V_1) //n
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: n = new MemoryStream()
IL_0007: newobj ""System.IO.MemoryStream..ctor()""
IL_000c: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_000d: ldc.i4.1
IL_000e: call ""void System.Console.WriteLine(int)""
IL_0013: nop
// sequence point: }
IL_0014: leave.s IL_002c
}
finally
{
// sequence point: <hidden>
IL_0016: ldloc.1
IL_0017: brfalse.s IL_0020
IL_0019: ldloc.1
IL_001a: callvirt ""void System.IDisposable.Dispose()""
IL_001f: nop
// sequence point: <hidden>
IL_0020: endfinally
}
}
finally
{
// sequence point: <hidden>
IL_0021: ldloc.0
IL_0022: brfalse.s IL_002b
IL_0024: ldloc.0
IL_0025: callvirt ""void System.IDisposable.Dispose()""
IL_002a: nop
// sequence point: <hidden>
IL_002b: endfinally
}
// sequence point: }
IL_002c: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""0"" offset=""54"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""50"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""52"" endLine=""8"" endColumn=""74"" document=""1"" />
<entry offset=""0xd"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x14"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x20"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
<local name=""n"" il_index=""1"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScopeWithReturn()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static int Main()
{
using MemoryStream m = new MemoryStream();
Console.WriteLine(1);
return 1;
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream();
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: Console.WriteLine(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: nop
// sequence point: return 1;
IL_000e: ldc.i4.1
IL_000f: stloc.1
IL_0010: leave.s IL_001d
}
finally
{
// sequence point: <hidden>
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001c
IL_0015: ldloc.0
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
// sequence point: <hidden>
IL_001c: endfinally
}
// sequence point: }
IL_001d: ldloc.1
IL_001e: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""51"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0xe"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""18"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1f"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_IfBodyScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
public static bool G() => true;
static void Main()
{
if (G())
{
using var m = new MemoryStream();
Console.WriteLine(1);
}
Console.WriteLine(2);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// In this case the sequence point `}` is not emitted on the leave instruction,
// but to a nop instruction following the disposal.
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init (bool V_0,
System.IO.MemoryStream V_1) //m
// sequence point: {
IL_0000: nop
// sequence point: if (G())
IL_0001: call ""bool C.G()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0026
// sequence point: {
IL_000a: nop
// sequence point: using var m = new MemoryStream();
IL_000b: newobj ""System.IO.MemoryStream..ctor()""
IL_0010: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_0011: ldc.i4.1
IL_0012: call ""void System.Console.WriteLine(int)""
IL_0017: nop
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.1
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.1
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: }
IL_0025: nop
// sequence point: Console.WriteLine(2);
IL_0026: ldc.i4.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
// sequence point: }
IL_002d: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""11"" />
<slot kind=""0"" offset=""55"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""17"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""46"" document=""1"" />
<entry offset=""0x11"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""30"" document=""1"" />
<entry offset=""0x2d"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<scope startOffset=""0xa"" endOffset=""0x26"">
<local name=""m"" il_index=""1"" il_start=""0xa"" il_end=""0x26"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
// LockStatement tested in CodeGenLock
#region Anonymous Type
[Fact]
public void AnonymousType_Empty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new {};
}
}
");
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=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</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=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void AnonymousType_NonEmpty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new { a = 1 };
}
}
");
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=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</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=""31"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region FixedStatement
[Fact]
public void FixedStatementSingleAddress()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""9"" offset=""47"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""11"" startColumn=""16"" endLine=""11"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""20"" document=""1"" />
<entry offset=""0x15"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""32"" document=""1"" />
<entry offset=""0x25"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x26"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x19"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x19"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleString()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""9"" offset=""24"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""35"" document=""1"" />
<entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x21"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x21"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleArray()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
(*p)++;
}
Console.Write(c.a[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""79"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""28"" document=""1"" />
<entry offset=""0x32"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x39"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""1"" />
<entry offset=""0x4a"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4b"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x3c"">
<local name=""p"" il_index=""1"" il_start=""0x15"" il_end=""0x3c"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleAddresses()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.WriteLine(c.x + c.y);
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""0"" offset=""57"" />
<slot kind=""9"" offset=""47"" />
<slot kind=""9"" offset=""57"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x21"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""20"" document=""1"" />
<entry offset=""0x24"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""38"" document=""1"" />
<entry offset=""0x3f"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x40"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x2c"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleStrings()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"", q = ""goodbye"")
{
Console.Write(*p);
Console.Write(*q);
}
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""9"" offset=""24"" />
<slot kind=""9"" offset=""37"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x1b"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""48"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""31"" document=""1"" />
<entry offset=""0x32"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x3f"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
<local name=""q"" il_index=""1"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleArrays()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
int[] b = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
Console.Write(c.b[0]);
fixed (int* p = c.a, q = c.b)
{
*p = 1;
*q = 2;
}
Console.Write(c.a[0]);
Console.Write(c.b[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""111"" />
<slot kind=""0"" offset=""120"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""31"" document=""1"" />
<entry offset=""0x23"" startLine=""14"" startColumn=""16"" endLine=""14"" endColumn=""28"" document=""1"" />
<entry offset=""0x40"" startLine=""14"" startColumn=""30"" endLine=""14"" endColumn=""37"" document=""1"" />
<entry offset=""0x60"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x61"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""20"" document=""1"" />
<entry offset=""0x64"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x67"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" />
<entry offset=""0x68"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""31"" document=""1"" />
<entry offset=""0x7b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""31"" document=""1"" />
<entry offset=""0x89"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8a"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x8a"" attributes=""0"" />
<scope startOffset=""0x23"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0xc"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleMixed()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""48"" />
<slot kind=""0"" offset=""58"" />
<slot kind=""0"" offset=""67"" />
<slot kind=""9"" offset=""48"" />
<slot kind=""temp"" />
<slot kind=""9"" offset=""67"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x13"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""41"" endLine=""12"" endColumn=""52"" document=""1"" />
<entry offset=""0x49"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x4a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""36"" document=""1"" />
<entry offset=""0x52"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""36"" document=""1"" />
<entry offset=""0x5a"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""36"" document=""1"" />
<entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x63"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6e"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x6e"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""r"" il_index=""3"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""18"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""28"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Line Directives
[Fact]
public void LineDirective()
{
var source = @"
#line 50 ""foo.cs""
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""57"" startColumn=""9"" endLine=""57"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")]
[Fact]
public void DisabledLineDirective()
{
var source = @"
#if false
#line 50 ""foo.cs""
#endif
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestLineDirectivesHidden()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public class C
{
public void Foo()
{
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line hidden
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line default
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
}
}
");
var compilation = CreateCompilation(text1, options: TestOptions.DebugDll);
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Foo"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""6"" offset=""137"" />
<slot kind=""8"" offset=""137"" />
<slot kind=""0"" offset=""137"" />
<slot kind=""6"" offset=""264"" />
<slot kind=""8"" offset=""264"" />
<slot kind=""0"" offset=""264"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""23"" document=""1"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""7"" startColumn=""24"" endLine=""7"" endColumn=""26"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""1"" />
<entry offset=""0x65"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""51"" document=""1"" />
<entry offset=""0x7b"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""1"" />
<entry offset=""0x84"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""1"" />
<entry offset=""0x85"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""34"" document=""1"" />
<entry offset=""0x8d"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x8e"" hidden=""true"" document=""1"" />
<entry offset=""0x94"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x9c"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9d"">
<namespace name=""System"" />
<scope startOffset=""0x18"" endOffset=""0x25"">
<local name=""x"" il_index=""2"" il_start=""0x18"" il_end=""0x25"" attributes=""0"" />
</scope>
<scope startOffset=""0x47"" endOffset=""0x57"">
<local name=""x"" il_index=""5"" il_start=""0x47"" il_end=""0x57"" attributes=""0"" />
</scope>
<scope startOffset=""0x7d"" endOffset=""0x8e"">
<local name=""x"" il_index=""8"" il_start=""0x7d"" il_end=""0x8e"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenMethods()
{
var src = WithWindowsLineBreaks(@"
using System;
class C
{
#line hidden
public static void H()
{
F();
}
#line default
public static void G()
{
F();
}
#line hidden
public static void F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""64"" />
<slot kind=""0"" offset=""158"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenEntryPoint()
{
var src = @"
class C
{
#line hidden
public static void Main()
{
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe);
// Note: Dev10 emitted a hidden sequence point to #line hidden method,
// which enabled the debugger to locate the first user visible sequence point starting from the entry point.
// Roslyn does not emit such sequence point. We could potentially synthesize one but that would defeat the purpose of
// #line hidden directive.
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"" format=""windows"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
</method>
</methods>
</symbols>",
// When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method
// and thus there is no entry point record either.
options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void HiddenIterator()
{
var src = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class C
{
public static void Main()
{
F();
}
#line hidden
public static IEnumerable<int> F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
yield return 1;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
// We don't really need the debug info for kickoff method when the entire iterator method is hidden,
// but it doesn't hurt and removing it would need extra effort that's unnecessary.
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</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=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forwardIterator name=""<F>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""64"" />
<slot kind=""0"" offset=""158"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Nested Types
[Fact]
public void NestedTypes()
{
string source = WithWindowsLineBreaks(@"
using System;
namespace N
{
public class C
{
public class D<T>
{
public class E
{
public static void f(int a)
{
Console.WriteLine();
}
}
}
}
}
");
var c = CreateCompilation(Parse(source, filename: "file.cs"));
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""file.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""F7-03-46-2C-11-16-DE-85-F9-DD-5C-76-F6-55-D9-13-E0-95-DE-14"" />
</files>
<methods>
<method containingType=""N.C+D`1+E"" name=""f"" parameterNames=""a"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""6"" endLine=""14"" endColumn=""26"" document=""1"" />
<entry offset=""0x5"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Expression Bodied Members
[Fact]
public void ExpressionBodiedProperty()
{
var source = WithWindowsLineBreaks(@"
class C
{
public int P => M();
public int M()
{
return 2;
}
}");
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""21"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedIndexer()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int this[Int32 i] => M();
public int M()
{
return 2;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_Item"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""36"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_Item"" parameterNames=""i"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedMethod()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public Int32 P => 2;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""23"" endLine=""6"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedOperator()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public static C operator ++(C c) => c;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Increment"" parameterNames=""c"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""41"" endLine=""4"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedConversion()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public static explicit operator C(Int32 i) => new C();
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Explicit"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""51"" endLine=""6"" endColumn=""58"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedConstructor()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int X;
public C(Int32 x) => X = x;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""22"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""26"" endLine=""7"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xe"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedDestructor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int X;
~C() => X = 0;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""13"" endLine=""5"" endColumn=""18"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedAccessor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int x;
public int X
{
get => x;
set => x = value;
}
public event System.Action E
{
add => x = 1;
remove => x = 0;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_X"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""17"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_X"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""25"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""add_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""remove_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Synthesized Methods
[Fact]
public void ImportsInLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
System.Action f = () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
f();
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""63"" />
</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=""30"" document=""1"" />
<entry offset=""0x39"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInIterator()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static IEnumerable<object> F()
{
var c = new[] { 1, 2, 3 };
foreach (var i in c.Select(i => i))
{
yield return i;
}
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x27"" endOffset=""0xd5"" />
<slot />
<slot startOffset=""0x7f"" endOffset=""0xb6"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x28"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x40"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""43"" document=""1"" />
<entry offset=""0x7d"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x90"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x91"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""28"" document=""1"" />
<entry offset=""0xad"" hidden=""true"" document=""1"" />
<entry offset=""0xb5"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb6"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xd1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
<entry offset=""0xd5"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInAsync()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task F()
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x1f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""F"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")]
[Fact]
public void ImportsInAsyncLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
class C
{
static void M()
{
System.Action f = async () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forwardIterator name=""<<M>b__0_0>d"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""69"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
c.VerifyPdb("C+<>c+<<M>b__0_0>d.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c+<<M>b__0_0>d"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""50"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""39"" document=""1"" />
<entry offset=""0x1f"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x4c"" />
<kickoffMethod declaringType=""C+<>c"" methodName=""<M>b__0_0"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Patterns
[Fact]
public void SyntaxOffset_IsPattern()
{
var source = @"class C { bool F(object o) => o is int i && o is 3 && o is bool; }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""12"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""31"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static int Main()
{
switch (F())
{
// declaration pattern
case int x when G(x) > 10: return 1;
// discard pattern
case bool _: return 2;
// var pattern
case var (y, z): return 3;
// constant pattern
case 4.0: return 4;
// positional patterns
case C() when B(): return 5;
case (): return 6;
case C(int p, C(int q)): return 7;
case C(x: int p): return 8;
// property pattern
case D { P: 1, Q: D { P: 2 }, R: C(int z) }: return 9;
default: return 10;
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 448 (0x1c0)
.maxstack 3
.locals init (int V_0,
int V_1, //x
object V_2, //y
object V_3, //z
int V_4, //p
int V_5, //q
int V_6, //p
int V_7, //z
object V_8,
System.Runtime.CompilerServices.ITuple V_9,
int V_10,
double V_11,
C V_12,
object V_13,
C V_14,
D V_15,
int V_16,
D V_17,
int V_18,
C V_19,
object V_20,
int V_21)
// sequence point: {
IL_0000: nop
// sequence point: switch (F())
IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_20
// sequence point: <hidden>
IL_0008: ldloc.s V_20
IL_000a: stloc.s V_8
// sequence point: <hidden>
IL_000c: ldloc.s V_8
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_8
IL_0017: unbox.any ""int""
IL_001c: stloc.1
// sequence point: <hidden>
IL_001d: br IL_0150
IL_0022: ldloc.s V_8
IL_0024: isinst ""bool""
IL_0029: brtrue IL_0161
IL_002e: ldloc.s V_8
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_9
IL_0037: ldloc.s V_9
IL_0039: brfalse.s IL_0080
IL_003b: ldloc.s V_9
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_10
// sequence point: <hidden>
IL_0044: ldloc.s V_10
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0060
IL_0049: ldloc.s V_9
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.2
// sequence point: <hidden>
IL_0052: ldloc.s V_9
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.3
// sequence point: <hidden>
IL_005b: br IL_0166
IL_0060: ldloc.s V_8
IL_0062: isinst ""C""
IL_0067: brtrue IL_0172
IL_006c: br.s IL_0077
IL_006e: ldloc.s V_10
IL_0070: brfalse IL_019c
IL_0075: br.s IL_00b5
IL_0077: ldloc.s V_10
IL_0079: brfalse IL_019c
IL_007e: br.s IL_00f5
IL_0080: ldloc.s V_8
IL_0082: isinst ""double""
IL_0087: brfalse.s IL_00a7
IL_0089: ldloc.s V_8
IL_008b: unbox.any ""double""
IL_0090: stloc.s V_11
// sequence point: <hidden>
IL_0092: ldloc.s V_11
IL_0094: ldc.r8 4
IL_009d: beq IL_016d
IL_00a2: br IL_01b7
IL_00a7: ldloc.s V_8
IL_00a9: isinst ""C""
IL_00ae: brtrue IL_0176
IL_00b3: br.s IL_00f5
IL_00b5: ldloc.s V_8
IL_00b7: castclass ""C""
IL_00bc: stloc.s V_12
// sequence point: <hidden>
IL_00be: ldloc.s V_12
IL_00c0: ldloca.s V_4
IL_00c2: ldloca.s V_13
IL_00c4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00c9: nop
// sequence point: <hidden>
IL_00ca: ldloc.s V_13
IL_00cc: isinst ""C""
IL_00d1: stloc.s V_14
IL_00d3: ldloc.s V_14
IL_00d5: brfalse.s IL_00e6
IL_00d7: ldloc.s V_14
IL_00d9: ldloca.s V_5
IL_00db: callvirt ""void C.Deconstruct(out int)""
IL_00e0: nop
// sequence point: <hidden>
IL_00e1: br IL_01a1
IL_00e6: ldloc.s V_12
IL_00e8: ldloca.s V_6
IL_00ea: callvirt ""void C.Deconstruct(out int)""
IL_00ef: nop
// sequence point: <hidden>
IL_00f0: br IL_01a8
IL_00f5: ldloc.s V_8
IL_00f7: isinst ""D""
IL_00fc: stloc.s V_15
IL_00fe: ldloc.s V_15
IL_0100: brfalse IL_01b7
IL_0105: ldloc.s V_15
IL_0107: callvirt ""int D.P.get""
IL_010c: stloc.s V_16
// sequence point: <hidden>
IL_010e: ldloc.s V_16
IL_0110: ldc.i4.1
IL_0111: bne.un IL_01b7
IL_0116: ldloc.s V_15
IL_0118: callvirt ""D D.Q.get""
IL_011d: stloc.s V_17
// sequence point: <hidden>
IL_011f: ldloc.s V_17
IL_0121: brfalse IL_01b7
IL_0126: ldloc.s V_17
IL_0128: callvirt ""int D.P.get""
IL_012d: stloc.s V_18
// sequence point: <hidden>
IL_012f: ldloc.s V_18
IL_0131: ldc.i4.2
IL_0132: bne.un IL_01b7
IL_0137: ldloc.s V_15
IL_0139: callvirt ""C D.R.get""
IL_013e: stloc.s V_19
// sequence point: <hidden>
IL_0140: ldloc.s V_19
IL_0142: brfalse.s IL_01b7
IL_0144: ldloc.s V_19
IL_0146: ldloca.s V_7
IL_0148: callvirt ""void C.Deconstruct(out int)""
IL_014d: nop
// sequence point: <hidden>
IL_014e: br.s IL_01af
// sequence point: when G(x) > 10
IL_0150: ldloc.1
IL_0151: call ""int Program.G(int)""
IL_0156: ldc.i4.s 10
IL_0158: bgt.s IL_015c
// sequence point: <hidden>
IL_015a: br.s IL_01b7
// sequence point: return 1;
IL_015c: ldc.i4.1
IL_015d: stloc.s V_21
IL_015f: br.s IL_01bd
// sequence point: return 2;
IL_0161: ldc.i4.2
IL_0162: stloc.s V_21
IL_0164: br.s IL_01bd
// sequence point: <hidden>
IL_0166: br.s IL_0168
// sequence point: return 3;
IL_0168: ldc.i4.3
IL_0169: stloc.s V_21
IL_016b: br.s IL_01bd
// sequence point: return 4;
IL_016d: ldc.i4.4
IL_016e: stloc.s V_21
IL_0170: br.s IL_01bd
// sequence point: <hidden>
IL_0172: ldc.i4.1
IL_0173: stloc.0
IL_0174: br.s IL_017a
IL_0176: ldc.i4.2
IL_0177: stloc.0
IL_0178: br.s IL_017a
// sequence point: when B()
IL_017a: call ""bool Program.B()""
IL_017f: brtrue.s IL_0197
// sequence point: <hidden>
IL_0181: ldloc.0
IL_0182: ldc.i4.1
IL_0183: beq.s IL_018d
IL_0185: br.s IL_0187
IL_0187: ldloc.0
IL_0188: ldc.i4.2
IL_0189: beq.s IL_0192
IL_018b: br.s IL_0197
IL_018d: br IL_006e
IL_0192: br IL_00b5
// sequence point: return 5;
IL_0197: ldc.i4.5
IL_0198: stloc.s V_21
IL_019a: br.s IL_01bd
// sequence point: return 6;
IL_019c: ldc.i4.6
IL_019d: stloc.s V_21
IL_019f: br.s IL_01bd
// sequence point: <hidden>
IL_01a1: br.s IL_01a3
// sequence point: return 7;
IL_01a3: ldc.i4.7
IL_01a4: stloc.s V_21
IL_01a6: br.s IL_01bd
// sequence point: <hidden>
IL_01a8: br.s IL_01aa
// sequence point: return 8;
IL_01aa: ldc.i4.8
IL_01ab: stloc.s V_21
IL_01ad: br.s IL_01bd
// sequence point: <hidden>
IL_01af: br.s IL_01b1
// sequence point: return 9;
IL_01b1: ldc.i4.s 9
IL_01b3: stloc.s V_21
IL_01b5: br.s IL_01bd
// sequence point: return 10;
IL_01b7: ldc.i4.s 10
IL_01b9: stloc.s V_21
IL_01bb: br.s IL_01bd
// sequence point: }
IL_01bd: ldloc.s V_21
IL_01bf: ret
}
", source: source);
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""0"" offset=""93"" />
<slot kind=""0"" offset=""244"" />
<slot kind=""0"" offset=""247"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""474"" />
<slot kind=""0"" offset=""516"" />
<slot kind=""0"" offset=""617"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""35"" offset=""11"" ordinal=""5"" />
<slot kind=""35"" offset=""11"" ordinal=""6"" />
<slot kind=""35"" offset=""11"" ordinal=""7"" />
<slot kind=""35"" offset=""11"" ordinal=""8"" />
<slot kind=""35"" offset=""11"" ordinal=""9"" />
<slot kind=""35"" offset=""11"" ordinal=""10"" />
<slot kind=""35"" offset=""11"" ordinal=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
<entry offset=""0xbe"" hidden=""true"" document=""1"" />
<entry offset=""0xca"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" hidden=""true"" document=""1"" />
<entry offset=""0xf0"" hidden=""true"" document=""1"" />
<entry offset=""0x10e"" hidden=""true"" document=""1"" />
<entry offset=""0x11f"" hidden=""true"" document=""1"" />
<entry offset=""0x12f"" hidden=""true"" document=""1"" />
<entry offset=""0x140"" hidden=""true"" document=""1"" />
<entry offset=""0x14e"" hidden=""true"" document=""1"" />
<entry offset=""0x150"" startLine=""27"" startColumn=""24"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x15a"" hidden=""true"" document=""1"" />
<entry offset=""0x15c"" startLine=""27"" startColumn=""40"" endLine=""27"" endColumn=""49"" document=""1"" />
<entry offset=""0x161"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""35"" document=""1"" />
<entry offset=""0x166"" hidden=""true"" document=""1"" />
<entry offset=""0x168"" startLine=""33"" startColumn=""30"" endLine=""33"" endColumn=""39"" document=""1"" />
<entry offset=""0x16d"" startLine=""36"" startColumn=""23"" endLine=""36"" endColumn=""32"" document=""1"" />
<entry offset=""0x172"" hidden=""true"" document=""1"" />
<entry offset=""0x17a"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x181"" hidden=""true"" document=""1"" />
<entry offset=""0x197"" startLine=""39"" startColumn=""32"" endLine=""39"" endColumn=""41"" document=""1"" />
<entry offset=""0x19c"" startLine=""40"" startColumn=""22"" endLine=""40"" endColumn=""31"" document=""1"" />
<entry offset=""0x1a1"" hidden=""true"" document=""1"" />
<entry offset=""0x1a3"" startLine=""41"" startColumn=""38"" endLine=""41"" endColumn=""47"" document=""1"" />
<entry offset=""0x1a8"" hidden=""true"" document=""1"" />
<entry offset=""0x1aa"" startLine=""42"" startColumn=""31"" endLine=""42"" endColumn=""40"" document=""1"" />
<entry offset=""0x1af"" hidden=""true"" document=""1"" />
<entry offset=""0x1b1"" startLine=""45"" startColumn=""58"" endLine=""45"" endColumn=""67"" document=""1"" />
<entry offset=""0x1b7"" startLine=""47"" startColumn=""22"" endLine=""47"" endColumn=""32"" document=""1"" />
<entry offset=""0x1bd"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c0"">
<scope startOffset=""0x150"" endOffset=""0x161"">
<local name=""x"" il_index=""1"" il_start=""0x150"" il_end=""0x161"" attributes=""0"" />
</scope>
<scope startOffset=""0x166"" endOffset=""0x16d"">
<local name=""y"" il_index=""2"" il_start=""0x166"" il_end=""0x16d"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x166"" il_end=""0x16d"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a1"" endOffset=""0x1a8"">
<local name=""p"" il_index=""4"" il_start=""0x1a1"" il_end=""0x1a8"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x1a1"" il_end=""0x1a8"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a8"" endOffset=""0x1af"">
<local name=""p"" il_index=""6"" il_start=""0x1a8"" il_end=""0x1af"" attributes=""0"" />
</scope>
<scope startOffset=""0x1af"" endOffset=""0x1b7"">
<local name=""z"" il_index=""7"" il_start=""0x1af"" il_end=""0x1b7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchExpression()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static void Main()
{
var a = F() switch
{
// declaration pattern
int x when G(x) > 10 => 1,
// discard pattern
bool _ => 2,
// var pattern
var (y, z) => 3,
// constant pattern
4.0 => 4,
// positional patterns
C() when B() => 5,
() => 6,
C(int p, C(int q)) => 7,
C(x: int p) => 8,
// property pattern
D { P: 1, Q: D { P: 2 }, R: C (int z) } => 9,
_ => 10,
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
// note no sequence points emitted within the switch expression
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 454 (0x1c6)
.maxstack 3
.locals init (int V_0, //a
int V_1,
int V_2, //x
object V_3, //y
object V_4, //z
int V_5, //p
int V_6, //q
int V_7, //p
int V_8, //z
int V_9,
object V_10,
System.Runtime.CompilerServices.ITuple V_11,
int V_12,
double V_13,
C V_14,
object V_15,
C V_16,
D V_17,
int V_18,
D V_19,
int V_20,
C V_21)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_10
IL_0008: ldc.i4.1
IL_0009: brtrue.s IL_000c
-IL_000b: nop
~IL_000c: ldloc.s V_10
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_10
IL_0017: unbox.any ""int""
IL_001c: stloc.2
~IL_001d: br IL_0151
IL_0022: ldloc.s V_10
IL_0024: isinst ""bool""
IL_0029: brtrue IL_0162
IL_002e: ldloc.s V_10
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_11
IL_0037: ldloc.s V_11
IL_0039: brfalse.s IL_0081
IL_003b: ldloc.s V_11
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_12
~IL_0044: ldloc.s V_12
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0061
IL_0049: ldloc.s V_11
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.3
~IL_0052: ldloc.s V_11
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.s V_4
~IL_005c: br IL_0167
IL_0061: ldloc.s V_10
IL_0063: isinst ""C""
IL_0068: brtrue IL_0173
IL_006d: br.s IL_0078
IL_006f: ldloc.s V_12
IL_0071: brfalse IL_019d
IL_0076: br.s IL_00b6
IL_0078: ldloc.s V_12
IL_007a: brfalse IL_019d
IL_007f: br.s IL_00f6
IL_0081: ldloc.s V_10
IL_0083: isinst ""double""
IL_0088: brfalse.s IL_00a8
IL_008a: ldloc.s V_10
IL_008c: unbox.any ""double""
IL_0091: stloc.s V_13
~IL_0093: ldloc.s V_13
IL_0095: ldc.r8 4
IL_009e: beq IL_016e
IL_00a3: br IL_01b8
IL_00a8: ldloc.s V_10
IL_00aa: isinst ""C""
IL_00af: brtrue IL_0177
IL_00b4: br.s IL_00f6
IL_00b6: ldloc.s V_10
IL_00b8: castclass ""C""
IL_00bd: stloc.s V_14
~IL_00bf: ldloc.s V_14
IL_00c1: ldloca.s V_5
IL_00c3: ldloca.s V_15
IL_00c5: callvirt ""void C.Deconstruct(out int, out object)""
IL_00ca: nop
~IL_00cb: ldloc.s V_15
IL_00cd: isinst ""C""
IL_00d2: stloc.s V_16
IL_00d4: ldloc.s V_16
IL_00d6: brfalse.s IL_00e7
IL_00d8: ldloc.s V_16
IL_00da: ldloca.s V_6
IL_00dc: callvirt ""void C.Deconstruct(out int)""
IL_00e1: nop
~IL_00e2: br IL_01a2
IL_00e7: ldloc.s V_14
IL_00e9: ldloca.s V_7
IL_00eb: callvirt ""void C.Deconstruct(out int)""
IL_00f0: nop
~IL_00f1: br IL_01a9
IL_00f6: ldloc.s V_10
IL_00f8: isinst ""D""
IL_00fd: stloc.s V_17
IL_00ff: ldloc.s V_17
IL_0101: brfalse IL_01b8
IL_0106: ldloc.s V_17
IL_0108: callvirt ""int D.P.get""
IL_010d: stloc.s V_18
~IL_010f: ldloc.s V_18
IL_0111: ldc.i4.1
IL_0112: bne.un IL_01b8
IL_0117: ldloc.s V_17
IL_0119: callvirt ""D D.Q.get""
IL_011e: stloc.s V_19
~IL_0120: ldloc.s V_19
IL_0122: brfalse IL_01b8
IL_0127: ldloc.s V_19
IL_0129: callvirt ""int D.P.get""
IL_012e: stloc.s V_20
~IL_0130: ldloc.s V_20
IL_0132: ldc.i4.2
IL_0133: bne.un IL_01b8
IL_0138: ldloc.s V_17
IL_013a: callvirt ""C D.R.get""
IL_013f: stloc.s V_21
~IL_0141: ldloc.s V_21
IL_0143: brfalse.s IL_01b8
IL_0145: ldloc.s V_21
IL_0147: ldloca.s V_8
IL_0149: callvirt ""void C.Deconstruct(out int)""
IL_014e: nop
~IL_014f: br.s IL_01b0
-IL_0151: ldloc.2
IL_0152: call ""int Program.G(int)""
IL_0157: ldc.i4.s 10
IL_0159: bgt.s IL_015d
~IL_015b: br.s IL_01b8
-IL_015d: ldc.i4.1
IL_015e: stloc.s V_9
IL_0160: br.s IL_01be
-IL_0162: ldc.i4.2
IL_0163: stloc.s V_9
IL_0165: br.s IL_01be
~IL_0167: br.s IL_0169
-IL_0169: ldc.i4.3
IL_016a: stloc.s V_9
IL_016c: br.s IL_01be
-IL_016e: ldc.i4.4
IL_016f: stloc.s V_9
IL_0171: br.s IL_01be
~IL_0173: ldc.i4.1
IL_0174: stloc.1
IL_0175: br.s IL_017b
IL_0177: ldc.i4.2
IL_0178: stloc.1
IL_0179: br.s IL_017b
-IL_017b: call ""bool Program.B()""
IL_0180: brtrue.s IL_0198
~IL_0182: ldloc.1
IL_0183: ldc.i4.1
IL_0184: beq.s IL_018e
IL_0186: br.s IL_0188
IL_0188: ldloc.1
IL_0189: ldc.i4.2
IL_018a: beq.s IL_0193
IL_018c: br.s IL_0198
IL_018e: br IL_006f
IL_0193: br IL_00b6
-IL_0198: ldc.i4.5
IL_0199: stloc.s V_9
IL_019b: br.s IL_01be
-IL_019d: ldc.i4.6
IL_019e: stloc.s V_9
IL_01a0: br.s IL_01be
~IL_01a2: br.s IL_01a4
-IL_01a4: ldc.i4.7
IL_01a5: stloc.s V_9
IL_01a7: br.s IL_01be
~IL_01a9: br.s IL_01ab
-IL_01ab: ldc.i4.8
IL_01ac: stloc.s V_9
IL_01ae: br.s IL_01be
~IL_01b0: br.s IL_01b2
-IL_01b2: ldc.i4.s 9
IL_01b4: stloc.s V_9
IL_01b6: br.s IL_01be
-IL_01b8: ldc.i4.s 10
IL_01ba: stloc.s V_9
IL_01bc: br.s IL_01be
~IL_01be: ldc.i4.1
IL_01bf: brtrue.s IL_01c2
-IL_01c1: nop
~IL_01c2: ldloc.s V_9
IL_01c4: stloc.0
-IL_01c5: ret
}
");
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""temp"" />
<slot kind=""0"" offset=""94"" />
<slot kind=""0"" offset=""225"" />
<slot kind=""0"" offset=""228"" />
<slot kind=""0"" offset=""406"" />
<slot kind=""0"" offset=""415"" />
<slot kind=""0"" offset=""447"" />
<slot kind=""0"" offset=""539"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""23"" />
<slot kind=""35"" offset=""23"" ordinal=""1"" />
<slot kind=""35"" offset=""23"" ordinal=""2"" />
<slot kind=""35"" offset=""23"" ordinal=""3"" />
<slot kind=""35"" offset=""23"" ordinal=""4"" />
<slot kind=""35"" offset=""23"" ordinal=""5"" />
<slot kind=""35"" offset=""23"" ordinal=""6"" />
<slot kind=""35"" offset=""23"" ordinal=""7"" />
<slot kind=""35"" offset=""23"" ordinal=""8"" />
<slot kind=""35"" offset=""23"" ordinal=""9"" />
<slot kind=""35"" offset=""23"" ordinal=""10"" />
<slot kind=""35"" offset=""23"" ordinal=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0xb"" startLine=""24"" startColumn=""21"" endLine=""48"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5c"" hidden=""true"" document=""1"" />
<entry offset=""0x93"" hidden=""true"" document=""1"" />
<entry offset=""0xbf"" hidden=""true"" document=""1"" />
<entry offset=""0xcb"" hidden=""true"" document=""1"" />
<entry offset=""0xe2"" hidden=""true"" document=""1"" />
<entry offset=""0xf1"" hidden=""true"" document=""1"" />
<entry offset=""0x10f"" hidden=""true"" document=""1"" />
<entry offset=""0x120"" hidden=""true"" document=""1"" />
<entry offset=""0x130"" hidden=""true"" document=""1"" />
<entry offset=""0x141"" hidden=""true"" document=""1"" />
<entry offset=""0x14f"" hidden=""true"" document=""1"" />
<entry offset=""0x151"" startLine=""27"" startColumn=""19"" endLine=""27"" endColumn=""33"" document=""1"" />
<entry offset=""0x15b"" hidden=""true"" document=""1"" />
<entry offset=""0x15d"" startLine=""27"" startColumn=""37"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x162"" startLine=""30"" startColumn=""23"" endLine=""30"" endColumn=""24"" document=""1"" />
<entry offset=""0x167"" hidden=""true"" document=""1"" />
<entry offset=""0x169"" startLine=""33"" startColumn=""27"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x16e"" startLine=""36"" startColumn=""20"" endLine=""36"" endColumn=""21"" document=""1"" />
<entry offset=""0x173"" hidden=""true"" document=""1"" />
<entry offset=""0x17b"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" />
<entry offset=""0x182"" hidden=""true"" document=""1"" />
<entry offset=""0x198"" startLine=""39"" startColumn=""29"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x19d"" startLine=""40"" startColumn=""19"" endLine=""40"" endColumn=""20"" document=""1"" />
<entry offset=""0x1a2"" hidden=""true"" document=""1"" />
<entry offset=""0x1a4"" startLine=""41"" startColumn=""35"" endLine=""41"" endColumn=""36"" document=""1"" />
<entry offset=""0x1a9"" hidden=""true"" document=""1"" />
<entry offset=""0x1ab"" startLine=""42"" startColumn=""28"" endLine=""42"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b0"" hidden=""true"" document=""1"" />
<entry offset=""0x1b2"" startLine=""45"" startColumn=""56"" endLine=""45"" endColumn=""57"" document=""1"" />
<entry offset=""0x1b8"" startLine=""47"" startColumn=""18"" endLine=""47"" endColumn=""20"" document=""1"" />
<entry offset=""0x1be"" hidden=""true"" document=""1"" />
<entry offset=""0x1c1"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0x1c2"" hidden=""true"" document=""1"" />
<entry offset=""0x1c5"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c6"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1c6"" attributes=""0"" />
<scope startOffset=""0x151"" endOffset=""0x162"">
<local name=""x"" il_index=""2"" il_start=""0x151"" il_end=""0x162"" attributes=""0"" />
</scope>
<scope startOffset=""0x167"" endOffset=""0x16e"">
<local name=""y"" il_index=""3"" il_start=""0x167"" il_end=""0x16e"" attributes=""0"" />
<local name=""z"" il_index=""4"" il_start=""0x167"" il_end=""0x16e"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a2"" endOffset=""0x1a9"">
<local name=""p"" il_index=""5"" il_start=""0x1a2"" il_end=""0x1a9"" attributes=""0"" />
<local name=""q"" il_index=""6"" il_start=""0x1a2"" il_end=""0x1a9"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a9"" endOffset=""0x1b0"">
<local name=""p"" il_index=""7"" il_start=""0x1a9"" il_end=""0x1b0"" attributes=""0"" />
</scope>
<scope startOffset=""0x1b0"" endOffset=""0x1b8"">
<local name=""z"" il_index=""8"" il_start=""0x1b0"" il_end=""0x1b8"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_IsPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static bool M()
{
object obj = F();
return
// declaration pattern
obj is int x ||
// discard pattern
obj is bool _ ||
// var pattern
obj is var (y, z1) ||
// constant pattern
obj is 4.0 ||
// positional patterns
obj is C() ||
obj is () ||
obj is C(int p1, C(int q)) ||
obj is C(x: int p2) ||
// property pattern
obj is D { P: 1, Q: D { P: 2 }, R: C(int z2) };
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.M", sequencePoints: "Program.M", expectedIL: @"
{
// Code size 301 (0x12d)
.maxstack 3
.locals init (object V_0, //obj
int V_1, //x
object V_2, //y
object V_3, //z1
int V_4, //p1
int V_5, //q
int V_6, //p2
int V_7, //z2
System.Runtime.CompilerServices.ITuple V_8,
C V_9,
object V_10,
C V_11,
D V_12,
D V_13,
bool V_14)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.0
-IL_0007: ldloc.0
IL_0008: isinst ""int""
IL_000d: brfalse.s IL_001b
IL_000f: ldloc.0
IL_0010: unbox.any ""int""
IL_0015: stloc.1
IL_0016: br IL_0125
IL_001b: ldloc.0
IL_001c: isinst ""bool""
IL_0021: brtrue IL_0125
IL_0026: ldloc.0
IL_0027: isinst ""System.Runtime.CompilerServices.ITuple""
IL_002c: stloc.s V_8
IL_002e: ldloc.s V_8
IL_0030: brfalse.s IL_0053
IL_0032: ldloc.s V_8
IL_0034: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0039: ldc.i4.2
IL_003a: bne.un.s IL_0053
IL_003c: ldloc.s V_8
IL_003e: ldc.i4.0
IL_003f: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0044: stloc.2
IL_0045: ldloc.s V_8
IL_0047: ldc.i4.1
IL_0048: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_004d: stloc.3
IL_004e: br IL_0125
IL_0053: ldloc.0
IL_0054: isinst ""double""
IL_0059: brfalse.s IL_006f
IL_005b: ldloc.0
IL_005c: unbox.any ""double""
IL_0061: ldc.r8 4
IL_006a: beq IL_0125
IL_006f: ldloc.0
IL_0070: isinst ""C""
IL_0075: brtrue IL_0125
IL_007a: ldloc.0
IL_007b: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0080: stloc.s V_8
IL_0082: ldloc.s V_8
IL_0084: brfalse.s IL_0092
IL_0086: ldloc.s V_8
IL_0088: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_008d: brfalse IL_0125
IL_0092: ldloc.0
IL_0093: isinst ""C""
IL_0098: stloc.s V_9
IL_009a: ldloc.s V_9
IL_009c: brfalse.s IL_00c3
IL_009e: ldloc.s V_9
IL_00a0: ldloca.s V_4
IL_00a2: ldloca.s V_10
IL_00a4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00a9: nop
IL_00aa: ldloc.s V_10
IL_00ac: isinst ""C""
IL_00b1: stloc.s V_11
IL_00b3: ldloc.s V_11
IL_00b5: brfalse.s IL_00c3
IL_00b7: ldloc.s V_11
IL_00b9: ldloca.s V_5
IL_00bb: callvirt ""void C.Deconstruct(out int)""
IL_00c0: nop
IL_00c1: br.s IL_0125
IL_00c3: ldloc.0
IL_00c4: isinst ""C""
IL_00c9: stloc.s V_11
IL_00cb: ldloc.s V_11
IL_00cd: brfalse.s IL_00db
IL_00cf: ldloc.s V_11
IL_00d1: ldloca.s V_6
IL_00d3: callvirt ""void C.Deconstruct(out int)""
IL_00d8: nop
IL_00d9: br.s IL_0125
IL_00db: ldloc.0
IL_00dc: isinst ""D""
IL_00e1: stloc.s V_12
IL_00e3: ldloc.s V_12
IL_00e5: brfalse.s IL_0122
IL_00e7: ldloc.s V_12
IL_00e9: callvirt ""int D.P.get""
IL_00ee: ldc.i4.1
IL_00ef: bne.un.s IL_0122
IL_00f1: ldloc.s V_12
IL_00f3: callvirt ""D D.Q.get""
IL_00f8: stloc.s V_13
IL_00fa: ldloc.s V_13
IL_00fc: brfalse.s IL_0122
IL_00fe: ldloc.s V_13
IL_0100: callvirt ""int D.P.get""
IL_0105: ldc.i4.2
IL_0106: bne.un.s IL_0122
IL_0108: ldloc.s V_12
IL_010a: callvirt ""C D.R.get""
IL_010f: stloc.s V_11
IL_0111: ldloc.s V_11
IL_0113: brfalse.s IL_0122
IL_0115: ldloc.s V_11
IL_0117: ldloca.s V_7
IL_0119: callvirt ""void C.Deconstruct(out int)""
IL_011e: nop
IL_011f: ldc.i4.1
IL_0120: br.s IL_0123
IL_0122: ldc.i4.0
IL_0123: br.s IL_0126
IL_0125: ldc.i4.1
IL_0126: stloc.s V_14
IL_0128: br.s IL_012a
-IL_012a: ldloc.s V_14
IL_012c: ret
}
");
verifier.VerifyPdb("Program.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
<slot kind=""0"" offset=""106"" />
<slot kind=""0"" offset=""230"" />
<slot kind=""0"" offset=""233"" />
<slot kind=""0"" offset=""419"" />
<slot kind=""0"" offset=""429"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""561"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""25"" startColumn=""9"" endLine=""45"" endColumn=""60"" document=""1"" />
<entry offset=""0x12a"" startLine=""46"" startColumn=""5"" endLine=""46"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x12d"">
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""y"" il_index=""2"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z1"" il_index=""3"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p1"" il_index=""4"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p2"" il_index=""6"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z2"" il_index=""7"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(37232, "https://github.com/dotnet/roslyn/issues/37232")]
[WorkItem(37237, "https://github.com/dotnet/roslyn/issues/37237")]
[Fact]
public void Patterns_SwitchExpression_Closures()
{
string source = WithWindowsLineBreaks(@"
using System;
public class C
{
static int M()
{
return F() switch
{
1 => F() switch
{
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 10
},
2 => F() switch
{
C { P: int r } => G(() => r),
_ => 20
},
C { Q: int s } => G(() => s),
_ => 0
}
switch
{
var t when t > 0 => G(() => t),
_ => 0
};
}
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 472 (0x1d8)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
C.<>c__DisplayClass0_1 V_2, //CS$<>8__locals1
int V_3,
object V_4,
int V_5,
C V_6,
object V_7,
C.<>c__DisplayClass0_2 V_8, //CS$<>8__locals2
int V_9,
object V_10,
C V_11,
object V_12,
object V_13,
C V_14,
object V_15,
C.<>c__DisplayClass0_3 V_16, //CS$<>8__locals3
object V_17,
C V_18,
object V_19,
int V_20)
// sequence point: {
IL_0000: nop
// sequence point: <hidden>
IL_0001: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_000c: stloc.2
IL_000d: call ""object C.F()""
IL_0012: stloc.s V_4
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
// sequence point: switch ... }
IL_0017: nop
// sequence point: <hidden>
IL_0018: ldloc.s V_4
IL_001a: isinst ""int""
IL_001f: brfalse.s IL_003e
IL_0021: ldloc.s V_4
IL_0023: unbox.any ""int""
IL_0028: stloc.s V_5
// sequence point: <hidden>
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.1
IL_002d: beq.s IL_0075
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_5
IL_0033: ldc.i4.2
IL_0034: beq IL_0116
IL_0039: br IL_0194
IL_003e: ldloc.s V_4
IL_0040: isinst ""C""
IL_0045: stloc.s V_6
IL_0047: ldloc.s V_6
IL_0049: brfalse IL_0194
IL_004e: ldloc.s V_6
IL_0050: callvirt ""object C.Q.get""
IL_0055: stloc.s V_7
// sequence point: <hidden>
IL_0057: ldloc.s V_7
IL_0059: isinst ""int""
IL_005e: brfalse IL_0194
IL_0063: ldloc.2
IL_0064: ldloc.s V_7
IL_0066: unbox.any ""int""
IL_006b: stfld ""int C.<>c__DisplayClass0_1.<s>5__3""
// sequence point: <hidden>
IL_0070: br IL_017e
// sequence point: <hidden>
IL_0075: newobj ""C.<>c__DisplayClass0_2..ctor()""
IL_007a: stloc.s V_8
IL_007c: call ""object C.F()""
IL_0081: stloc.s V_10
IL_0083: ldc.i4.1
IL_0084: brtrue.s IL_0087
// sequence point: switch ...
IL_0086: nop
// sequence point: <hidden>
IL_0087: ldloc.s V_10
IL_0089: isinst ""C""
IL_008e: stloc.s V_11
IL_0090: ldloc.s V_11
IL_0092: brfalse.s IL_0104
IL_0094: ldloc.s V_11
IL_0096: callvirt ""object C.P.get""
IL_009b: stloc.s V_12
// sequence point: <hidden>
IL_009d: ldloc.s V_12
IL_009f: isinst ""int""
IL_00a4: brfalse.s IL_0104
IL_00a6: ldloc.s V_8
IL_00a8: ldloc.s V_12
IL_00aa: unbox.any ""int""
IL_00af: stfld ""int C.<>c__DisplayClass0_2.<p>5__4""
// sequence point: <hidden>
IL_00b4: ldloc.s V_11
IL_00b6: callvirt ""object C.Q.get""
IL_00bb: stloc.s V_13
// sequence point: <hidden>
IL_00bd: ldloc.s V_13
IL_00bf: isinst ""C""
IL_00c4: stloc.s V_14
IL_00c6: ldloc.s V_14
IL_00c8: brfalse.s IL_0104
IL_00ca: ldloc.s V_14
IL_00cc: callvirt ""object C.P.get""
IL_00d1: stloc.s V_15
// sequence point: <hidden>
IL_00d3: ldloc.s V_15
IL_00d5: isinst ""int""
IL_00da: brfalse.s IL_0104
IL_00dc: ldloc.s V_8
IL_00de: ldloc.s V_15
IL_00e0: unbox.any ""int""
IL_00e5: stfld ""int C.<>c__DisplayClass0_2.<q>5__5""
// sequence point: <hidden>
IL_00ea: br.s IL_00ec
// sequence point: <hidden>
IL_00ec: br.s IL_00ee
// sequence point: G(() => p + q)
IL_00ee: ldloc.s V_8
IL_00f0: ldftn ""int C.<>c__DisplayClass0_2.<M>b__2()""
IL_00f6: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_00fb: call ""int C.G(System.Func<int>)""
IL_0100: stloc.s V_9
IL_0102: br.s IL_010a
// sequence point: 10
IL_0104: ldc.i4.s 10
IL_0106: stloc.s V_9
IL_0108: br.s IL_010a
// sequence point: <hidden>
IL_010a: ldc.i4.1
IL_010b: brtrue.s IL_010e
// sequence point: switch ... }
IL_010d: nop
// sequence point: F() switch ...
IL_010e: ldloc.s V_9
IL_0110: stloc.3
IL_0111: br IL_0198
// sequence point: <hidden>
IL_0116: newobj ""C.<>c__DisplayClass0_3..ctor()""
IL_011b: stloc.s V_16
IL_011d: call ""object C.F()""
IL_0122: stloc.s V_17
IL_0124: ldc.i4.1
IL_0125: brtrue.s IL_0128
// sequence point: switch ...
IL_0127: nop
// sequence point: <hidden>
IL_0128: ldloc.s V_17
IL_012a: isinst ""C""
IL_012f: stloc.s V_18
IL_0131: ldloc.s V_18
IL_0133: brfalse.s IL_016f
IL_0135: ldloc.s V_18
IL_0137: callvirt ""object C.P.get""
IL_013c: stloc.s V_19
// sequence point: <hidden>
IL_013e: ldloc.s V_19
IL_0140: isinst ""int""
IL_0145: brfalse.s IL_016f
IL_0147: ldloc.s V_16
IL_0149: ldloc.s V_19
IL_014b: unbox.any ""int""
IL_0150: stfld ""int C.<>c__DisplayClass0_3.<r>5__6""
// sequence point: <hidden>
IL_0155: br.s IL_0157
// sequence point: <hidden>
IL_0157: br.s IL_0159
// sequence point: G(() => r)
IL_0159: ldloc.s V_16
IL_015b: ldftn ""int C.<>c__DisplayClass0_3.<M>b__3()""
IL_0161: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0166: call ""int C.G(System.Func<int>)""
IL_016b: stloc.s V_9
IL_016d: br.s IL_0175
// sequence point: 20
IL_016f: ldc.i4.s 20
IL_0171: stloc.s V_9
IL_0173: br.s IL_0175
// sequence point: <hidden>
IL_0175: ldc.i4.1
IL_0176: brtrue.s IL_0179
// sequence point: F() switch ...
IL_0178: nop
// sequence point: F() switch ...
IL_0179: ldloc.s V_9
IL_017b: stloc.3
IL_017c: br.s IL_0198
// sequence point: <hidden>
IL_017e: br.s IL_0180
// sequence point: G(() => s)
IL_0180: ldloc.2
IL_0181: ldftn ""int C.<>c__DisplayClass0_1.<M>b__1()""
IL_0187: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_018c: call ""int C.G(System.Func<int>)""
IL_0191: stloc.3
IL_0192: br.s IL_0198
// sequence point: 0
IL_0194: ldc.i4.0
IL_0195: stloc.3
IL_0196: br.s IL_0198
// sequence point: <hidden>
IL_0198: ldc.i4.1
IL_0199: brtrue.s IL_019c
// sequence point: return F() s ... };
IL_019b: nop
// sequence point: <hidden>
IL_019c: ldloc.0
IL_019d: ldloc.3
IL_019e: stfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01a3: ldc.i4.1
IL_01a4: brtrue.s IL_01a7
// sequence point: switch ... }
IL_01a6: nop
// sequence point: <hidden>
IL_01a7: br.s IL_01a9
// sequence point: when t > 0
IL_01a9: ldloc.0
IL_01aa: ldfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01af: ldc.i4.0
IL_01b0: bgt.s IL_01b4
// sequence point: <hidden>
IL_01b2: br.s IL_01c8
// sequence point: G(() => t)
IL_01b4: ldloc.0
IL_01b5: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_01bb: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_01c0: call ""int C.G(System.Func<int>)""
IL_01c5: stloc.1
IL_01c6: br.s IL_01cc
// sequence point: 0
IL_01c8: ldc.i4.0
IL_01c9: stloc.1
IL_01ca: br.s IL_01cc
// sequence point: <hidden>
IL_01cc: ldc.i4.1
IL_01cd: brtrue.s IL_01d0
// sequence point: return F() s ... };
IL_01cf: nop
// sequence point: <hidden>
IL_01d0: ldloc.1
IL_01d1: stloc.s V_20
IL_01d3: br.s IL_01d5
// sequence point: }
IL_01d5: ldloc.s V_20
IL_01d7: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""30"" offset=""22"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""22"" />
<slot kind=""35"" offset=""22"" ordinal=""1"" />
<slot kind=""35"" offset=""22"" ordinal=""2"" />
<slot kind=""35"" offset=""22"" ordinal=""3"" />
<slot kind=""30"" offset=""63"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""63"" />
<slot kind=""35"" offset=""63"" ordinal=""1"" />
<slot kind=""35"" offset=""63"" ordinal=""2"" />
<slot kind=""35"" offset=""63"" ordinal=""3"" />
<slot kind=""35"" offset=""63"" ordinal=""4"" />
<slot kind=""35"" offset=""63"" ordinal=""5"" />
<slot kind=""30"" offset=""238"" />
<slot kind=""35"" offset=""238"" />
<slot kind=""35"" offset=""238"" ordinal=""1"" />
<slot kind=""35"" offset=""238"" ordinal=""2"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<closure offset=""22"" />
<closure offset=""63"" />
<closure offset=""238"" />
<lambda offset=""511"" closure=""0"" />
<lambda offset=""407"" closure=""1"" />
<lambda offset=""157"" closure=""2"" />
<lambda offset=""313"" closure=""3"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x17"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x18"" hidden=""true"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" hidden=""true"" document=""1"" />
<entry offset=""0x86"" startLine=""9"" startColumn=""22"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x87"" hidden=""true"" document=""1"" />
<entry offset=""0x9d"" hidden=""true"" document=""1"" />
<entry offset=""0xb4"" hidden=""true"" document=""1"" />
<entry offset=""0xbd"" hidden=""true"" document=""1"" />
<entry offset=""0xd3"" hidden=""true"" document=""1"" />
<entry offset=""0xea"" hidden=""true"" document=""1"" />
<entry offset=""0xec"" hidden=""true"" document=""1"" />
<entry offset=""0xee"" startLine=""11"" startColumn=""59"" endLine=""11"" endColumn=""73"" document=""1"" />
<entry offset=""0x104"" startLine=""12"" startColumn=""27"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x10a"" hidden=""true"" document=""1"" />
<entry offset=""0x10d"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x10e"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x116"" hidden=""true"" document=""1"" />
<entry offset=""0x127"" startLine=""14"" startColumn=""22"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x128"" hidden=""true"" document=""1"" />
<entry offset=""0x13e"" hidden=""true"" document=""1"" />
<entry offset=""0x155"" hidden=""true"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""16"" startColumn=""40"" endLine=""16"" endColumn=""50"" document=""1"" />
<entry offset=""0x16f"" startLine=""17"" startColumn=""27"" endLine=""17"" endColumn=""29"" document=""1"" />
<entry offset=""0x175"" hidden=""true"" document=""1"" />
<entry offset=""0x178"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x179"" startLine=""14"" startColumn=""18"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x17e"" hidden=""true"" document=""1"" />
<entry offset=""0x180"" startLine=""19"" startColumn=""31"" endLine=""19"" endColumn=""41"" document=""1"" />
<entry offset=""0x194"" startLine=""20"" startColumn=""18"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19b"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x19c"" hidden=""true"" document=""1"" />
<entry offset=""0x1a6"" startLine=""22"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a7"" hidden=""true"" document=""1"" />
<entry offset=""0x1a9"" startLine=""24"" startColumn=""19"" endLine=""24"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b2"" hidden=""true"" document=""1"" />
<entry offset=""0x1b4"" startLine=""24"" startColumn=""33"" endLine=""24"" endColumn=""43"" document=""1"" />
<entry offset=""0x1c8"" startLine=""25"" startColumn=""18"" endLine=""25"" endColumn=""19"" document=""1"" />
<entry offset=""0x1cc"" hidden=""true"" document=""1"" />
<entry offset=""0x1cf"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x1d0"" hidden=""true"" document=""1"" />
<entry offset=""0x1d5"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1d8"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x1d5"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x1d5"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x1a3"">
<local name=""CS$<>8__locals1"" il_index=""2"" il_start=""0x7"" il_end=""0x1a3"" attributes=""0"" />
<scope startOffset=""0x75"" endOffset=""0x111"">
<local name=""CS$<>8__locals2"" il_index=""8"" il_start=""0x75"" il_end=""0x111"" attributes=""0"" />
</scope>
<scope startOffset=""0x116"" endOffset=""0x17c"">
<local name=""CS$<>8__locals3"" il_index=""16"" il_start=""0x116"" il_end=""0x17c"" attributes=""0"" />
</scope>
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_01()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static int F(object o)
{
return o switch
{
int i => new Func<int>(() => i + i switch
{
1 => 2,
_ => 3
})(),
_ => 4
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance int32 '<F>b__0' () cil managed
{
// Method begins at RVA 0x20ac
// Code size 38 (0x26)
.maxstack 2
.locals init (
[0] int32,
[1] int32
)
IL_0000: ldarg.0
IL_0001: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0011: ldc.i4.1
IL_0012: beq.s IL_0016
IL_0014: br.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.1
IL_0018: br.s IL_001e
IL_001a: ldc.i4.3
IL_001b: stloc.1
IL_001c: br.s IL_001e
IL_001e: ldc.i4.1
IL_001f: brtrue.s IL_0022
IL_0021: nop
IL_0022: ldloc.0
IL_0023: ldloc.1
IL_0024: add
IL_0025: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
int32 F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 69 (0x45)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] int32,
[2] int32
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance int32 C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<int32>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<int32>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003b
IL_0037: ldc.i4.4
IL_0038: stloc.1
IL_0039: br.s IL_003b
IL_003b: ldc.i4.1
IL_003c: brtrue.s IL_003f
IL_003e: nop
IL_003f: ldloc.1
IL_0040: stloc.2
IL_0041: br.s IL_0043
IL_0043: ldloc.2
IL_0044: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""80"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3e"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x45"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x43"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x43"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
<encLocalSlotMap>
<slot kind=""28"" offset=""86"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""48"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x1a"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_02()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static string F(object o)
{
return o switch
{
int i => new Func<string>(() => ""1"" + i switch
{
1 => new Func<string>(() => ""2"" + i)(),
_ => ""3""
})(),
_ => ""4""
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
.field public class [netstandard]System.Func`1<string> '<>9__1'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance string '<F>b__0' () cil managed
{
// Method begins at RVA 0x20b0
// Code size 78 (0x4e)
.maxstack 3
.locals init (
[0] string,
[1] class [netstandard]System.Func`1<string>
)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.0
IL_0005: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000a: ldc.i4.1
IL_000b: beq.s IL_000f
IL_000d: br.s IL_0036
IL_000f: ldarg.0
IL_0010: ldfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_0015: dup
IL_0016: brtrue.s IL_002e
IL_0018: pop
IL_0019: ldarg.0
IL_001a: ldarg.0
IL_001b: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__1'()
IL_0021: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_0026: dup
IL_0027: stloc.1
IL_0028: stfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_002d: ldloc.1
IL_002e: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0033: stloc.0
IL_0034: br.s IL_003e
IL_0036: ldstr ""3""
IL_003b: stloc.0
IL_003c: br.s IL_003e
IL_003e: ldc.i4.1
IL_003f: brtrue.s IL_0042
IL_0041: nop
IL_0042: ldstr ""1""
IL_0047: ldloc.0
IL_0048: call string [netstandard]System.String::Concat(string, string)
IL_004d: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
.method assembly hidebysig
instance string '<F>b__1' () cil managed
{
// Method begins at RVA 0x210a
// Code size 22 (0x16)
.maxstack 8
IL_0000: ldstr ""2""
IL_0005: ldarg.0
IL_0006: ldflda int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000b: call instance string [netstandard]System.Int32::ToString()
IL_0010: call string [netstandard]System.String::Concat(string, string)
IL_0015: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__1'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
string F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 73 (0x49)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] string,
[2] string
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003f
IL_0037: ldstr ""4""
IL_003c: stloc.1
IL_003d: br.s IL_003f
IL_003f: ldc.i4.1
IL_0040: brtrue.s IL_0043
IL_0042: nop
IL_0043: ldloc.1
IL_0044: stloc.2
IL_0045: br.s IL_0047
IL_0047: ldloc.2
IL_0048: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""83"" closure=""0"" />
<lambda offset=""158"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x42"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x43"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x49"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x47"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x47"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""53"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""55"" document=""1"" />
<entry offset=""0x36"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""25"" document=""1"" />
<entry offset=""0x3e"" hidden=""true"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x42"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody()
{
string source = @"
using System;
public class C
{
static int M() => F() switch
{
1 => 1,
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 0
};
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 171 (0xab)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
object V_2,
int V_3,
C V_4,
object V_5,
object V_6,
C V_7,
object V_8)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: call ""object C.F()""
IL_000b: stloc.2
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
// sequence point: switch ... }
IL_000f: nop
// sequence point: <hidden>
IL_0010: ldloc.2
IL_0011: isinst ""int""
IL_0016: brfalse.s IL_0025
IL_0018: ldloc.2
IL_0019: unbox.any ""int""
IL_001e: stloc.3
// sequence point: <hidden>
IL_001f: ldloc.3
IL_0020: ldc.i4.1
IL_0021: beq.s IL_0087
IL_0023: br.s IL_00a1
IL_0025: ldloc.2
IL_0026: isinst ""C""
IL_002b: stloc.s V_4
IL_002d: ldloc.s V_4
IL_002f: brfalse.s IL_00a1
IL_0031: ldloc.s V_4
IL_0033: callvirt ""object C.P.get""
IL_0038: stloc.s V_5
// sequence point: <hidden>
IL_003a: ldloc.s V_5
IL_003c: isinst ""int""
IL_0041: brfalse.s IL_00a1
IL_0043: ldloc.0
IL_0044: ldloc.s V_5
IL_0046: unbox.any ""int""
IL_004b: stfld ""int C.<>c__DisplayClass0_0.<p>5__2""
// sequence point: <hidden>
IL_0050: ldloc.s V_4
IL_0052: callvirt ""object C.Q.get""
IL_0057: stloc.s V_6
// sequence point: <hidden>
IL_0059: ldloc.s V_6
IL_005b: isinst ""C""
IL_0060: stloc.s V_7
IL_0062: ldloc.s V_7
IL_0064: brfalse.s IL_00a1
IL_0066: ldloc.s V_7
IL_0068: callvirt ""object C.P.get""
IL_006d: stloc.s V_8
// sequence point: <hidden>
IL_006f: ldloc.s V_8
IL_0071: isinst ""int""
IL_0076: brfalse.s IL_00a1
IL_0078: ldloc.0
IL_0079: ldloc.s V_8
IL_007b: unbox.any ""int""
IL_0080: stfld ""int C.<>c__DisplayClass0_0.<q>5__3""
// sequence point: <hidden>
IL_0085: br.s IL_008b
// sequence point: 1
IL_0087: ldc.i4.1
IL_0088: stloc.1
IL_0089: br.s IL_00a5
// sequence point: <hidden>
IL_008b: br.s IL_008d
// sequence point: G(() => p + q)
IL_008d: ldloc.0
IL_008e: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_0094: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0099: call ""int C.G(System.Func<int>)""
IL_009e: stloc.1
IL_009f: br.s IL_00a5
// sequence point: 0
IL_00a1: ldc.i4.0
IL_00a2: stloc.1
IL_00a3: br.s IL_00a5
// sequence point: <hidden>
IL_00a5: ldc.i4.1
IL_00a6: brtrue.s IL_00a9
// sequence point: F() switch ... }
IL_00a8: nop
// sequence point: <hidden>
IL_00a9: ldloc.1
IL_00aa: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""7"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""7"" />
<slot kind=""35"" offset=""7"" ordinal=""1"" />
<slot kind=""35"" offset=""7"" ordinal=""2"" />
<slot kind=""35"" offset=""7"" ordinal=""3"" />
<slot kind=""35"" offset=""7"" ordinal=""4"" />
<slot kind=""35"" offset=""7"" ordinal=""5"" />
<slot kind=""35"" offset=""7"" ordinal=""6"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""7"" />
<lambda offset=""92"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""27"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x50"" hidden=""true"" document=""1"" />
<entry offset=""0x59"" hidden=""true"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x85"" hidden=""true"" document=""1"" />
<entry offset=""0x87"" startLine=""7"" startColumn=""14"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x8b"" hidden=""true"" document=""1"" />
<entry offset=""0x8d"" startLine=""8"" startColumn=""46"" endLine=""8"" endColumn=""60"" document=""1"" />
<entry offset=""0xa1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""15"" document=""1"" />
<entry offset=""0xa5"" hidden=""true"" document=""1"" />
<entry offset=""0xa8"" startLine=""5"" startColumn=""23"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0xa9"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xab"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xab"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody_02()
{
string source = @"
using System;
public class C
{
static Action M1(int x) => () => { _ = x; };
static Action M2(int x) => x switch { _ => () => { _ = x; } };
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M1", sequencePoints: "C.M1", source: source, expectedIL: @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass0_0.x""
// sequence point: () => { _ = x; }
IL_000d: ldloc.0
IL_000e: ldftn ""void C.<>c__DisplayClass0_0.<M1>b__0()""
IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0019: ret
}
");
verifier.VerifyIL("C.M2", sequencePoints: "C.M2", source: source, expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
System.Action V_1)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass1_0.x""
// sequence point: x switch { _ => () => { _ = x; } }
IL_000d: ldc.i4.1
IL_000e: brtrue.s IL_0011
// sequence point: switch { _ => () => { _ = x; } }
IL_0010: nop
// sequence point: <hidden>
IL_0011: br.s IL_0013
// sequence point: () => { _ = x; }
IL_0013: ldloc.0
IL_0014: ldftn ""void C.<>c__DisplayClass1_0.<M2>b__0()""
IL_001a: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: br.s IL_0022
// sequence point: <hidden>
IL_0022: ldc.i4.1
IL_0023: brtrue.s IL_0026
// sequence point: x switch { _ => () => { _ = x; } }
IL_0025: nop
// sequence point: <hidden>
IL_0026: ldloc.1
IL_0027: ret
}
");
verifier.VerifyPdb("C.M1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M1"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""9"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
verifier.VerifyPdb("C.M2", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M2"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M1"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""25"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""34"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x13"" startLine=""6"" startColumn=""48"" endLine=""6"" endColumn=""64"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SyntaxOffset_OutVarInInitializers_SwitchExpression()
{
var source =
@"class C
{
static int G(out int x) => throw null;
static int F(System.Func<int> x) => throw null;
C() { }
int y1 = G(out var z) switch { _ => F(() => z) }; // line 7
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-26"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""-26"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-26"" />
<lambda offset=""-4"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x15"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""53"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x3e"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""10"" document=""1"" />
<entry offset=""0x3f"" startLine=""5"" startColumn=""11"" endLine=""5"" endColumn=""12"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<scope startOffset=""0x0"" endOffset=""0x37"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x37"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(43468, "https://github.com/dotnet/roslyn/issues/43468")]
[Fact]
public void HiddenSequencePointAtSwitchExpressionFinalMergePoint()
{
var source =
@"class C
{
static int M(int x)
{
var y = x switch
{
1 => 2,
_ => 3,
};
return y;
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (int V_0, //y
int V_1,
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: var y = x sw ... };
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
// sequence point: switch ... }
IL_0004: nop
// sequence point: <hidden>
IL_0005: ldarg.0
IL_0006: ldc.i4.1
IL_0007: beq.s IL_000b
IL_0009: br.s IL_000f
// sequence point: 2
IL_000b: ldc.i4.2
IL_000c: stloc.1
IL_000d: br.s IL_0013
// sequence point: 3
IL_000f: ldc.i4.3
IL_0010: stloc.1
IL_0011: br.s IL_0013
// sequence point: <hidden>
IL_0013: ldc.i4.1
IL_0014: brtrue.s IL_0017
// sequence point: var y = x sw ... };
IL_0016: nop
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stloc.0
// sequence point: return y;
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_001d
// sequence point: }
IL_001d: ldloc.2
IL_001e: ret
}
");
}
[WorkItem(12378, "https://github.com/dotnet/roslyn/issues/12378")]
[WorkItem(13971, "https://github.com/dotnet/roslyn/issues/13971")]
[Fact]
public void Patterns_SwitchStatement_Constant()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static void M(object o)
{
switch (o)
{
case 1 when o == null:
case 4:
case 2 when o == null:
break;
case 1 when o != null:
case 5:
case 3 when o != null:
break;
default:
break;
case 1:
break;
}
switch (o)
{
case 1:
break;
default:
break;
}
switch (o)
{
default:
break;
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
CompileAndVerify(c).VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source,
expectedIL: @"{
// Code size 123 (0x7b)
.maxstack 2
.locals init (object V_0,
int V_1,
object V_2,
object V_3,
int V_4,
object V_5,
object V_6,
object V_7)
// sequence point: {
IL_0000: nop
// sequence point: switch (o)
IL_0001: ldarg.0
IL_0002: stloc.2
// sequence point: <hidden>
IL_0003: ldloc.2
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: ldloc.0
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_004a
IL_000d: ldloc.0
IL_000e: unbox.any ""int""
IL_0013: stloc.1
// sequence point: <hidden>
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: sub
IL_0017: switch (
IL_0032,
IL_0037,
IL_0043,
IL_003c,
IL_0048)
IL_0030: br.s IL_004a
// sequence point: when o == null
IL_0032: ldarg.0
IL_0033: brfalse.s IL_003c
// sequence point: <hidden>
IL_0035: br.s IL_003e
// sequence point: when o == null
IL_0037: ldarg.0
IL_0038: brfalse.s IL_003c
// sequence point: <hidden>
IL_003a: br.s IL_004a
// sequence point: break;
IL_003c: br.s IL_004e
// sequence point: when o != null
IL_003e: ldarg.0
IL_003f: brtrue.s IL_0048
// sequence point: <hidden>
IL_0041: br.s IL_004c
// sequence point: when o != null
IL_0043: ldarg.0
IL_0044: brtrue.s IL_0048
// sequence point: <hidden>
IL_0046: br.s IL_004a
// sequence point: break;
IL_0048: br.s IL_004e
// sequence point: break;
IL_004a: br.s IL_004e
// sequence point: break;
IL_004c: br.s IL_004e
// sequence point: switch (o)
IL_004e: ldarg.0
IL_004f: stloc.s V_5
// sequence point: <hidden>
IL_0051: ldloc.s V_5
IL_0053: stloc.3
// sequence point: <hidden>
IL_0054: ldloc.3
IL_0055: isinst ""int""
IL_005a: brfalse.s IL_006d
IL_005c: ldloc.3
IL_005d: unbox.any ""int""
IL_0062: stloc.s V_4
// sequence point: <hidden>
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: beq.s IL_006b
IL_0069: br.s IL_006d
// sequence point: break;
IL_006b: br.s IL_006f
// sequence point: break;
IL_006d: br.s IL_006f
// sequence point: switch (o)
IL_006f: ldarg.0
IL_0070: stloc.s V_7
// sequence point: <hidden>
IL_0072: ldloc.s V_7
IL_0074: stloc.s V_6
// sequence point: <hidden>
IL_0076: br.s IL_0078
// sequence point: break;
IL_0078: br.s IL_007a
// sequence point: }
IL_007a: ret
}");
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""35"" offset=""378"" />
<slot kind=""35"" offset=""378"" ordinal=""1"" />
<slot kind=""1"" offset=""378"" />
<slot kind=""35"" offset=""511"" />
<slot kind=""1"" offset=""511"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""34"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x3e"" startLine=""11"" startColumn=""20"" endLine=""11"" endColumn=""34"" document=""1"" />
<entry offset=""0x41"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""13"" startColumn=""20"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x46"" hidden=""true"" document=""1"" />
<entry offset=""0x48"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""23"" document=""1"" />
<entry offset=""0x4a"" startLine=""16"" startColumn=""17"" endLine=""16"" endColumn=""23"" document=""1"" />
<entry offset=""0x4c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""23"" document=""1"" />
<entry offset=""0x4e"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x51"" hidden=""true"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""23"" document=""1"" />
<entry offset=""0x6d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" />
<entry offset=""0x6f"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""19"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x76"" hidden=""true"" document=""1"" />
<entry offset=""0x78"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""23"" document=""1"" />
<entry offset=""0x7a"" startLine=""32"" startColumn=""5"" endLine=""32"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement_Tuple()
{
string source = WithWindowsLineBreaks(@"
public class C
{
static int F(int i)
{
switch (G())
{
case (1, 2): return 3;
default: return 0;
};
}
static (object, object) G() => (2, 3);
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
var cv = CompileAndVerify(c);
cv.VerifyIL("C.F", @"
{
// Code size 80 (0x50)
.maxstack 2
.locals init (System.ValueTuple<object, object> V_0,
object V_1,
int V_2,
object V_3,
int V_4,
System.ValueTuple<object, object> V_5,
int V_6)
IL_0000: nop
IL_0001: call ""System.ValueTuple<object, object> C.G()""
IL_0006: stloc.s V_5
IL_0008: ldloc.s V_5
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldfld ""object System.ValueTuple<object, object>.Item1""
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: isinst ""int""
IL_0018: brfalse.s IL_0048
IL_001a: ldloc.1
IL_001b: unbox.any ""int""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: ldc.i4.1
IL_0023: bne.un.s IL_0048
IL_0025: ldloc.0
IL_0026: ldfld ""object System.ValueTuple<object, object>.Item2""
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: isinst ""int""
IL_0032: brfalse.s IL_0048
IL_0034: ldloc.3
IL_0035: unbox.any ""int""
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: ldc.i4.2
IL_003f: beq.s IL_0043
IL_0041: br.s IL_0048
IL_0043: ldc.i4.3
IL_0044: stloc.s V_6
IL_0046: br.s IL_004d
IL_0048: ldc.i4.0
IL_0049: stloc.s V_6
IL_004b: br.s IL_004d
IL_004d: ldloc.s V_6
IL_004f: ret
}
");
c.VerifyPdb("C.F", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</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=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""8"" startColumn=""26"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x48"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0x4d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Tuples
[Fact]
public void SyntaxOffset_TupleDeconstruction()
{
var source = @"class C { int F() { (int a, (_, int c)) = (1, (2, 3)); return a + c; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""7"" />
<slot kind=""0"" offset=""18"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""69"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""70"" endLine=""1"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
<local name=""c"" il_index=""1"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestDeconstruction()
{
var source = @"
public class C
{
public static (int, int) F() => (1, 2);
public static void Main()
{
int x, y;
(x, y) = F();
System.Console.WriteLine(x + y);
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
// sequence point: {
IL_0000: nop
// sequence point: (x, y) = F();
IL_0001: call ""System.ValueTuple<int, int> C.F()""
IL_0006: dup
IL_0007: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_000c: stloc.0
IL_000d: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0012: stloc.1
// sequence point: System.Console.WriteLine(x + y);
IL_0013: ldloc.0
IL_0014: ldloc.1
IL_0015: add
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
// sequence point: }
IL_001c: ret
}
", sequencePoints: "C.Main", source: source);
}
[Fact]
public void SyntaxOffset_TupleParenthesized()
{
var source = @"class C { int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x10"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""103"" document=""1"" />
<entry offset=""0x31"" startLine=""1"" startColumn=""104"" endLine=""1"" endColumn=""105"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x33"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x33"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void SyntaxOffset_TupleVarDefined()
{
var source = @"class C { int F() { var x = (1, 2); return x.Item1 + x.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""36"" document=""1"" />
<entry offset=""0xa"" startLine=""1"" startColumn=""37"" endLine=""1"" endColumn=""62"" document=""1"" />
<entry offset=""0x1a"" startLine=""1"" startColumn=""63"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SyntaxOffset_TupleIgnoreDeconstructionIfVariableDeclared()
{
var source = @"class C { int F() { (int x, int y) a = (1, 2); return a.Item1 + a.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<tupleElementNames>
<local elementNames=""|x|y"" slotIndex=""0"" localName=""a"" scopeStart=""0x0"" scopeEnd=""0x0"" />
</tupleElementNames>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""47"" document=""1"" />
<entry offset=""0x9"" startLine=""1"" startColumn=""48"" endLine=""1"" endColumn=""73"" document=""1"" />
<entry offset=""0x19"" startLine=""1"" startColumn=""74"" endLine=""1"" endColumn=""75"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region OutVar
[Fact]
public void SyntaxOffset_OutVarInConstructor()
{
var source = @"
class B
{
B(out int z) { z = 2; }
}
class C
{
int F = G(out var v1);
int P => G(out var v2);
C()
: base(out var v3)
{
G(out var v4);
}
int G(out int x)
{
x = 1;
return 2;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics(
// (9,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.G(out int)'
// int F = G(out var v1);
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "G").WithArguments("C.G(out int)").WithLocation(9, 13),
// (13,7): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// : base(out var v3)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(13, 7));
}
[Fact]
public void SyntaxOffset_OutVarInMethod()
{
var source = @"class C { int G(out int x) { int z = 1; G(out var y); G(out var w); return x = y; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""0"" offset=""23"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""28"" endLine=""1"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""30"" endLine=""1"" endColumn=""40"" document=""1"" />
<entry offset=""0x3"" startLine=""1"" startColumn=""41"" endLine=""1"" endColumn=""54"" document=""1"" />
<entry offset=""0xc"" startLine=""1"" startColumn=""55"" endLine=""1"" endColumn=""68"" document=""1"" />
<entry offset=""0x15"" startLine=""1"" startColumn=""69"" endLine=""1"" endColumn=""82"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""83"" endLine=""1"" endColumn=""84"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""w"" il_index=""2"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_01()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
int x = G(out var x);
int y {get;} = G(out var y);
C() : base(G(out var z))
{
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-36"" />
<slot kind=""0"" offset=""-22"" />
<slot kind=""0"" offset=""-3"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""32"" document=""1"" />
<entry offset=""0x1a"" startLine=""7"" startColumn=""11"" endLine=""7"" endColumn=""29"" document=""1"" />
<entry offset=""0x28"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""y"" il_index=""1"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a"" endOffset=""0x2a"">
<local name=""z"" il_index=""2"" il_start=""0x1a"" il_end=""0x2a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_02()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
{
int y = 1;
y++;
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""16"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""13"" document=""1"" />
<entry offset=""0x15"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x16"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x16"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_03()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
=> G(out var y);
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""13"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""8"" endLine=""5"" endColumn=""20"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x17"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x17"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x17"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x17"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_04()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
C()
{
}
#line 2000
int y1 = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""40"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x30"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x31"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x32"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass2_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_05()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 { get; } = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>5</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""23"" endLine=""2000"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x31"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass5_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass5_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""46"" endLine=""2000"" endColumn=""47"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_06()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 = G(out var z) + F(() => z), y2 = G(out var u) + F(() => u);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C..ctor", sequencePoints: "C..ctor", expectedIL: @"
{
// Code size 90 (0x5a)
.maxstack 4
.locals init (C.<>c__DisplayClass4_0 V_0, //CS$<>8__locals0
C.<>c__DisplayClass4_1 V_1) //CS$<>8__locals1
~IL_0000: newobj ""C.<>c__DisplayClass4_0..ctor()""
IL_0005: stloc.0
-IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass4_0.z""
IL_000d: call ""int C.G(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass4_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.F(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.y1""
~IL_0029: newobj ""C.<>c__DisplayClass4_1..ctor()""
IL_002e: stloc.1
-IL_002f: ldarg.0
IL_0030: ldloc.1
IL_0031: ldflda ""int C.<>c__DisplayClass4_1.u""
IL_0036: call ""int C.G(out int)""
IL_003b: ldloc.1
IL_003c: ldftn ""int C.<>c__DisplayClass4_1.<.ctor>b__1()""
IL_0042: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0047: call ""int C.F(System.Func<int>)""
IL_004c: add
IL_004d: stfld ""int C.y2""
IL_0052: ldarg.0
IL_0053: call ""object..ctor()""
IL_0058: nop
IL_0059: ret
}
");
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-52"" />
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<closure offset=""-52"" />
<closure offset=""-25"" />
<lambda offset=""-29"" closure=""0"" />
<lambda offset=""-2"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""39"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""2000"" startColumn=""41"" endLine=""2000"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x5a"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
<scope startOffset=""0x29"" endOffset=""0x52"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x29"" il_end=""0x52"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_1.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_1"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""69"" endLine=""2000"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_07()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
#line 2000
C() : base(G(out var z)+ F(() => z))
{
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""-1"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""-1"" />
<lambda offset=""-3"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""11"" endLine=""2000"" endColumn=""41"" document=""1"" />
<entry offset=""0x2a"" startLine=""2001"" startColumn=""5"" endLine=""2001"" endColumn=""6"" document=""1"" />
<entry offset=""0x2b"" startLine=""2002"" startColumn=""5"" endLine=""2002"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2c"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x2c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""38"" endLine=""2000"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_01()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
{
var q = from a in new [] {1}
where
G(out var x1) > a
select a;
}
static int G(out int x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""88"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""98"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""40"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""x1"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_02()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
#line 2000
{
var q = from a in new [] {1}
where
G(out var x1) > F(() => x1)
select a;
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""88"" />
<lambda offset=""88"" />
<lambda offset=""112"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""2001"" startColumn=""9"" endLine=""2004"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""2005"" startColumn=""5"" endLine=""2005"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""88"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2003"" startColumn=""23"" endLine=""2003"" endColumn=""50"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x25"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2003"" startColumn=""47"" endLine=""2003"" endColumn=""49"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInSwitchExpression()
{
var source = @"class C { static object G() => N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; static object N(out int x) { x = 1; return null; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""16"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""1"" startColumn=""64"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""1"" startColumn=""78"" endLine=""1"" endColumn=""79"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""86"" endLine=""1"" endColumn=""87"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x27"" startLine=""1"" startColumn=""62"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x2b"" startLine=""1"" startColumn=""96"" endLine=""1"" endColumn=""97"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
#endregion
[WorkItem(4370, "https://github.com/dotnet/roslyn/issues/4370")]
[Fact]
public void HeadingHiddenSequencePointsPickUpDocumentFromVisibleSequencePoint()
{
var source = WithWindowsLineBreaks(
@"#line 1 ""C:\Async.cs""
#pragma checksum ""C:\Async.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""DBEB2A067B2F0E0D678A002C587A2806056C3DCE""
using System.Threading.Tasks;
public class C
{
public async void M1()
{
}
}
");
var tree = SyntaxFactory.ParseSyntaxTree(source, encoding: Encoding.UTF8, path: "HIDDEN.cs");
var c = CSharpCompilation.Create("Compilation", new[] { tree }, new[] { MscorlibRef_v46 }, options: TestOptions.DebugDll.WithDebugPlusMode(true));
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
<file id=""2"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
</files>
<methods>
<method containingType=""C"" name=""M1"">
<customDebugInfo>
<forwardIterator name=""<M1>d__0"" />
</customDebugInfo>
</method>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
<file id=""2"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
</files>
<methods>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""2"" />
<entry offset=""0xa"" hidden=""true"" document=""2"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""2"" />
<entry offset=""0x2a"" hidden=""true"" document=""2"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(12923, "https://github.com/dotnet/roslyn/issues/12923")]
[Fact]
public void SequencePointsForConstructorWithHiddenInitializer()
{
string initializerSource = WithWindowsLineBreaks(@"
#line hidden
partial class C
{
int i = 42;
}
");
string constructorSource = WithWindowsLineBreaks(@"
partial class C
{
C()
{
}
}
");
var c = CreateCompilation(
new[] { Parse(initializerSource, "initializer.cs"), Parse(constructorSource, "constructor.cs") },
options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
<file id=""2"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
<file id=""2"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""2"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""2"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")]
[Fact]
public void LocalFunctionSequencePoints()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static int Main(string[] args)
{ // 4
int Local1(string[] a)
=>
a.Length; // 7
int Local2(string[] a)
{ // 9
return a.Length; // 10
} // 11
return Local1(args) + Local2(args); // 12
} // 13
}");
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=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""115"" />
<lambda offset=""202"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""44"" document=""1"" />
<entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local1|0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local2|0_1"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""202"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void SwitchInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
switch (i)
{
case 1:
break;
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (int V_0,
int V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: switch (i)
IL_000f: ldarg.0
IL_0010: ldarg.0
IL_0011: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0016: stloc.1
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stfld ""int Program.<Test>d__0.<>s__2""
// sequence point: <hidden>
IL_001d: ldarg.0
IL_001e: ldfld ""int Program.<Test>d__0.<>s__2""
IL_0023: ldc.i4.1
IL_0024: beq.s IL_0028
IL_0026: br.s IL_002a
// sequence point: break;
IL_0028: br.s IL_002a
// sequence point: <hidden>
IL_002a: leave.s IL_0044
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_002c: stloc.2
IL_002d: ldarg.0
IL_002e: ldc.i4.s -2
IL_0030: stfld ""int Program.<Test>d__0.<>1__state""
IL_0035: ldarg.0
IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_003b: ldloc.2
IL_003c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0041: nop
IL_0042: leave.s IL_0058
}
// sequence point: }
IL_0044: ldarg.0
IL_0045: ldc.i4.s -2
IL_0047: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_004c: ldarg.0
IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0052: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0057: nop
IL_0058: ret
}", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void WhileInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
while (i == 1)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 83 (0x53)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0017
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: while (i == 1)
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: ldc.i4.1
IL_001e: ceq
IL_0020: stloc.1
// sequence point: <hidden>
IL_0021: ldloc.1
IL_0022: brtrue.s IL_0011
IL_0024: leave.s IL_003e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldc.i4.s -2
IL_002a: stfld ""int Program.<Test>d__0.<>1__state""
IL_002f: ldarg.0
IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0035: ldloc.2
IL_0036: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_003b: nop
IL_003c: leave.s IL_0052
}
// sequence point: }
IL_003e: ldarg.0
IL_003f: ldc.i4.s -2
IL_0041: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0046: ldarg.0
IL_0047: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0051: nop
IL_0052: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = 0; i > 1; i--)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0027
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: i--
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: stloc.1
IL_001e: ldarg.0
IL_001f: ldloc.1
IL_0020: ldc.i4.1
IL_0021: sub
IL_0022: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0027: ldarg.0
IL_0028: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_002d: ldc.i4.1
IL_002e: cgt
IL_0030: stloc.2
// sequence point: <hidden>
IL_0031: ldloc.2
IL_0032: brtrue.s IL_0011
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.3
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.3
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForWithInnerLocalsInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = M(out var x); i > 1; i--)
Console.WriteLine();
}
public static int M(out int x) { x = 0; return 0; }
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = M(out var x)
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: ldflda ""int Program.<Test>d__0.<x>5__2""
IL_000f: call ""int Program.M(out int)""
IL_0014: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_0019: br.s IL_0031
// sequence point: Console.WriteLine();
IL_001b: call ""void System.Console.WriteLine()""
IL_0020: nop
// sequence point: i--
IL_0021: ldarg.0
IL_0022: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0027: stloc.1
IL_0028: ldarg.0
IL_0029: ldloc.1
IL_002a: ldc.i4.1
IL_002b: sub
IL_002c: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0031: ldarg.0
IL_0032: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0037: ldc.i4.1
IL_0038: cgt
IL_003a: stloc.2
// sequence point: <hidden>
IL_003b: ldloc.2
IL_003c: brtrue.s IL_001b
IL_003e: leave.s IL_0058
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0040: stloc.3
IL_0041: ldarg.0
IL_0042: ldc.i4.s -2
IL_0044: stfld ""int Program.<Test>d__0.<>1__state""
IL_0049: ldarg.0
IL_004a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004f: ldloc.3
IL_0050: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0055: nop
IL_0056: leave.s IL_006c
}
// sequence point: }
IL_0058: ldarg.0
IL_0059: ldc.i4.s -2
IL_005b: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0060: ldarg.0
IL_0061: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0066: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_006b: nop
IL_006c: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
public void InvalidCharacterInPdbPath()
{
using (var outStream = Temp.CreateFile().Open())
{
var compilation = CreateCompilation("");
var result = compilation.Emit(outStream, options: new EmitOptions(pdbFilePath: "test\\?.pdb", debugInformationFormat: DebugInformationFormat.Embedded));
// This is fine because EmitOptions just controls what is written into the PE file and it's
// valid for this to be an illegal file name (path map can easily create these).
Assert.True(result.Success);
}
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void FilesOneWithNoMethodBody()
{
string source1 = WithWindowsLineBreaks(@"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
");
string source2 = WithWindowsLineBreaks(@"
// no code
");
var tree1 = Parse(source1, "f:/build/goo.cs");
var tree2 = Parse(source2, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree1, tree2 }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/goo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""5D-7D-CF-1B-79-12-0E-0A-80-13-E0-98-7E-5C-AA-3B-63-D8-7E-4F"" />
<file id=""2"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void SingleFileWithNoMethodBody()
{
string source = WithWindowsLineBreaks(@"
// no code
");
var tree = Parse(source, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<methods />
</symbols>
");
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests2.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.Patterns)]
public class PatternMatchingTests2 : PatternMatchingTestBase
{
[Fact]
public void Patterns2_00()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.WriteLine(1 is int {} x ? x : -1);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"1");
}
[Fact]
public void Patterns2_01()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Point p = new Point();
Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1));
Check(false, p is Point(1, 4) { Length: 5 });
Check(false, p is Point(3, 1) { Length: 5 });
Check(false, p is Point(3, 4) { Length: 1 });
Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2));
Check(false, p is (1, 4) { Length: 5 });
Check(false, p is (3, 1) { Length: 5 });
Check(false, p is (3, 4) { Length: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}
public class Point
{
public void Deconstruct(out int X, out int Y)
{
X = 3;
Y = 4;
}
public int Length => 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_02()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Point p = new Point();
Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1));
Check(false, p is Point(1, 4) { Length: 5 });
Check(false, p is Point(3, 1) { Length: 5 });
Check(false, p is Point(3, 4) { Length: 1 });
Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2));
Check(false, p is (1, 4) { Length: 5 });
Check(false, p is (3, 1) { Length: 5 });
Check(false, p is (3, 4) { Length: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}
public class Point
{
public int Length => 5;
}
public static class PointExtensions
{
public static void Deconstruct(this Point p, out int X, out int Y)
{
X = 3;
Y = 4;
}
}
";
// We use a compilation profile that provides System.Runtime.CompilerServices.ExtensionAttribute needed for this test
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_03()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
var p = (x: 3, y: 4);
Check(true, p is (3, 4) q1 && Check(p, q1));
Check(false, p is (1, 4) { x: 3 });
Check(false, p is (3, 1) { y: 4 });
Check(false, p is (3, 4) { x: 1 });
Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2));
Check(false, p is (1, 4) { x: 3 });
Check(false, p is (3, 1) { x: 3 });
Check(false, p is (3, 4) { x: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (1, 4) { x: 3 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(9, 22),
// (10,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (3, 1) { y: 4 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 1) { y: 4 }").WithArguments("(int x, int y)").WithLocation(10, 22),
// (11,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (3, 4) { x: 1 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(11, 22),
// (13,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (1, 4) { x: 3 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(13, 22),
// (15,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (3, 4) { x: 1 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(15, 22)
);
}
[Fact]
public void Patterns2_04b()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
var p = (x: 3, y: 4);
Check(true, p is (3, 4) q1 && Check(p, q1));
Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2));
Check(false, p is (3, 1) { x: 3 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_DiscardPattern_01()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Point p = new Point();
Check(true, p is Point(_, _) { Length: _ } q1 && Check(p, q1));
Check(false, p is Point(1, _) { Length: _ });
Check(false, p is Point(_, 1) { Length: _ });
Check(false, p is Point(_, _) { Length: 1 });
Check(true, p is (_, _) { Length: _ } q2 && Check(p, q2));
Check(false, p is (1, _) { Length: _ });
Check(false, p is (_, 1) { Length: _ });
Check(false, p is (_, _) { Length: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}
public class Point
{
public void Deconstruct(out int X, out int Y)
{
X = 3;
Y = 4;
}
public int Length => 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_Switch01()
{
var sourceTemplate =
@"
class Program
{{
public static void Main()
{{
var p = (true, false);
switch (p)
{{
{0}
{1}
{2}
case (_, _): // error - subsumed
break;
}}
}}
}}";
void testErrorCase(string s1, string s2, string s3)
{
var source = string.Format(sourceTemplate, s1, s2, s3);
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (12,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case (_, _): // error - subsumed
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "(_, _)").WithLocation(12, 18)
);
}
void testGoodCase(string s1, string s2)
{
var source = string.Format(sourceTemplate, s1, s2, string.Empty);
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
var c1 = "case (true, _):";
var c2 = "case (false, false):";
var c3 = "case (_, true):";
testErrorCase(c1, c2, c3);
testErrorCase(c2, c3, c1);
testErrorCase(c3, c1, c2);
testErrorCase(c1, c3, c2);
testErrorCase(c3, c2, c1);
testErrorCase(c2, c1, c3);
testGoodCase(c1, c2);
testGoodCase(c1, c3);
testGoodCase(c2, c3);
testGoodCase(c2, c1);
testGoodCase(c3, c1);
testGoodCase(c3, c2);
}
[Fact]
public void Patterns2_Switch02()
{
var source =
@"
class Program
{
public static void Main()
{
Point p = new Point();
switch (p)
{
case Point(3, 4) { Length: 5 }:
System.Console.WriteLine(true);
break;
default:
System.Console.WriteLine(false);
break;
}
}
}
public class Point
{
public void Deconstruct(out int X, out int Y)
{
X = 3;
Y = 4;
}
public int Length => 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "True");
}
[Fact]
public void DefaultPattern()
{
var source =
@"class Program
{
public static void Main()
{
int i = 12;
if (i is default) {} // error 1
if (i is (default)) {} // error 2
switch (i) { case default: break; } // error 3
switch (i) { case default when true: break; } // error 4
switch ((1, 2)) { case (1, default): break; } // error 5
if (i is < default) {} // error 6
switch (i) { case < default: break; } // error 7
if (i is < ((default))) {} // error 8
switch (i) { case < ((default)): break; } // error 9
if (i is default!) {} // error 10
if (i is (default!)) {} // error 11
if (i is < ((default)!)) {} // error 12
if (i is default!!) {} // error 13
if (i is (default!!)) {} // error 14
if (i is < ((default)!!)) {} // error 15
// These are not accepted by the parser. See https://github.com/dotnet/roslyn/issues/45387
if (i is (default)!) {} // error 16
if (i is ((default)!)) {} // error 17
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is default) {} // error 1
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 18),
// (7,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default)) {} // error 2
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(7, 19),
// (8,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case default: break; } // error 3
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 27),
// (9,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case default when true: break; } // error 4
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27),
// (10,36): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch ((1, 2)) { case (1, default): break; } // error 5
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 36),
// (12,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < default) {} // error 6
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 20),
// (13,29): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case < default: break; } // error 7
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(13, 29),
// (14,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < ((default))) {} // error 8
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(14, 22),
// (15,31): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case < ((default)): break; } // error 9
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(15, 31),
// (17,18): error CS8598: The suppression operator is not allowed in this context
// if (i is default!) {} // error 10
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(17, 18),
// (17,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is default!) {} // error 10
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(17, 18),
// (18,19): error CS8598: The suppression operator is not allowed in this context
// if (i is (default!)) {} // error 11
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(18, 19),
// (18,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default!)) {} // error 11
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(18, 19),
// (19,21): error CS8598: The suppression operator is not allowed in this context
// if (i is < ((default)!)) {} // error 12
Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(19, 21),
// (19,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < ((default)!)) {} // error 12
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(19, 22),
// (20,18): error CS8598: The suppression operator is not allowed in this context
// if (i is default!!) {} // error 13
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(20, 18),
// (20,18): error CS8598: The suppression operator is not allowed in this context
// if (i is default!!) {} // error 13
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(20, 18),
// (20,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is default!!) {} // error 13
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(20, 18),
// (21,19): error CS8598: The suppression operator is not allowed in this context
// if (i is (default!!)) {} // error 14
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(21, 19),
// (21,19): error CS8598: The suppression operator is not allowed in this context
// if (i is (default!!)) {} // error 14
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(21, 19),
// (21,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default!!)) {} // error 14
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(21, 19),
// (22,21): error CS8598: The suppression operator is not allowed in this context
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!!").WithLocation(22, 21),
// (22,21): error CS8598: The suppression operator is not allowed in this context
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(22, 21),
// (22,22): error CS8715: Duplicate null suppression operator ('!')
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(22, 22),
// (22,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(22, 22),
// (25,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(25, 19),
// (25,27): error CS1026: ) expected
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(25, 27),
// (25,28): error CS1525: Invalid expression term ')'
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(25, 28),
// (25,28): error CS1002: ; expected
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(25, 28),
// (25,28): error CS1513: } expected
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(25, 28),
// (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'int', with 2 out parameters and a void return type.
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "((default)!)").WithArguments("int", "2").WithLocation(26, 18),
// (26,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(26, 20),
// (26,28): error CS1003: Syntax error, ',' expected
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(26, 28),
// (26,29): error CS1525: Invalid expression term ')'
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(26, 29)
);
}
[Fact]
public void SwitchExpression_01()
{
// test appropriate language version or feature flag
var source =
@"class Program
{
public static void Main()
{
var r = 1 switch { _ => 0, };
}
}";
CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns).VerifyDiagnostics(
// (5,17): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater.
// var r = 1 switch { _ => 0, };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { _ => 0, }").WithArguments("recursive patterns", "8.0").WithLocation(5, 17)
);
CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void SwitchExpression_02()
{
// test switch expression's governing expression has no type
// test switch expression's governing expression has type void
var source =
@"class Program
{
public static void Main()
{
var r1 = (1, null) switch { _ => 0 };
var r2 = System.Console.Write(1) switch { _ => 0 };
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (5,18): error CS8117: Invalid operand for pattern match; value required, but found '(int, <null>)'.
// var r1 = (1, null) switch ( _ => 0 );
Diagnostic(ErrorCode.ERR_BadPatternExpression, "(1, null)").WithArguments("(int, <null>)").WithLocation(5, 18),
// (6,18): error CS8117: Invalid operand for pattern match; value required, but found 'void'.
// var r2 = System.Console.Write(1) switch ( _ => 0 );
Diagnostic(ErrorCode.ERR_BadPatternExpression, "System.Console.Write(1)").WithArguments("void").WithLocation(6, 18)
);
}
[Fact]
public void SwitchExpression_03()
{
// test that a ternary expression is not at an appropriate precedence
// for the constant expression of a constant pattern in a switch expression arm.
var source =
@"class Program
{
public static void Main()
{
bool b = true;
var r1 = b switch { true ? true : true => true, false => false };
var r2 = b switch { (true ? true : true) => true, false => false };
}
}";
// This is admittedly poor syntax error recovery (for the line declaring r2),
// but this test demonstrates that it is a syntax error.
CreatePatternCompilation(source).VerifyDiagnostics(
// (6,34): error CS1003: Syntax error, '=>' expected
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(6, 34),
// (6,34): error CS1525: Invalid expression term '?'
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(6, 34),
// (6,48): error CS1003: Syntax error, ',' expected
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 48),
// (6,48): error CS8504: Pattern missing
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(6, 48)
);
}
[Fact]
public void SwitchExpression_04()
{
// test that a ternary expression is permitted as a constant pattern in recursive contexts and the case expression.
var source =
@"class Program
{
public static void Main()
{
var b = (true, false);
var r1 = b switch { (true ? true : true, _) => true, _ => false, };
var r2 = b is (true ? true : true, _);
switch (b.Item1) { case true ? true : true: break; }
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
);
}
[Fact]
public void SwitchExpression_05()
{
// test throw expression in match arm.
var source =
@"class Program
{
public static void Main()
{
var x = 1 switch { 1 => 1, _ => throw null };
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
);
}
[Fact]
public void EmptySwitchExpression()
{
var source =
@"class Program
{
public static void Main()
{
var r = 1 switch { };
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// var r = 1 switch { };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 19),
// (5,19): error CS8506: No best type was found for the switch expression.
// var r = 1 switch { };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(5, 19));
}
[Fact]
public void SwitchExpression_06()
{
// test common type vs delegate in match expression
var source =
@"class Program
{
public static void Main()
{
var x = 1 switch { 0 => M, 1 => new D(M), 2 => M };
x();
}
public static void M() {}
public delegate void D();
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '3' is not covered.
// var x = 1 switch { 0 => M, 1 => new D(M), 2 => M };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("3").WithLocation(5, 19)
);
}
[Fact]
public void SwitchExpression_07()
{
// test flow analysis of the switch expression
var source =
@"class Program
{
public static void Main()
{
int q = 1;
int u;
var x = q switch { 0 => u=0, 1 => u=1, _ => u=2 };
System.Console.WriteLine(u);
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
);
}
[Fact]
public void SwitchExpression_08()
{
// test flow analysis of the switch expression
var source =
@"class Program
{
public static void Main()
{
int q = 1;
int u;
var x = q switch { 0 => u=0, 1 => 1, _ => u=2 };
System.Console.WriteLine(u);
}
static int M(int i) => i;
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (8,34): error CS0165: Use of unassigned local variable 'u'
// System.Console.WriteLine(u);
Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(8, 34)
);
}
[Fact]
public void SwitchExpression_09()
{
// test flow analysis of the switch expression
var source =
@"class Program
{
public static void Main()
{
int q = 1;
int u;
var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2, };
System.Console.WriteLine(u);
}
static int M(int i) => i;
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (7,47): error CS0165: Use of unassigned local variable 'u'
// var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(7, 47)
);
}
[Fact]
public void SwitchExpression_10()
{
// test lazily inferring variables in the pattern
// test lazily inferring variables in the when clause
// test lazily inferring variables in the arrow expression
var source =
@"class Program
{
public static void Main()
{
int a = 1;
var b = a switch { var x1 => x1, };
var c = a switch { var x2 when x2 is var x3 => x3 };
var d = a switch { var x4 => x4 is var x5 ? x5 : 1, };
}
static int M(int i) => i;
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. However, a pattern with a 'when' clause might successfully match this value.
// var c = a switch { var x2 when x2 is var x3 => x3 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("_").WithLocation(7, 19)
);
var names = new[] { "x1", "x2", "x3", "x4", "x5" };
var tree = compilation.SyntaxTrees[0];
foreach (var designation in tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>())
{
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetDeclaredSymbol(designation);
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal("int", ((ILocalSymbol)symbol).Type.ToDisplayString());
}
foreach (var ident in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>())
{
var model = compilation.GetSemanticModel(tree);
var typeInfo = model.GetTypeInfo(ident);
Assert.Equal("int", typeInfo.Type.ToDisplayString());
}
}
[Fact]
public void ShortDiscardInIsPattern()
{
// test that we forbid a short discard at the top level of an is-pattern expression
var source =
@"class Program
{
public static void Main()
{
int a = 1;
if (a is _) { }
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// if (a is _) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(6, 18)
);
}
[Fact]
public void Patterns2_04()
{
// Test that a single-element deconstruct pattern is an error if no further elements disambiguate.
var source =
@"
using System;
class Program
{
public static void Main()
{
var t = new System.ValueTuple<int>(1);
if (t is (int x)) { } // error 1
switch (t) { case (_): break; } // error 2
var u = t switch { (int y) => y, _ => 2 }; // error 3
if (t is (int z1) _) { } // ok
if (t is (Item1: int z2)) { } // ok
if (t is (int z3) { }) { } // ok
if (t is ValueTuple<int>(int z4)) { } // ok
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8);
compilation.VerifyDiagnostics(
// (8,18): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater.
// if (t is (int x)) { } // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x)").WithArguments("parenthesized pattern", "9.0").WithLocation(8, 18),
// (8,19): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'.
// if (t is (int x)) { } // error 1
Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(8, 19),
// (9,27): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater.
// switch (t) { case (_): break; } // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(_)").WithArguments("parenthesized pattern", "9.0").WithLocation(9, 27),
// (10,28): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater.
// var u = t switch { (int y) => y, _ => 2 }; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int y)").WithArguments("parenthesized pattern", "9.0").WithLocation(10, 28),
// (10,29): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'.
// var u = t switch { (int y) => y, _ => 2 }; // error 3
Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(10, 29)
);
}
[Fact]
public void Patterns2_05()
{
// Test parsing the var pattern
// Test binding the var pattern
// Test lowering the var pattern for the is-expression
var source =
@"
using System;
class Program
{
public static void Main()
{
var t = (1, 2);
{ Check(true, t is var (x, y) && x == 1 && y == 2); }
{ Check(false, t is var (x, y) && x == 1 && y == 3); }
}
private static void Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'"");
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"");
}
[Fact]
public void Patterns2_06()
{
// Test that 'var' does not bind to a type
var source =
@"
using System;
namespace N
{
class Program
{
public static void Main()
{
var t = (1, 2);
{ Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
{ Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
{ Check(true, t is var x); } // error 3
}
private static void Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'"");
}
}
class var { }
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,21): error CS0029: Cannot implicitly convert type '(int, int)' to 'N.var'
// var t = (1, 2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2)").WithArguments("(int, int)", "N.var").WithLocation(9, 21),
// (10,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here.
// { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(10, 32),
// (10,36): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?)
// { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(10, 36),
// (10,36): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type.
// { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(10, 36),
// (11,33): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here.
// { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(11, 33),
// (11,37): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?)
// { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(11, 37),
// (11,37): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type.
// { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(11, 37),
// (12,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here.
// { Check(true, t is var x); } // error 3
Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(12, 32)
);
}
[Fact]
public void Patterns2_10()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.Write(M((false, false)));
Console.Write(M((false, true)));
Console.Write(M((true, false)));
Console.Write(M((true, true)));
}
private static int M((bool, bool) t)
{
switch (t)
{
case (false, false): return 0;
case (false, _): return 1;
case (_, false): return 2;
case var _: return 3;
}
}
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"0123");
}
[Fact]
public void Patterns2_11()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.Write(M((false, false)));
Console.Write(M((false, true)));
Console.Write(M((true, false)));
Console.Write(M((true, true)));
}
private static int M((bool, bool) t)
{
switch (t)
{
case (false, false): return 0;
case (false, _): return 1;
case (_, false): return 2;
case (true, true): return 3;
case var _: return 4;
}
}
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (20,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case var _: return 4;
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "var _").WithLocation(20, 18)
);
}
[Fact]
public void Patterns2_12()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.Write(M((false, false)));
Console.Write(M((false, true)));
Console.Write(M((true, false)));
Console.Write(M((true, true)));
}
private static int M((bool, bool) t)
{
return t switch {
(false, false) => 0,
(false, _) => 1,
(_, false) => 2,
_ => 3
};
}
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"0123");
}
[Fact]
public void SwitchArmSubsumed()
{
var source =
@"public class X
{
public static void Main()
{
string s = string.Empty;
string s2 = s switch { null => null, string t => t, ""foo"" => null };
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,61): error CS8410: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.
// string s2 = s switch { null => null, string t => t, "foo" => null };
Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, @"""foo""").WithLocation(6, 61)
);
}
[Fact]
public void LongTuples()
{
var source =
@"using System;
public class X
{
public static void Main()
{
var t = (1, 2, 3, 4, 5, 6, 7, 8, 9);
{
Console.WriteLine(t is (_, _, _, _, _, _, _, _, var t9) ? t9 : 100);
}
switch (t)
{
case (_, _, _, _, _, _, _, _, var t9):
Console.WriteLine(t9);
break;
}
Console.WriteLine(t switch { (_, _, _, _, _, _, _, _, var t9) => t9 });
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"9
9
9");
}
[Fact]
public void TypeCheckInPropertyPattern()
{
var source =
@"using System;
class Program2
{
public static void Main()
{
object o = new Frog(1, 2);
if (o is Frog(1, 2))
{
Console.Write(1);
}
if (o is Frog { A: 1, B: 2 })
{
Console.Write(2);
}
if (o is Frog(1, 2) { A: 1, B: 2, C: 3 })
{
Console.Write(3);
}
if (o is Frog(9, 2) { A: 1, B: 2, C: 3 }) {} else
{
Console.Write(4);
}
if (o is Frog(1, 9) { A: 1, B: 2, C: 3 }) {} else
{
Console.Write(5);
}
if (o is Frog(1, 2) { A: 9, B: 2, C: 3 }) {} else
{
Console.Write(6);
}
if (o is Frog(1, 2) { A: 1, B: 9, C: 3 }) {} else
{
Console.Write(7);
}
if (o is Frog(1, 2) { A: 1, B: 2, C: 9 }) {} else
{
Console.Write(8);
}
}
}
class Frog
{
public object A, B;
public object C => (int)A + (int)B;
public Frog(object A, object B) => (this.A, this.B) = (A, B);
public void Deconstruct(out object A, out object B) => (A, B) = (this.A, this.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"12345678");
}
[Fact]
public void OvereagerSubsumption()
{
var source =
@"class Program2
{
public static int Main() => 0;
public static void M(object o)
{
switch (o)
{
case (1, 2):
break;
case string s:
break;
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source); // doesn't have ITuple
// Two errors below instead of one due to https://github.com/dotnet/roslyn/issues/25533
compilation.VerifyDiagnostics(
// (8,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// case (1, 2):
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(8, 18),
// (8,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// case (1, 2):
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(8, 18)
);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_01()
{
var source =
@"class Program0
{
static int Main() => 0;
private const int _ = 1;
bool M1(object o) => o is _;
bool M2(object o) => o switch { 1 => true, _ => false };
}
class Program1
{
class _ {}
bool M3(object o) => o is _;
bool M4(object o) => o switch { 1 => true, _ => false };
}
";
var expected = new[]
{
// (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// bool M1(object o) => o is _;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31),
// (11,31): warning CS8513: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
// bool M3(object o) => o is _;
Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("Program1._").WithLocation(11, 31)
};
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(expected);
compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8);
compilation.VerifyDiagnostics(expected);
expected = new[]
{
// (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// bool M1(object o) => o is _;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31),
// (6,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater.
// bool M2(object o) => o switch { 1 => true, _ => false };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(6, 26),
// (12,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater.
// bool M4(object o) => o switch { 1 => true, _ => false };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(12, 26)
};
compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(expected);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_02()
{
var source =
@"class Program0
{
static int Main() => 0;
private const int _ = 1;
}
class Program1 : Program0
{
bool M2(object o) => o switch { 1 => true, _ => false }; // ok, private member not inherited
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_03()
{
var source =
@"class Program0
{
static int Main() => 0;
protected const int _ = 1;
}
class Program1 : Program0
{
bool M2(object o) => o switch { 1 => true, _ => false };
}
class Program2
{
bool _(object q) => true;
bool M2(object o) => o switch { 1 => true, _ => false };
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_04()
{
var source =
@"using _ = System.Int32;
class Program
{
static int Main() => 0;
bool M2(object o) => o switch { 1 => true, _ => false };
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using _ = System.Int32;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using _ = System.Int32;").WithLocation(1, 1)
);
}
[Fact]
public void EscapingUnderscoreDeclaredAndDiscardPattern_04()
{
var source =
@"class Program0
{
static int Main() => 0;
private const int _ = 2;
bool M1(object o) => o is @_;
int M2(object o) => o switch { 1 => 1, @_ => 2, var _ => 3 };
}
class Program1
{
class _ {}
bool M1(object o) => o is @_;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void ErroneousSwitchArmDefiniteAssignment()
{
// When a switch expression arm is erroneous, ensure that the expression is treated as unreachable (e.g. for definite assignment purposes).
var source =
@"class Program2
{
public static int Main() => 0;
public static void M(string s)
{
int i;
int j = s switch { ""frog"" => 1, 0 => i, _ => 2 };
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,41): error CS0029: Cannot implicitly convert type 'int' to 'string'
// int j = s switch { "frog" => 1, 0 => i, _ => 2 };
Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "string").WithLocation(7, 41)
);
}
[Fact, WorkItem(9154, "https://github.com/dotnet/roslyn/issues/9154")]
public void ErroneousIsPatternDefiniteAssignment()
{
var source =
@"class Program2
{
public static int Main() => 0;
void Dummy(object o) {}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0));
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,74): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(8, 74)
);
}
[Fact]
public void ERR_IsPatternImpossible()
{
var source =
@"class Program
{
public static void Main()
{
System.Console.WriteLine(""frog"" is string { Length: 4, Length: 5 });
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,34): error CS8415: An expression of type 'string' can never match the provided pattern.
// System.Console.WriteLine("frog" is string { Length: 4, Length: 5 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"""frog"" is string { Length: 4, Length: 5 }").WithArguments("string").WithLocation(5, 34)
);
}
[Fact]
public void WRN_GivenExpressionNeverMatchesPattern01()
{
var source =
@"class Program
{
public static void Main()
{
System.Console.WriteLine(3 is 4);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,34): warning CS8416: The given expression never matches the provided pattern.
// System.Console.WriteLine(3 is 4);
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "3 is 4").WithLocation(5, 34)
);
}
[Fact]
public void WRN_GivenExpressionNeverMatchesPattern02()
{
var source =
@"class Program
{
public static void Main()
{
const string s = null;
System.Console.WriteLine(s is string { Length: 3 });
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,34): warning CS8416: The given expression never matches the provided pattern.
// System.Console.WriteLine(s is string { Length: 3 });
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(6, 34)
);
}
[Fact]
public void DefiniteAssignmentForIsPattern01()
{
var source =
@"class Program
{
public static void Main()
{
string s = 300.ToString();
System.Console.WriteLine(s is string { Length: int j });
System.Console.WriteLine(j);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,34): error CS0165: Use of unassigned local variable 'j'
// System.Console.WriteLine(j);
Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(7, 34)
);
}
[Fact]
public void DefiniteAssignmentForIsPattern02()
{
var source =
@"class Program
{
public static void Main()
{
const string s = ""300"";
System.Console.WriteLine(s is string { Length: int j });
System.Console.WriteLine(j);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var expectedOutput = @"True
3";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void DefiniteAssignmentForIsPattern03()
{
var source =
@"class Program
{
public static void Main()
{
int j;
const string s = null;
if (s is string { Length: 3 })
{
System.Console.WriteLine(j);
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,13): warning CS8416: The given expression never matches the provided pattern.
// if (s is string { Length: 3 })
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(7, 13)
);
}
[Fact]
public void RefutableConstantPattern01()
{
var source =
@"class Program
{
public static void Main()
{
int j;
const int N = 3;
const int M = 3;
if (N is M)
{
}
else
{
System.Console.WriteLine(j);
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,13): warning CS8417: The given expression always matches the provided constant.
// if (N is M)
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "N is M").WithLocation(8, 13)
);
}
[Fact, WorkItem(25591, "https://github.com/dotnet/roslyn/issues/25591")]
public void TupleSubsumptionError()
{
var source =
@"class Program2
{
public static void Main()
{
M(new Fox());
M(new Cat());
M(new Program2());
}
static void M(object o)
{
switch ((o, 0))
{
case (Fox fox, _):
System.Console.Write(""Fox "");
break;
case (Cat cat, _):
System.Console.Write(""Cat"");
break;
}
}
}
class Fox {}
class Cat {}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"Fox Cat");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns01()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (c: 2, d: 3): // error: c and d not defined
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8416: The name 'c' does not identify tuple element 'Item1'.
// case (c: 2, d: 3): // error: c and d not defined
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "c").WithArguments("c", "Item1").WithLocation(7, 19),
// (7,25): error CS8416: The name 'd' does not identify tuple element 'Item2'.
// case (c: 2, d: 3): // error: c and d not defined
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "d").WithArguments("d", "Item2").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns02()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (a: 2, a: 3):
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,25): error CS8416: The name 'a' does not identify tuple element 'Item2'.
// case (a: 2, a: 3):
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "a").WithArguments("a", "Item2").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns03()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (a: 2, Item2: 3):
System.Console.WriteLine(666);
break;
case (a: 1, Item2: 2):
System.Console.WriteLine(111);
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"111");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns04()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (c: 2, d: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
public void Deconstruct(out int a, out int b) => (a, b) = (A, B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19),
// (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns05()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (c: 2, d: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
}
static class Extensions
{
public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19),
// (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns06()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, a: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
public void Deconstruct(out int a, out int b) => (a, b) = (A, B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (a: 2, a: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns07()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, a: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
}
static class Extensions
{
public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (a: 2, a: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns08()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, b: 3):
System.Console.WriteLine(666);
break;
case (a: 1, b: 2):
System.Console.WriteLine(111);
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
public void Deconstruct(out int a, out int b) => (a, b) = (A, B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"111");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns09()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, b: 3):
System.Console.WriteLine(666);
break;
case (a: 1, b: 2):
System.Console.WriteLine(111);
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
}
static class Extensions
{
public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"111");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns10()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (Item2: 1, 2):
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8416: The name 'Item2' does not identify tuple element 'Item1'.
// case (Item2: 1, 2):
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "Item2").WithArguments("Item2", "Item1").WithLocation(7, 19)
);
}
[Fact]
public void PropertyPatternMemberMissing01()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
if (b is Blah { X: int i })
{
}
}
}
class Blah
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,25): error CS0117: 'Blah' does not contain a definition for 'X'
// if (b is Blah { X: int i })
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(6, 25)
);
}
[Fact]
public void PropertyPatternMemberMissing02()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
if (b is Blah { X: int i })
{
}
}
}
class Blah
{
public int X { set {} }
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor
// if (b is Blah { X: int i })
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(6, 25)
);
}
[Fact]
public void PropertyPatternMemberMissing03()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
switch (b)
{
case Blah { X: int i }:
break;
}
}
}
class Blah
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,25): error CS0117: 'Blah' does not contain a definition for 'X'
// case Blah { X: int i }:
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(8, 25)
);
}
[Fact]
public void PropertyPatternMemberMissing04()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
switch (b)
{
case Blah { X: int i }:
break;
}
}
}
class Blah
{
public int X { set {} }
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor
// case Blah { X: int i }:
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(8, 25)
);
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter03()
{
var source =
@"class C<T>
{
internal struct S { }
static bool Test(S s)
{
return s is null;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (6,21): error CS0037: Cannot convert null to 'C<T>.S' because it is a non-nullable value type
// return s is null;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("C<T>.S").WithLocation(6, 21)
);
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter04()
{
var source =
@"class C<T>
{
static bool Test(C<T> x)
{
return x is 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (5,21): error CS8121: An expression of type 'C<T>' cannot be handled by a pattern of type 'int'.
// return x is 1;
Diagnostic(ErrorCode.ERR_PatternWrongType, "1").WithArguments("C<T>", "int").WithLocation(5, 21)
);
}
[Fact]
[WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")]
public void SpeculateWithNameConflict01()
{
var source =
@"public class Class1
{
int i = 1;
public override int GetHashCode() => 1;
public override bool Equals(object obj)
{
return obj is global::Class1 @class && this.i == @class.i;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
);
var tree = compilation.SyntaxTrees[0];
var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single();
Assert.Equal("return obj is global::Class1 @class && this.i == @class.i;", returnStatement.ToString());
var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement);
Assert.Equal("return obj is Class1 @class && this.i == @class.i;", modifiedReturnStatement.ToString());
var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel);
Assert.True(gotModel);
Assert.NotNull(speculativeModel);
var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression);
Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType);
}
/// <summary>
/// Helper class to remove alias qualifications.
/// </summary>
class RemoveAliasQualifiers : CSharpSyntaxRewriter
{
public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node)
{
return node.Name;
}
}
[Fact]
[WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")]
public void SpeculateWithNameConflict02()
{
var source =
@"public class Class1
{
public override int GetHashCode() => 1;
public override bool Equals(object obj)
{
return obj is global::Class1 @class;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
);
var tree = compilation.SyntaxTrees[0];
var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single();
Assert.Equal("return obj is global::Class1 @class;", returnStatement.ToString());
var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement);
Assert.Equal("return obj is Class1 @class;", modifiedReturnStatement.ToString());
var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel);
Assert.True(gotModel);
Assert.NotNull(speculativeModel);
var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression);
Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType);
}
[Fact]
public void WrongArity()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Point p = new Point() { X = 3, Y = 4 };
if (p is Point())
{
}
}
}
class Point
{
public int X, Y;
public void Deconstruct(out int X, out int Y) => (X, Y) = (this.X, this.Y);
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (6,23): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Point.Deconstruct(out int, out int)'
// if (p is Point())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "()").WithArguments("X", "Point.Deconstruct(out int, out int)").WithLocation(6, 23),
// (6,23): error CS8129: No suitable Deconstruct instance or extension method was found for type 'Point', with 0 out parameters and a void return type.
// if (p is Point())
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("Point", "0").WithLocation(6, 23)
);
}
[Fact]
public void GetTypeInfo_01()
{
var source =
@"class Program
{
static void Main(string[] args)
{
object o = null;
Point p = null;
if (o is Point(3, string { Length: 2 })) { }
if (p is (_, { })) { }
if (p is Point({ }, { }, { })) { }
if (p is Point(, { })) { }
}
}
class Point
{
public object X, Y;
public void Deconstruct(out object X, out object Y) => (X, Y) = (this.X, this.Y);
public Point(object X, object Y) => (this.X, this.Y) = (X, Y);
}
";
var expected = new[]
{
new { Source = "Point(3, string { Length: 2 })", Type = "System.Object", ConvertedType = "Point" },
new { Source = "3", Type = "System.Object", ConvertedType = "System.Int32" },
new { Source = "string { Length: 2 }", Type = "System.Object", ConvertedType = "System.String" },
new { Source = "2", Type = "System.Int32", ConvertedType = "System.Int32" },
new { Source = "(_, { })", Type = "Point", ConvertedType = "Point" },
new { Source = "_", Type = "System.Object", ConvertedType = "System.Object" },
new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" },
new { Source = "Point({ }, { }, { })", Type = "Point", ConvertedType = "Point" },
new { Source = "{ }", Type = "?", ConvertedType = "?" },
new { Source = "{ }", Type = "?", ConvertedType = "?" },
new { Source = "{ }", Type = "?", ConvertedType = "?" },
new { Source = "Point(, { })", Type = "Point", ConvertedType = "Point" },
new { Source = "", Type = "System.Object", ConvertedType = "System.Object" },
new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" },
};
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (10,24): error CS8504: Pattern missing
// if (p is Point(, { })) { }
Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(10, 24),
// (9,23): error CS1501: No overload for method 'Deconstruct' takes 3 arguments
// if (p is Point({ }, { }, { })) { }
Diagnostic(ErrorCode.ERR_BadArgCount, "({ }, { }, { })").WithArguments("Deconstruct", "3").WithLocation(9, 23),
// (9,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Point', with 3 out parameters and a void return type.
// if (p is Point({ }, { }, { })) { }
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "({ }, { }, { })").WithArguments("Point", "3").WithLocation(9, 23)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
int i = 0;
foreach (var pat in tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>())
{
var typeInfo = model.GetTypeInfo(pat);
var ex = expected[i++];
Assert.Equal(ex.Source, pat.ToString());
Assert.Equal(ex.Type, typeInfo.Type.ToTestDisplayString());
Assert.Equal(ex.ConvertedType, typeInfo.ConvertedType.ToTestDisplayString());
}
Assert.Equal(expected.Length, i);
}
[Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")]
public void MissingDeconstruct_01()
{
var source =
@"using System;
public class C {
public void M() {
_ = this is (a: 1);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (4,21): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// _ = this is (a: 1);
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 21),
// (4,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 1 out parameters and a void return type.
// _ = this is (a: 1);
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 21)
);
}
[Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")]
public void MissingDeconstruct_02()
{
var source =
@"using System;
public class C {
public void M() {
_ = this is C(a: 1);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (4,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// _ = this is C(a: 1);
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 22),
// (4,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 1 out parameters and a void return type.
// _ = this is C(a: 1);
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 22)
);
}
[Fact]
public void PatternTypeInfo_01()
{
var source = @"
public class C
{
void M(T1 t1)
{
if (t1 is T2 (var t3, t4: T4 t4) { V5 : T6 t5 }) {}
}
}
class T1
{
}
class T2 : T1
{
public T5 V5 = null;
public void Deconstruct(out T3 t3, out T4 t4) => throw null;
}
class T3
{
}
class T4
{
}
class T5
{
}
class T6 : T5
{
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray();
Assert.Equal(4, patterns.Length);
Assert.Equal("T2 (var t3, t4: T4 t4) { V5 : T6 t5 }", patterns[0].ToString());
var ti = model.GetTypeInfo(patterns[0]);
Assert.Equal("T1", ti.Type.ToTestDisplayString());
Assert.Equal("T2", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("var t3", patterns[1].ToString());
ti = model.GetTypeInfo(patterns[1]);
Assert.Equal("T3", ti.Type.ToTestDisplayString());
Assert.Equal("T3", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("T4 t4", patterns[2].ToString());
ti = model.GetTypeInfo(patterns[2]);
Assert.Equal("T4", ti.Type.ToTestDisplayString());
Assert.Equal("T4", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("T6 t5", patterns[3].ToString());
ti = model.GetTypeInfo(patterns[3]);
Assert.Equal("T5", ti.Type.ToTestDisplayString());
Assert.Equal("T6", ti.ConvertedType.ToTestDisplayString());
}
[Fact]
public void PatternTypeInfo_02()
{
var source = @"
public class C
{
void M(object o)
{
if (o is Point(3, 4.0)) {}
}
}
class Point
{
public void Deconstruct(out object o1, out System.IComparable o2) => throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray();
Assert.Equal(3, patterns.Length);
Assert.Equal("Point(3, 4.0)", patterns[0].ToString());
var ti = model.GetTypeInfo(patterns[0]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("3", patterns[1].ToString());
ti = model.GetTypeInfo(patterns[1]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("4.0", patterns[2].ToString());
ti = model.GetTypeInfo(patterns[2]);
Assert.Equal("System.IComparable", ti.Type.ToTestDisplayString());
Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString());
}
[Fact]
public void PatternTypeInfo_03()
{
var source = @"
public class C
{
void M(object o)
{
if (o is Point(3, 4.0) { Missing: Xyzzy }) {}
if (o is Q7 t) {}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?)
// if (o is Point(3, 4.0) { Missing: Xyzzy }) {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Point").WithArguments("Point").WithLocation(6, 18),
// (6,43): error CS0103: The name 'Xyzzy' does not exist in the current context
// if (o is Point(3, 4.0) { Missing: Xyzzy }) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "Xyzzy").WithArguments("Xyzzy").WithLocation(6, 43),
// (7,18): error CS0246: The type or namespace name 'Q7' could not be found (are you missing a using directive or an assembly reference?)
// if (o is Q7 t) {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Q7").WithArguments("Q7").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray();
Assert.Equal(5, patterns.Length);
Assert.Equal("Point(3, 4.0) { Missing: Xyzzy }", patterns[0].ToString());
var ti = model.GetTypeInfo(patterns[0]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("3", patterns[1].ToString());
ti = model.GetTypeInfo(patterns[1]);
Assert.Equal("?", ti.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.Type.TypeKind);
Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("4.0", patterns[2].ToString());
ti = model.GetTypeInfo(patterns[2]);
Assert.Equal("?", ti.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.Type.TypeKind);
Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("Xyzzy", patterns[3].ToString());
ti = model.GetTypeInfo(patterns[3]);
Assert.Equal("?", ti.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.Type.TypeKind);
Assert.Equal("?", ti.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind);
Assert.Equal("Q7 t", patterns[4].ToString());
ti = model.GetTypeInfo(patterns[4]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("Q7", ti.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind);
}
[Fact]
[WorkItem(34678, "https://github.com/dotnet/roslyn/issues/34678")]
public void ConstantPatternVsUnconstrainedTypeParameter05()
{
var source =
@"class C<T>
{
static bool Test1(T t)
{
return t is null; // 1
}
static bool Test2(C<T> t)
{
return t is null; // ok
}
static bool Test3(T t)
{
return t is 1; // 2
}
static bool Test4(T t)
{
return t is ""frog""; // 3
}
}";
CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics();
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (5,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version '8.0' or greater to match an open type with a constant pattern.
// return t is null; // 1
Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "null").WithArguments("T", "<null>", "8.0").WithLocation(5, 21),
// (13,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'int'. Please use language version '8.0' or greater to match an open type with a constant pattern.
// return t is 1; // 2
Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "1").WithArguments("T", "int", "8.0").WithLocation(13, 21),
// (17,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'string'. Please use language version '8.0' or greater to match an open type with a constant pattern.
// return t is "frog"; // 3
Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, @"""frog""").WithArguments("T", "string", "8.0").WithLocation(17, 21));
}
[Fact]
[WorkItem(34905, "https://github.com/dotnet/roslyn/issues/34905")]
public void ConstantPatternVsUnconstrainedTypeParameter06()
{
var source =
@"public class C<T>
{
public enum E
{
V1, V2
}
public void M()
{
switch (default(E))
{
case E.V1:
break;
}
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics();
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics();
}
[Fact]
public void WarnUnmatchedIsRelationalPattern()
{
var source =
@"public class C
{
public void M()
{
_ = 1 is < 0; // 1
_ = 1 is < 1; // 2
_ = 1 is < 2; // 3
_ = 1 is <= 0; // 4
_ = 1 is <= 1; // 5
_ = 1 is <= 2; // 6
_ = 1 is > 0; // 7
_ = 1 is > 1; // 8
_ = 1 is > 2; // 9
_ = 1 is >= 0; // 10
_ = 1 is >= 1; // 11
_ = 1 is >= 2; // 12
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (5,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is < 0; // 1
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 0").WithLocation(5, 13),
// (6,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is < 1; // 2
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 1").WithLocation(6, 13),
// (7,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is < 2; // 3
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is < 2").WithLocation(7, 13),
// (8,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is <= 0; // 4
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is <= 0").WithLocation(8, 13),
// (9,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is <= 1; // 5
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 1").WithLocation(9, 13),
// (10,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is <= 2; // 6
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 2").WithLocation(10, 13),
// (11,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is > 0; // 7
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is > 0").WithLocation(11, 13),
// (12,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is > 1; // 8
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 1").WithLocation(12, 13),
// (13,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is > 2; // 9
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 2").WithLocation(13, 13),
// (14,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is >= 0; // 10
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 0").WithLocation(14, 13),
// (15,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is >= 1; // 11
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 1").WithLocation(15, 13),
// (16,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is >= 2; // 12
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is >= 2").WithLocation(16, 13)
);
}
[Fact]
public void RelationalPatternInSwitchWithConstantControllingExpression()
{
var source =
@"public class C
{
public void M()
{
switch (1)
{
case < 0: break; // 1
case < 1: break; // 2
case < 2: break;
case < 3: break; // 3
}
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (7,23): warning CS0162: Unreachable code detected
// case < 0: break; // 1
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(7, 23),
// (8,23): warning CS0162: Unreachable code detected
// case < 1: break; // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(8, 23),
// (10,23): warning CS0162: Unreachable code detected
// case < 3: break; // 3
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 23)
);
}
[Fact]
public void RelationalPatternInSwitchWithOutOfRangeComparand()
{
var source =
@"public class C
{
public void M(int i)
{
switch (i)
{
case < int.MinValue: break; // 1
case <= int.MinValue: break;
case > int.MaxValue: break; // 2
case >= int.MaxValue: break;
}
}
public void M(uint i)
{
switch (i)
{
case < 0: break; // 3
case <= 0: break;
case > uint.MaxValue: break; // 4
case >= uint.MaxValue: break;
}
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case < int.MinValue: break; // 1
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< int.MinValue").WithLocation(7, 18),
// (9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case > int.MaxValue: break; // 2
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> int.MaxValue").WithLocation(9, 18),
// (17,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case < 0: break; // 3
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< 0").WithLocation(17, 18),
// (19,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case > uint.MaxValue: break; // 4
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> uint.MaxValue").WithLocation(19, 18)
);
}
[Fact]
public void IsRelationalPatternWithOutOfRangeComparand()
{
var source =
@"public class C
{
public void M(int i)
{
_ = i is < int.MinValue; // 1
_ = i is <= int.MinValue;
_ = i is > int.MaxValue; // 2
_ = i is >= int.MaxValue;
}
public void M(uint i)
{
_ = i is < 0; // 3
_ = i is <= 0;
_ = i is > uint.MaxValue; // 4
_ = i is >= uint.MaxValue;
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (5,13): error CS8518: An expression of type 'int' can never match the provided pattern.
// _ = i is < int.MinValue; // 1
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < int.MinValue").WithArguments("int").WithLocation(5, 13),
// (7,13): error CS8518: An expression of type 'int' can never match the provided pattern.
// _ = i is > int.MaxValue; // 2
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > int.MaxValue").WithArguments("int").WithLocation(7, 13),
// (12,13): error CS8518: An expression of type 'uint' can never match the provided pattern.
// _ = i is < 0; // 3
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < 0").WithArguments("uint").WithLocation(12, 13),
// (14,13): error CS8518: An expression of type 'uint' can never match the provided pattern.
// _ = i is > uint.MaxValue; // 4
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > uint.MaxValue").WithArguments("uint").WithLocation(14, 13)
);
}
[Fact]
public void IsRelationalPatternWithAlwaysMatchingRange()
{
var source =
@"public class C
{
public void M(int i)
{
_ = i is > int.MinValue;
_ = i is >= int.MinValue; // 1
_ = i is < int.MaxValue;
_ = i is <= int.MaxValue; // 2
}
public void M(uint i)
{
_ = i is > 0;
_ = i is >= 0; // 3
_ = i is < uint.MaxValue;
_ = i is <= uint.MaxValue; // 4
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (6,13): warning CS8794: An expression of type 'int' always matches the provided pattern.
// _ = i is >= int.MinValue; // 1
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= int.MinValue").WithArguments("int").WithLocation(6, 13),
// (8,13): warning CS8794: An expression of type 'int' always matches the provided pattern.
// _ = i is <= int.MaxValue; // 2
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= int.MaxValue").WithArguments("int").WithLocation(8, 13),
// (13,13): warning CS8794: An expression of type 'uint' always matches the provided pattern.
// _ = i is >= 0; // 3
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= 0").WithArguments("uint").WithLocation(13, 13),
// (15,13): warning CS8794: An expression of type 'uint' always matches the provided pattern.
// _ = i is <= uint.MaxValue; // 4
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= uint.MaxValue").WithArguments("uint").WithLocation(15, 13)
);
}
[Fact]
public void IsImpossiblePatternKinds()
{
var source =
@"public class C
{
public void M(string s)
{
_ = s is (System.Delegate); // impossible parenthesized type pattern
_ = s is not _; // impossible negated pattern
_ = s is ""a"" and ""b""; // impossible conjunctive pattern
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (5,19): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'.
// _ = s is (System.Delegate); // impossible parenthesized type pattern
Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(5, 19),
// (6,13): error CS8518: An expression of type 'string' can never match the provided pattern.
// _ = s is not _; // impossible negated pattern
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "s is not _").WithArguments("string").WithLocation(6, 13),
// (7,13): error CS8518: An expression of type 'string' can never match the provided pattern.
// _ = s is "a" and "b"; // impossible conjunctive pattern
Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"s is ""a"" and ""b""").WithArguments("string").WithLocation(7, 13)
);
}
[Fact]
public void IsNullableReferenceType_01()
{
var source =
@"#nullable enable
public class C {
public void M1(object o) {
var t = o is string? { };
}
public void M2(object o) {
var t = o is (string? { });
}
public void M3(object o) {
var t = o is string?;
}
public void M4(object o) {
var t = o is string? _;
}
public void M5(object o) {
var t = o is (string? _);
}
}";
CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (4,22): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead.
// var t = o is string? { };
Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(4, 22),
// (7,23): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead.
// var t = o is (string? { });
Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(7, 23),
// (10,22): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead.
// var t = o is string?;
Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(10, 22),
// (13,30): error CS0103: The name '_' does not exist in the current context
// var t = o is string? _;
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 30),
// (13,31): error CS1003: Syntax error, ':' expected
// var t = o is string? _;
Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(13, 31),
// (13,31): error CS1525: Invalid expression term ';'
// var t = o is string? _;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 31),
// (16,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// var t = o is (string? _);
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(string? _)").WithArguments("object", "2").WithLocation(16, 22),
// (16,29): error CS1003: Syntax error, ',' expected
// var t = o is (string? _);
Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(",", "?").WithLocation(16, 29),
// (16,31): error CS1003: Syntax error, ',' expected
// var t = o is (string? _);
Diagnostic(ErrorCode.ERR_SyntaxError, "_").WithArguments(",", "").WithLocation(16, 31)
);
}
[Fact]
public void IsAlwaysPatternKinds()
{
var source =
@"public class C
{
public void M(string s)
{
_ = s is (_); // always parenthesized discard pattern
_ = s is not System.Delegate; // always negated type pattern
_ = s is string or null; // always disjunctive pattern
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (6,22): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'.
// _ = s is not System.Delegate; // always negated type pattern
Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(6, 22),
// (7,13): warning CS8794: An expression of type 'string' always matches the provided pattern.
// _ = s is string or null; // always disjunctive pattern
Diagnostic(ErrorCode.WRN_IsPatternAlways, "s is string or null").WithArguments("string").WithLocation(7, 13)
);
}
[Fact]
public void SemanticModelForSwitchExpression()
{
var source =
@"public class C
{
void M(int i)
{
C x0 = i switch // 0
{
0 => new A(),
1 => new B(),
_ => throw null,
};
_ = i switch // 1
{
0 => new A(),
1 => new B(),
_ => throw null,
};
D x2 = i switch // 2
{
0 => new A(),
1 => new B(),
_ => throw null,
};
D x3 = i switch // 3
{
0 => new E(), // 3.1
1 => new F(), // 3.2
_ => throw null,
};
C x4 = i switch // 4
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
};
D x5 = i switch // 5
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
};
D x6 = i switch // 6
{
0 => 1,
1 => 2,
_ => throw null,
};
_ = (C)(i switch // 7
{
0 => new A(),
1 => new B(),
_ => throw null,
});
_ = (D)(i switch // 8
{
0 => new A(),
1 => new B(),
_ => throw null,
});
_ = (D)(i switch // 9
{
0 => new E(), // 9.1
1 => new F(), // 9.2
_ => throw null,
});
_ = (C)(i switch // 10
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
});
_ = (D)(i switch // 11
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
});
_ = (D)(i switch // 12
{
0 => 1,
1 => 2,
_ => throw null,
});
}
}
class A : C { }
class B : C { }
class D
{
public static implicit operator D(C c) => throw null;
public static implicit operator D(short s) => throw null;
}
class E
{
public static implicit operator C(E c) => throw null;
}
class F
{
public static implicit operator C(F c) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (11,15): error CS8506: No best type was found for the switch expression.
// _ = i switch // 1
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(11, 15),
// (25,18): error CS0029: Cannot implicitly convert type 'E' to 'D'
// 0 => new E(), // 3.1
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(25, 18),
// (26,18): error CS0029: Cannot implicitly convert type 'F' to 'D'
// 1 => new F(), // 3.2
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(26, 18),
// (63,18): error CS0029: Cannot implicitly convert type 'E' to 'D'
// 0 => new E(), // 9.1
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(63, 18),
// (64,18): error CS0029: Cannot implicitly convert type 'F' to 'D'
// 1 => new F(), // 9.2
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(64, 18)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
void checkType(ExpressionSyntax expr, string expectedNaturalType, string expectedConvertedType, ConversionKind expectedConversionKind)
{
var typeInfo = model.GetTypeInfo(expr);
var conversion = model.GetConversion(expr);
Assert.Equal(expectedNaturalType, typeInfo.Type?.ToTestDisplayString());
Assert.Equal(expectedConvertedType, typeInfo.ConvertedType?.ToTestDisplayString());
Assert.Equal(expectedConversionKind, conversion.Kind);
}
var switches = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray();
for (int i = 0; i < switches.Length; i++)
{
var expr = switches[i];
switch (i)
{
case 0:
checkType(expr, null, "C", ConversionKind.SwitchExpression);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 1:
checkType(expr, "?", "?", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "?", ConversionKind.NoConversion);
checkType(expr.Arms[1].Expression, "B", "?", ConversionKind.NoConversion);
checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow);
break;
case 2:
checkType(expr, null, "D", ConversionKind.SwitchExpression);
checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
break;
case 3:
checkType(expr, "?", "D", ConversionKind.NoConversion);
checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion);
checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion);
checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow);
break;
case 4:
case 10:
checkType(expr, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 5:
checkType(expr, "C", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 11:
checkType(expr, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 6:
checkType(expr, "System.Int32", "D", ConversionKind.SwitchExpression);
checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
break;
case 7:
checkType(expr, null, null, ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "C", "C", ConversionKind.Identity);
break;
case 8:
checkType(expr, null, null, ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity);
break;
case 9:
checkType(expr, "?", "?", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion);
checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion);
checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity);
break;
case 12:
checkType(expr, "System.Int32", "System.Int32", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity);
break;
default:
Assert.False(true);
break;
}
}
}
[Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")]
public void VoidPattern_01()
{
var source = @"
class C
{
void F(object o)
{
_ = is this.F(1);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,13): error CS1525: Invalid expression term 'is'
// _ = is this.F(1);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "is").WithArguments("is").WithLocation(6, 13)
);
}
[Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")]
public void VoidPattern_02()
{
var source = @"
class C
{
void F(object o)
{
_ = switch { this.F(1) => 1 };
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,13): error CS1525: Invalid expression term 'switch'
// _ = switch { this.F(1) => 1 };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "switch").WithArguments("switch").WithLocation(6, 13),
// (6,13): warning CS8848: Operator 'switch' cannot be used here due to precedence. Use parentheses to disambiguate.
// _ = switch { this.F(1) => 1 };
Diagnostic(ErrorCode.WRN_PrecedenceInversion, "switch").WithArguments("switch").WithLocation(6, 13)
);
}
[Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")]
public void NullableTypePattern()
{
var source = @"
class C
{
void F(object o)
{
_ = o switch { (int?) => 1, _ => 0 };
_ = o switch { int? => 1, _ => 0 };
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,25): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead.
// _ = o switch { (int?) => 1, _ => 0 };
Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(6, 25),
// (7,24): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead.
// _ = o switch { int? => 1, _ => 0 };
Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(7, 24)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.Patterns)]
public class PatternMatchingTests2 : PatternMatchingTestBase
{
[Fact]
public void Patterns2_00()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.WriteLine(1 is int {} x ? x : -1);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"1");
}
[Fact]
public void Patterns2_01()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Point p = new Point();
Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1));
Check(false, p is Point(1, 4) { Length: 5 });
Check(false, p is Point(3, 1) { Length: 5 });
Check(false, p is Point(3, 4) { Length: 1 });
Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2));
Check(false, p is (1, 4) { Length: 5 });
Check(false, p is (3, 1) { Length: 5 });
Check(false, p is (3, 4) { Length: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}
public class Point
{
public void Deconstruct(out int X, out int Y)
{
X = 3;
Y = 4;
}
public int Length => 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_02()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Point p = new Point();
Check(true, p is Point(3, 4) { Length: 5 } q1 && Check(p, q1));
Check(false, p is Point(1, 4) { Length: 5 });
Check(false, p is Point(3, 1) { Length: 5 });
Check(false, p is Point(3, 4) { Length: 1 });
Check(true, p is (3, 4) { Length: 5 } q2 && Check(p, q2));
Check(false, p is (1, 4) { Length: 5 });
Check(false, p is (3, 1) { Length: 5 });
Check(false, p is (3, 4) { Length: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}
public class Point
{
public int Length => 5;
}
public static class PointExtensions
{
public static void Deconstruct(this Point p, out int X, out int Y)
{
X = 3;
Y = 4;
}
}
";
// We use a compilation profile that provides System.Runtime.CompilerServices.ExtensionAttribute needed for this test
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_03()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
var p = (x: 3, y: 4);
Check(true, p is (3, 4) q1 && Check(p, q1));
Check(false, p is (1, 4) { x: 3 });
Check(false, p is (3, 1) { y: 4 });
Check(false, p is (3, 4) { x: 1 });
Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2));
Check(false, p is (1, 4) { x: 3 });
Check(false, p is (3, 1) { x: 3 });
Check(false, p is (3, 4) { x: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (1, 4) { x: 3 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(9, 22),
// (10,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (3, 1) { y: 4 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 1) { y: 4 }").WithArguments("(int x, int y)").WithLocation(10, 22),
// (11,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (3, 4) { x: 1 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(11, 22),
// (13,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (1, 4) { x: 3 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (1, 4) { x: 3 }").WithArguments("(int x, int y)").WithLocation(13, 22),
// (15,22): error CS8415: An expression of type '(int x, int y)' can never match the provided pattern.
// Check(false, p is (3, 4) { x: 1 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "p is (3, 4) { x: 1 }").WithArguments("(int x, int y)").WithLocation(15, 22)
);
}
[Fact]
public void Patterns2_04b()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
var p = (x: 3, y: 4);
Check(true, p is (3, 4) q1 && Check(p, q1));
Check(true, p is (3, 4) { x: 3 } q2 && Check(p, q2));
Check(false, p is (3, 1) { x: 3 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_DiscardPattern_01()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Point p = new Point();
Check(true, p is Point(_, _) { Length: _ } q1 && Check(p, q1));
Check(false, p is Point(1, _) { Length: _ });
Check(false, p is Point(_, 1) { Length: _ });
Check(false, p is Point(_, _) { Length: 1 });
Check(true, p is (_, _) { Length: _ } q2 && Check(p, q2));
Check(false, p is (1, _) { Length: _ });
Check(false, p is (_, 1) { Length: _ });
Check(false, p is (_, _) { Length: 1 });
}
private static bool Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""expected: {expected}; actual: {actual}"");
return true;
}
}
public class Point
{
public void Deconstruct(out int X, out int Y)
{
X = 3;
Y = 4;
}
public int Length => 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "");
}
[Fact]
public void Patterns2_Switch01()
{
var sourceTemplate =
@"
class Program
{{
public static void Main()
{{
var p = (true, false);
switch (p)
{{
{0}
{1}
{2}
case (_, _): // error - subsumed
break;
}}
}}
}}";
void testErrorCase(string s1, string s2, string s3)
{
var source = string.Format(sourceTemplate, s1, s2, s3);
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (12,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case (_, _): // error - subsumed
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "(_, _)").WithLocation(12, 18)
);
}
void testGoodCase(string s1, string s2)
{
var source = string.Format(sourceTemplate, s1, s2, string.Empty);
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
var c1 = "case (true, _):";
var c2 = "case (false, false):";
var c3 = "case (_, true):";
testErrorCase(c1, c2, c3);
testErrorCase(c2, c3, c1);
testErrorCase(c3, c1, c2);
testErrorCase(c1, c3, c2);
testErrorCase(c3, c2, c1);
testErrorCase(c2, c1, c3);
testGoodCase(c1, c2);
testGoodCase(c1, c3);
testGoodCase(c2, c3);
testGoodCase(c2, c1);
testGoodCase(c3, c1);
testGoodCase(c3, c2);
}
[Fact]
public void Patterns2_Switch02()
{
var source =
@"
class Program
{
public static void Main()
{
Point p = new Point();
switch (p)
{
case Point(3, 4) { Length: 5 }:
System.Console.WriteLine(true);
break;
default:
System.Console.WriteLine(false);
break;
}
}
}
public class Point
{
public void Deconstruct(out int X, out int Y)
{
X = 3;
Y = 4;
}
public int Length => 5;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: "True");
}
[Fact]
public void DefaultPattern()
{
var source =
@"class Program
{
public static void Main()
{
int i = 12;
if (i is default) {} // error 1
if (i is (default)) {} // error 2
switch (i) { case default: break; } // error 3
switch (i) { case default when true: break; } // error 4
switch ((1, 2)) { case (1, default): break; } // error 5
if (i is < default) {} // error 6
switch (i) { case < default: break; } // error 7
if (i is < ((default))) {} // error 8
switch (i) { case < ((default)): break; } // error 9
if (i is default!) {} // error 10
if (i is (default!)) {} // error 11
if (i is < ((default)!)) {} // error 12
if (i is default!!) {} // error 13
if (i is (default!!)) {} // error 14
if (i is < ((default)!!)) {} // error 15
// These are not accepted by the parser. See https://github.com/dotnet/roslyn/issues/45387
if (i is (default)!) {} // error 16
if (i is ((default)!)) {} // error 17
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is default) {} // error 1
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 18),
// (7,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default)) {} // error 2
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(7, 19),
// (8,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case default: break; } // error 3
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 27),
// (9,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case default when true: break; } // error 4
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27),
// (10,36): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch ((1, 2)) { case (1, default): break; } // error 5
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 36),
// (12,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < default) {} // error 6
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 20),
// (13,29): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case < default: break; } // error 7
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(13, 29),
// (14,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < ((default))) {} // error 8
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(14, 22),
// (15,31): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// switch (i) { case < ((default)): break; } // error 9
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(15, 31),
// (17,18): error CS8598: The suppression operator is not allowed in this context
// if (i is default!) {} // error 10
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(17, 18),
// (17,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is default!) {} // error 10
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(17, 18),
// (18,19): error CS8598: The suppression operator is not allowed in this context
// if (i is (default!)) {} // error 11
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(18, 19),
// (18,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default!)) {} // error 11
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(18, 19),
// (19,21): error CS8598: The suppression operator is not allowed in this context
// if (i is < ((default)!)) {} // error 12
Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(19, 21),
// (19,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < ((default)!)) {} // error 12
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(19, 22),
// (20,18): error CS8598: The suppression operator is not allowed in this context
// if (i is default!!) {} // error 13
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(20, 18),
// (20,18): error CS8598: The suppression operator is not allowed in this context
// if (i is default!!) {} // error 13
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(20, 18),
// (20,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is default!!) {} // error 13
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(20, 18),
// (21,19): error CS8598: The suppression operator is not allowed in this context
// if (i is (default!!)) {} // error 14
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!!").WithLocation(21, 19),
// (21,19): error CS8598: The suppression operator is not allowed in this context
// if (i is (default!!)) {} // error 14
Diagnostic(ErrorCode.ERR_IllegalSuppression, "default!").WithLocation(21, 19),
// (21,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default!!)) {} // error 14
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(21, 19),
// (22,21): error CS8598: The suppression operator is not allowed in this context
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!!").WithLocation(22, 21),
// (22,21): error CS8598: The suppression operator is not allowed in this context
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_IllegalSuppression, "(default)!").WithLocation(22, 21),
// (22,22): error CS8715: Duplicate null suppression operator ('!')
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(22, 22),
// (22,22): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is < ((default)!!)) {} // error 15
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(22, 22),
// (25,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(25, 19),
// (25,27): error CS1026: ) expected
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(25, 27),
// (25,28): error CS1525: Invalid expression term ')'
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(25, 28),
// (25,28): error CS1002: ; expected
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(25, 28),
// (25,28): error CS1513: } expected
// if (i is (default)!) {} // error 16
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(25, 28),
// (26,18): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'int', with 2 out parameters and a void return type.
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "((default)!)").WithArguments("int", "2").WithLocation(26, 18),
// (26,20): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(26, 20),
// (26,28): error CS1003: Syntax error, ',' expected
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(26, 28),
// (26,29): error CS1525: Invalid expression term ')'
// if (i is ((default)!)) {} // error 17
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(26, 29)
);
}
[Fact]
public void SwitchExpression_01()
{
// test appropriate language version or feature flag
var source =
@"class Program
{
public static void Main()
{
var r = 1 switch { _ => 0, };
}
}";
CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns).VerifyDiagnostics(
// (5,17): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater.
// var r = 1 switch { _ => 0, };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { _ => 0, }").WithArguments("recursive patterns", "8.0").WithLocation(5, 17)
);
CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void SwitchExpression_02()
{
// test switch expression's governing expression has no type
// test switch expression's governing expression has type void
var source =
@"class Program
{
public static void Main()
{
var r1 = (1, null) switch { _ => 0 };
var r2 = System.Console.Write(1) switch { _ => 0 };
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (5,18): error CS8117: Invalid operand for pattern match; value required, but found '(int, <null>)'.
// var r1 = (1, null) switch ( _ => 0 );
Diagnostic(ErrorCode.ERR_BadPatternExpression, "(1, null)").WithArguments("(int, <null>)").WithLocation(5, 18),
// (6,18): error CS8117: Invalid operand for pattern match; value required, but found 'void'.
// var r2 = System.Console.Write(1) switch ( _ => 0 );
Diagnostic(ErrorCode.ERR_BadPatternExpression, "System.Console.Write(1)").WithArguments("void").WithLocation(6, 18)
);
}
[Fact]
public void SwitchExpression_03()
{
// test that a ternary expression is not at an appropriate precedence
// for the constant expression of a constant pattern in a switch expression arm.
var source =
@"class Program
{
public static void Main()
{
bool b = true;
var r1 = b switch { true ? true : true => true, false => false };
var r2 = b switch { (true ? true : true) => true, false => false };
}
}";
// This is admittedly poor syntax error recovery (for the line declaring r2),
// but this test demonstrates that it is a syntax error.
CreatePatternCompilation(source).VerifyDiagnostics(
// (6,34): error CS1003: Syntax error, '=>' expected
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(6, 34),
// (6,34): error CS1525: Invalid expression term '?'
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(6, 34),
// (6,48): error CS1003: Syntax error, ',' expected
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 48),
// (6,48): error CS8504: Pattern missing
// var r1 = b switch { true ? true : true => true, false => false };
Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(6, 48)
);
}
[Fact]
public void SwitchExpression_04()
{
// test that a ternary expression is permitted as a constant pattern in recursive contexts and the case expression.
var source =
@"class Program
{
public static void Main()
{
var b = (true, false);
var r1 = b switch { (true ? true : true, _) => true, _ => false, };
var r2 = b is (true ? true : true, _);
switch (b.Item1) { case true ? true : true: break; }
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
);
}
[Fact]
public void SwitchExpression_05()
{
// test throw expression in match arm.
var source =
@"class Program
{
public static void Main()
{
var x = 1 switch { 1 => 1, _ => throw null };
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
);
}
[Fact]
public void EmptySwitchExpression()
{
var source =
@"class Program
{
public static void Main()
{
var r = 1 switch { };
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// var r = 1 switch { };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 19),
// (5,19): error CS8506: No best type was found for the switch expression.
// var r = 1 switch { };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(5, 19));
}
[Fact]
public void SwitchExpression_06()
{
// test common type vs delegate in match expression
var source =
@"class Program
{
public static void Main()
{
var x = 1 switch { 0 => M, 1 => new D(M), 2 => M };
x();
}
public static void M() {}
public delegate void D();
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (5,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '3' is not covered.
// var x = 1 switch { 0 => M, 1 => new D(M), 2 => M };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("3").WithLocation(5, 19)
);
}
[Fact]
public void SwitchExpression_07()
{
// test flow analysis of the switch expression
var source =
@"class Program
{
public static void Main()
{
int q = 1;
int u;
var x = q switch { 0 => u=0, 1 => u=1, _ => u=2 };
System.Console.WriteLine(u);
}
}";
CreatePatternCompilation(source).VerifyDiagnostics(
);
}
[Fact]
public void SwitchExpression_08()
{
// test flow analysis of the switch expression
var source =
@"class Program
{
public static void Main()
{
int q = 1;
int u;
var x = q switch { 0 => u=0, 1 => 1, _ => u=2 };
System.Console.WriteLine(u);
}
static int M(int i) => i;
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (8,34): error CS0165: Use of unassigned local variable 'u'
// System.Console.WriteLine(u);
Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(8, 34)
);
}
[Fact]
public void SwitchExpression_09()
{
// test flow analysis of the switch expression
var source =
@"class Program
{
public static void Main()
{
int q = 1;
int u;
var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2, };
System.Console.WriteLine(u);
}
static int M(int i) => i;
}";
CreatePatternCompilation(source).VerifyDiagnostics(
// (7,47): error CS0165: Use of unassigned local variable 'u'
// var x = q switch { 0 => u=0, 1 => u=M(u), _ => u=2 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "u").WithArguments("u").WithLocation(7, 47)
);
}
[Fact]
public void SwitchExpression_10()
{
// test lazily inferring variables in the pattern
// test lazily inferring variables in the when clause
// test lazily inferring variables in the arrow expression
var source =
@"class Program
{
public static void Main()
{
int a = 1;
var b = a switch { var x1 => x1, };
var c = a switch { var x2 when x2 is var x3 => x3 };
var d = a switch { var x4 => x4 is var x5 ? x5 : 1, };
}
static int M(int i) => i;
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. However, a pattern with a 'when' clause might successfully match this value.
// var c = a switch { var x2 when x2 is var x3 => x3 };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("_").WithLocation(7, 19)
);
var names = new[] { "x1", "x2", "x3", "x4", "x5" };
var tree = compilation.SyntaxTrees[0];
foreach (var designation in tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>())
{
var model = compilation.GetSemanticModel(tree);
var symbol = model.GetDeclaredSymbol(designation);
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal("int", ((ILocalSymbol)symbol).Type.ToDisplayString());
}
foreach (var ident in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>())
{
var model = compilation.GetSemanticModel(tree);
var typeInfo = model.GetTypeInfo(ident);
Assert.Equal("int", typeInfo.Type.ToDisplayString());
}
}
[Fact]
public void ShortDiscardInIsPattern()
{
// test that we forbid a short discard at the top level of an is-pattern expression
var source =
@"class Program
{
public static void Main()
{
int a = 1;
if (a is _) { }
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// if (a is _) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(6, 18)
);
}
[Fact]
public void Patterns2_04()
{
// Test that a single-element deconstruct pattern is an error if no further elements disambiguate.
var source =
@"
using System;
class Program
{
public static void Main()
{
var t = new System.ValueTuple<int>(1);
if (t is (int x)) { } // error 1
switch (t) { case (_): break; } // error 2
var u = t switch { (int y) => y, _ => 2 }; // error 3
if (t is (int z1) _) { } // ok
if (t is (Item1: int z2)) { } // ok
if (t is (int z3) { }) { } // ok
if (t is ValueTuple<int>(int z4)) { } // ok
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8);
compilation.VerifyDiagnostics(
// (8,18): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater.
// if (t is (int x)) { } // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x)").WithArguments("parenthesized pattern", "9.0").WithLocation(8, 18),
// (8,19): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'.
// if (t is (int x)) { } // error 1
Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(8, 19),
// (9,27): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater.
// switch (t) { case (_): break; } // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(_)").WithArguments("parenthesized pattern", "9.0").WithLocation(9, 27),
// (10,28): error CS8400: Feature 'parenthesized pattern' is not available in C# 8.0. Please use language version 9.0 or greater.
// var u = t switch { (int y) => y, _ => 2 }; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int y)").WithArguments("parenthesized pattern", "9.0").WithLocation(10, 28),
// (10,29): error CS8121: An expression of type 'ValueTuple<int>' cannot be handled by a pattern of type 'int'.
// var u = t switch { (int y) => y, _ => 2 }; // error 3
Diagnostic(ErrorCode.ERR_PatternWrongType, "int").WithArguments("System.ValueTuple<int>", "int").WithLocation(10, 29)
);
}
[Fact]
public void Patterns2_05()
{
// Test parsing the var pattern
// Test binding the var pattern
// Test lowering the var pattern for the is-expression
var source =
@"
using System;
class Program
{
public static void Main()
{
var t = (1, 2);
{ Check(true, t is var (x, y) && x == 1 && y == 2); }
{ Check(false, t is var (x, y) && x == 1 && y == 3); }
}
private static void Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'"");
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"");
}
[Fact]
public void Patterns2_06()
{
// Test that 'var' does not bind to a type
var source =
@"
using System;
namespace N
{
class Program
{
public static void Main()
{
var t = (1, 2);
{ Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
{ Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
{ Check(true, t is var x); } // error 3
}
private static void Check<T>(T expected, T actual)
{
if (!object.Equals(expected, actual)) throw new Exception($""Expected: '{expected}', Actual: '{actual}'"");
}
}
class var { }
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (9,21): error CS0029: Cannot implicitly convert type '(int, int)' to 'N.var'
// var t = (1, 2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "(1, 2)").WithArguments("(int, int)", "N.var").WithLocation(9, 21),
// (10,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here.
// { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(10, 32),
// (10,36): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?)
// { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(10, 36),
// (10,36): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type.
// { Check(true, t is var (x, y) && x == 1 && y == 2); } // error 1
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(10, 36),
// (11,33): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here.
// { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(11, 33),
// (11,37): error CS1061: 'var' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'var' could be found (are you missing a using directive or an assembly reference?)
// { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(x, y)").WithArguments("N.var", "Deconstruct").WithLocation(11, 37),
// (11,37): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'var', with 2 out parameters and a void return type.
// { Check(false, t is var (x, y) && x == 1 && y == 3); } // error 2
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(x, y)").WithArguments("N.var", "2").WithLocation(11, 37),
// (12,32): error CS8508: The syntax 'var' for a pattern is not permitted to refer to a type, but 'N.var' is in scope here.
// { Check(true, t is var x); } // error 3
Diagnostic(ErrorCode.ERR_VarMayNotBindToType, "var").WithArguments("N.var").WithLocation(12, 32)
);
}
[Fact]
public void Patterns2_10()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.Write(M((false, false)));
Console.Write(M((false, true)));
Console.Write(M((true, false)));
Console.Write(M((true, true)));
}
private static int M((bool, bool) t)
{
switch (t)
{
case (false, false): return 0;
case (false, _): return 1;
case (_, false): return 2;
case var _: return 3;
}
}
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"0123");
}
[Fact]
public void Patterns2_11()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.Write(M((false, false)));
Console.Write(M((false, true)));
Console.Write(M((true, false)));
Console.Write(M((true, true)));
}
private static int M((bool, bool) t)
{
switch (t)
{
case (false, false): return 0;
case (false, _): return 1;
case (_, false): return 2;
case (true, true): return 3;
case var _: return 4;
}
}
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (20,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case var _: return 4;
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "var _").WithLocation(20, 18)
);
}
[Fact]
public void Patterns2_12()
{
var source =
@"
using System;
class Program
{
public static void Main()
{
Console.Write(M((false, false)));
Console.Write(M((false, true)));
Console.Write(M((true, false)));
Console.Write(M((true, true)));
}
private static int M((bool, bool) t)
{
return t switch {
(false, false) => 0,
(false, _) => 1,
(_, false) => 2,
_ => 3
};
}
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"0123");
}
[Fact]
public void SwitchArmSubsumed()
{
var source =
@"public class X
{
public static void Main()
{
string s = string.Empty;
string s2 = s switch { null => null, string t => t, ""foo"" => null };
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,61): error CS8410: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.
// string s2 = s switch { null => null, string t => t, "foo" => null };
Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, @"""foo""").WithLocation(6, 61)
);
}
[Fact]
public void LongTuples()
{
var source =
@"using System;
public class X
{
public static void Main()
{
var t = (1, 2, 3, 4, 5, 6, 7, 8, 9);
{
Console.WriteLine(t is (_, _, _, _, _, _, _, _, var t9) ? t9 : 100);
}
switch (t)
{
case (_, _, _, _, _, _, _, _, var t9):
Console.WriteLine(t9);
break;
}
Console.WriteLine(t switch { (_, _, _, _, _, _, _, _, var t9) => t9 });
}
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"9
9
9");
}
[Fact]
public void TypeCheckInPropertyPattern()
{
var source =
@"using System;
class Program2
{
public static void Main()
{
object o = new Frog(1, 2);
if (o is Frog(1, 2))
{
Console.Write(1);
}
if (o is Frog { A: 1, B: 2 })
{
Console.Write(2);
}
if (o is Frog(1, 2) { A: 1, B: 2, C: 3 })
{
Console.Write(3);
}
if (o is Frog(9, 2) { A: 1, B: 2, C: 3 }) {} else
{
Console.Write(4);
}
if (o is Frog(1, 9) { A: 1, B: 2, C: 3 }) {} else
{
Console.Write(5);
}
if (o is Frog(1, 2) { A: 9, B: 2, C: 3 }) {} else
{
Console.Write(6);
}
if (o is Frog(1, 2) { A: 1, B: 9, C: 3 }) {} else
{
Console.Write(7);
}
if (o is Frog(1, 2) { A: 1, B: 2, C: 9 }) {} else
{
Console.Write(8);
}
}
}
class Frog
{
public object A, B;
public object C => (int)A + (int)B;
public Frog(object A, object B) => (this.A, this.B) = (A, B);
public void Deconstruct(out object A, out object B) => (A, B) = (this.A, this.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"12345678");
}
[Fact]
public void OvereagerSubsumption()
{
var source =
@"class Program2
{
public static int Main() => 0;
public static void M(object o)
{
switch (o)
{
case (1, 2):
break;
case string s:
break;
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source); // doesn't have ITuple
// Two errors below instead of one due to https://github.com/dotnet/roslyn/issues/25533
compilation.VerifyDiagnostics(
// (8,18): error CS1061: 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
// case (1, 2):
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(1, 2)").WithArguments("object", "Deconstruct").WithLocation(8, 18),
// (8,18): error CS8129: No suitable Deconstruct instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// case (1, 2):
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(1, 2)").WithArguments("object", "2").WithLocation(8, 18)
);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_01()
{
var source =
@"class Program0
{
static int Main() => 0;
private const int _ = 1;
bool M1(object o) => o is _;
bool M2(object o) => o switch { 1 => true, _ => false };
}
class Program1
{
class _ {}
bool M3(object o) => o is _;
bool M4(object o) => o switch { 1 => true, _ => false };
}
";
var expected = new[]
{
// (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// bool M1(object o) => o is _;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31),
// (11,31): warning CS8513: The name '_' refers to the type 'Program1._', not the discard pattern. Use '@_' for the type, or 'var _' to discard.
// bool M3(object o) => o is _;
Diagnostic(ErrorCode.WRN_IsTypeNamedUnderscore, "_").WithArguments("Program1._").WithLocation(11, 31)
};
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(expected);
compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8);
compilation.VerifyDiagnostics(expected);
expected = new[]
{
// (5,31): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// bool M1(object o) => o is _;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(5, 31),
// (6,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater.
// bool M2(object o) => o switch { 1 => true, _ => false };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(6, 26),
// (12,26): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater.
// bool M4(object o) => o switch { 1 => true, _ => false };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "o switch { 1 => true, _ => false }").WithArguments("recursive patterns", "8.0").WithLocation(12, 26)
};
compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(expected);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_02()
{
var source =
@"class Program0
{
static int Main() => 0;
private const int _ = 1;
}
class Program1 : Program0
{
bool M2(object o) => o switch { 1 => true, _ => false }; // ok, private member not inherited
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_03()
{
var source =
@"class Program0
{
static int Main() => 0;
protected const int _ = 1;
}
class Program1 : Program0
{
bool M2(object o) => o switch { 1 => true, _ => false };
}
class Program2
{
bool _(object q) => true;
bool M2(object o) => o switch { 1 => true, _ => false };
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void UnderscoreDeclaredAndDiscardPattern_04()
{
var source =
@"using _ = System.Int32;
class Program
{
static int Main() => 0;
bool M2(object o) => o switch { 1 => true, _ => false };
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using _ = System.Int32;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using _ = System.Int32;").WithLocation(1, 1)
);
}
[Fact]
public void EscapingUnderscoreDeclaredAndDiscardPattern_04()
{
var source =
@"class Program0
{
static int Main() => 0;
private const int _ = 2;
bool M1(object o) => o is @_;
int M2(object o) => o switch { 1 => 1, @_ => 2, var _ => 3 };
}
class Program1
{
class _ {}
bool M1(object o) => o is @_;
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
}
[Fact]
public void ErroneousSwitchArmDefiniteAssignment()
{
// When a switch expression arm is erroneous, ensure that the expression is treated as unreachable (e.g. for definite assignment purposes).
var source =
@"class Program2
{
public static int Main() => 0;
public static void M(string s)
{
int i;
int j = s switch { ""frog"" => 1, 0 => i, _ => 2 };
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,41): error CS0029: Cannot implicitly convert type 'int' to 'string'
// int j = s switch { "frog" => 1, 0 => i, _ => 2 };
Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "string").WithLocation(7, 41)
);
}
[Fact, WorkItem(9154, "https://github.com/dotnet/roslyn/issues/9154")]
public void ErroneousIsPatternDefiniteAssignment()
{
var source =
@"class Program2
{
public static int Main() => 0;
void Dummy(object o) {}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => o1 is int x5 &&
o2 is int x5 &&
x5 > 0));
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,74): error CS0128: A local variable or function named 'x5' is already defined in this scope
// o2 is int x5 &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(8, 74)
);
}
[Fact]
public void ERR_IsPatternImpossible()
{
var source =
@"class Program
{
public static void Main()
{
System.Console.WriteLine(""frog"" is string { Length: 4, Length: 5 });
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,34): error CS8415: An expression of type 'string' can never match the provided pattern.
// System.Console.WriteLine("frog" is string { Length: 4, Length: 5 });
Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"""frog"" is string { Length: 4, Length: 5 }").WithArguments("string").WithLocation(5, 34)
);
}
[Fact]
public void WRN_GivenExpressionNeverMatchesPattern01()
{
var source =
@"class Program
{
public static void Main()
{
System.Console.WriteLine(3 is 4);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (5,34): warning CS8416: The given expression never matches the provided pattern.
// System.Console.WriteLine(3 is 4);
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "3 is 4").WithLocation(5, 34)
);
}
[Fact]
public void WRN_GivenExpressionNeverMatchesPattern02()
{
var source =
@"class Program
{
public static void Main()
{
const string s = null;
System.Console.WriteLine(s is string { Length: 3 });
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,34): warning CS8416: The given expression never matches the provided pattern.
// System.Console.WriteLine(s is string { Length: 3 });
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(6, 34)
);
}
[Fact]
public void DefiniteAssignmentForIsPattern01()
{
var source =
@"class Program
{
public static void Main()
{
string s = 300.ToString();
System.Console.WriteLine(s is string { Length: int j });
System.Console.WriteLine(j);
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,34): error CS0165: Use of unassigned local variable 'j'
// System.Console.WriteLine(j);
Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(7, 34)
);
}
[Fact]
public void DefiniteAssignmentForIsPattern02()
{
var source =
@"class Program
{
public static void Main()
{
const string s = ""300"";
System.Console.WriteLine(s is string { Length: int j });
System.Console.WriteLine(j);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var expectedOutput = @"True
3";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void DefiniteAssignmentForIsPattern03()
{
var source =
@"class Program
{
public static void Main()
{
int j;
const string s = null;
if (s is string { Length: 3 })
{
System.Console.WriteLine(j);
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,13): warning CS8416: The given expression never matches the provided pattern.
// if (s is string { Length: 3 })
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string { Length: 3 }").WithLocation(7, 13)
);
}
[Fact]
public void RefutableConstantPattern01()
{
var source =
@"class Program
{
public static void Main()
{
int j;
const int N = 3;
const int M = 3;
if (N is M)
{
}
else
{
System.Console.WriteLine(j);
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,13): warning CS8417: The given expression always matches the provided constant.
// if (N is M)
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "N is M").WithLocation(8, 13)
);
}
[Fact, WorkItem(25591, "https://github.com/dotnet/roslyn/issues/25591")]
public void TupleSubsumptionError()
{
var source =
@"class Program2
{
public static void Main()
{
M(new Fox());
M(new Cat());
M(new Program2());
}
static void M(object o)
{
switch ((o, 0))
{
case (Fox fox, _):
System.Console.Write(""Fox "");
break;
case (Cat cat, _):
System.Console.Write(""Cat"");
break;
}
}
}
class Fox {}
class Cat {}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"Fox Cat");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns01()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (c: 2, d: 3): // error: c and d not defined
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8416: The name 'c' does not identify tuple element 'Item1'.
// case (c: 2, d: 3): // error: c and d not defined
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "c").WithArguments("c", "Item1").WithLocation(7, 19),
// (7,25): error CS8416: The name 'd' does not identify tuple element 'Item2'.
// case (c: 2, d: 3): // error: c and d not defined
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "d").WithArguments("d", "Item2").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns02()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (a: 2, a: 3):
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,25): error CS8416: The name 'a' does not identify tuple element 'Item2'.
// case (a: 2, a: 3):
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "a").WithArguments("a", "Item2").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns03()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (a: 2, Item2: 3):
System.Console.WriteLine(666);
break;
case (a: 1, Item2: 2):
System.Console.WriteLine(111);
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"111");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns04()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (c: 2, d: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
public void Deconstruct(out int a, out int b) => (a, b) = (A, B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19),
// (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns05()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (c: 2, d: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
}
static class Extensions
{
public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8417: The name 'c' does not match the corresponding 'Deconstruct' parameter 'a'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "c").WithArguments("c", "a").WithLocation(7, 19),
// (7,25): error CS8417: The name 'd' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (c: 2, d: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "d").WithArguments("d", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns06()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, a: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
public void Deconstruct(out int a, out int b) => (a, b) = (A, B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (a: 2, a: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns07()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, a: 3):
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
}
static class Extensions
{
public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,25): error CS8417: The name 'a' does not match the corresponding 'Deconstruct' parameter 'b'.
// case (a: 2, a: 3):
Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "a").WithArguments("a", "b").WithLocation(7, 25)
);
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns08()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, b: 3):
System.Console.WriteLine(666);
break;
case (a: 1, b: 2):
System.Console.WriteLine(111);
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
public void Deconstruct(out int a, out int b) => (a, b) = (A, B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"111");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns09()
{
var source =
@"class Program
{
static void Main()
{
switch (new T(a: 1, b: 2))
{
case (a: 2, b: 3):
System.Console.WriteLine(666);
break;
case (a: 1, b: 2):
System.Console.WriteLine(111);
break;
}
}
}
class T
{
public int A;
public int B;
public T(int a, int b) => (A, B) = (a, b);
}
static class Extensions
{
public static void Deconstruct(this T t, out int a, out int b) => (a, b) = (t.A, t.B);
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
);
var comp = CompileAndVerify(compilation, expectedOutput: @"111");
}
[Fact, WorkItem(25934, "https://github.com/dotnet/roslyn/issues/25934")]
public void NamesInPositionalPatterns10()
{
var source =
@"class Program
{
static void Main()
{
switch (a: 1, b: 2)
{
case (Item2: 1, 2):
break;
}
}
}
";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8416: The name 'Item2' does not identify tuple element 'Item1'.
// case (Item2: 1, 2):
Diagnostic(ErrorCode.ERR_TupleElementNameMismatch, "Item2").WithArguments("Item2", "Item1").WithLocation(7, 19)
);
}
[Fact]
public void PropertyPatternMemberMissing01()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
if (b is Blah { X: int i })
{
}
}
}
class Blah
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,25): error CS0117: 'Blah' does not contain a definition for 'X'
// if (b is Blah { X: int i })
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(6, 25)
);
}
[Fact]
public void PropertyPatternMemberMissing02()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
if (b is Blah { X: int i })
{
}
}
}
class Blah
{
public int X { set {} }
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (6,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor
// if (b is Blah { X: int i })
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(6, 25)
);
}
[Fact]
public void PropertyPatternMemberMissing03()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
switch (b)
{
case Blah { X: int i }:
break;
}
}
}
class Blah
{
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,25): error CS0117: 'Blah' does not contain a definition for 'X'
// case Blah { X: int i }:
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("Blah", "X").WithLocation(8, 25)
);
}
[Fact]
public void PropertyPatternMemberMissing04()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Blah b = null;
switch (b)
{
case Blah { X: int i }:
break;
}
}
}
class Blah
{
public int X { set {} }
}";
var compilation = CreatePatternCompilation(source);
compilation.VerifyDiagnostics(
// (8,25): error CS0154: The property or indexer 'Blah.X' cannot be used in this context because it lacks the get accessor
// case Blah { X: int i }:
Diagnostic(ErrorCode.ERR_PropertyLacksGet, "X:").WithArguments("Blah.X").WithLocation(8, 25)
);
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter03()
{
var source =
@"class C<T>
{
internal struct S { }
static bool Test(S s)
{
return s is null;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (6,21): error CS0037: Cannot convert null to 'C<T>.S' because it is a non-nullable value type
// return s is null;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("C<T>.S").WithLocation(6, 21)
);
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter04()
{
var source =
@"class C<T>
{
static bool Test(C<T> x)
{
return x is 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (5,21): error CS8121: An expression of type 'C<T>' cannot be handled by a pattern of type 'int'.
// return x is 1;
Diagnostic(ErrorCode.ERR_PatternWrongType, "1").WithArguments("C<T>", "int").WithLocation(5, 21)
);
}
[Fact]
[WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")]
public void SpeculateWithNameConflict01()
{
var source =
@"public class Class1
{
int i = 1;
public override int GetHashCode() => 1;
public override bool Equals(object obj)
{
return obj is global::Class1 @class && this.i == @class.i;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
);
var tree = compilation.SyntaxTrees[0];
var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single();
Assert.Equal("return obj is global::Class1 @class && this.i == @class.i;", returnStatement.ToString());
var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement);
Assert.Equal("return obj is Class1 @class && this.i == @class.i;", modifiedReturnStatement.ToString());
var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel);
Assert.True(gotModel);
Assert.NotNull(speculativeModel);
var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression);
Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType);
}
/// <summary>
/// Helper class to remove alias qualifications.
/// </summary>
class RemoveAliasQualifiers : CSharpSyntaxRewriter
{
public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node)
{
return node.Name;
}
}
[Fact]
[WorkItem(20724, "https://github.com/dotnet/roslyn/issues/20724")]
public void SpeculateWithNameConflict02()
{
var source =
@"public class Class1
{
public override int GetHashCode() => 1;
public override bool Equals(object obj)
{
return obj is global::Class1 @class;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
);
var tree = compilation.SyntaxTrees[0];
var model = (CSharpSemanticModel)compilation.GetSemanticModel(tree);
var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single();
Assert.Equal("return obj is global::Class1 @class;", returnStatement.ToString());
var modifiedReturnStatement = (ReturnStatementSyntax)new RemoveAliasQualifiers().Visit(returnStatement);
Assert.Equal("return obj is Class1 @class;", modifiedReturnStatement.ToString());
var gotModel = model.TryGetSpeculativeSemanticModel(returnStatement.Location.SourceSpan.Start, modifiedReturnStatement, out var speculativeModel);
Assert.True(gotModel);
Assert.NotNull(speculativeModel);
var typeInfo = speculativeModel.GetTypeInfo(modifiedReturnStatement.Expression);
Assert.Equal(SpecialType.System_Boolean, typeInfo.Type.SpecialType);
}
[Fact]
public void WrongArity()
{
var source =
@"class Program
{
static void Main(string[] args)
{
Point p = new Point() { X = 3, Y = 4 };
if (p is Point())
{
}
}
}
class Point
{
public int X, Y;
public void Deconstruct(out int X, out int Y) => (X, Y) = (this.X, this.Y);
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (6,23): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Point.Deconstruct(out int, out int)'
// if (p is Point())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "()").WithArguments("X", "Point.Deconstruct(out int, out int)").WithLocation(6, 23),
// (6,23): error CS8129: No suitable Deconstruct instance or extension method was found for type 'Point', with 0 out parameters and a void return type.
// if (p is Point())
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("Point", "0").WithLocation(6, 23)
);
}
[Fact]
public void GetTypeInfo_01()
{
var source =
@"class Program
{
static void Main(string[] args)
{
object o = null;
Point p = null;
if (o is Point(3, string { Length: 2 })) { }
if (p is (_, { })) { }
if (p is Point({ }, { }, { })) { }
if (p is Point(, { })) { }
}
}
class Point
{
public object X, Y;
public void Deconstruct(out object X, out object Y) => (X, Y) = (this.X, this.Y);
public Point(object X, object Y) => (this.X, this.Y) = (X, Y);
}
";
var expected = new[]
{
new { Source = "Point(3, string { Length: 2 })", Type = "System.Object", ConvertedType = "Point" },
new { Source = "3", Type = "System.Object", ConvertedType = "System.Int32" },
new { Source = "string { Length: 2 }", Type = "System.Object", ConvertedType = "System.String" },
new { Source = "2", Type = "System.Int32", ConvertedType = "System.Int32" },
new { Source = "(_, { })", Type = "Point", ConvertedType = "Point" },
new { Source = "_", Type = "System.Object", ConvertedType = "System.Object" },
new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" },
new { Source = "Point({ }, { }, { })", Type = "Point", ConvertedType = "Point" },
new { Source = "{ }", Type = "?", ConvertedType = "?" },
new { Source = "{ }", Type = "?", ConvertedType = "?" },
new { Source = "{ }", Type = "?", ConvertedType = "?" },
new { Source = "Point(, { })", Type = "Point", ConvertedType = "Point" },
new { Source = "", Type = "System.Object", ConvertedType = "System.Object" },
new { Source = "{ }", Type = "System.Object", ConvertedType = "System.Object" },
};
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (10,24): error CS8504: Pattern missing
// if (p is Point(, { })) { }
Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(10, 24),
// (9,23): error CS1501: No overload for method 'Deconstruct' takes 3 arguments
// if (p is Point({ }, { }, { })) { }
Diagnostic(ErrorCode.ERR_BadArgCount, "({ }, { }, { })").WithArguments("Deconstruct", "3").WithLocation(9, 23),
// (9,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Point', with 3 out parameters and a void return type.
// if (p is Point({ }, { }, { })) { }
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "({ }, { }, { })").WithArguments("Point", "3").WithLocation(9, 23)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
int i = 0;
foreach (var pat in tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>())
{
var typeInfo = model.GetTypeInfo(pat);
var ex = expected[i++];
Assert.Equal(ex.Source, pat.ToString());
Assert.Equal(ex.Type, typeInfo.Type.ToTestDisplayString());
Assert.Equal(ex.ConvertedType, typeInfo.ConvertedType.ToTestDisplayString());
}
Assert.Equal(expected.Length, i);
}
[Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")]
public void MissingDeconstruct_01()
{
var source =
@"using System;
public class C {
public void M() {
_ = this is (a: 1);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (4,21): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// _ = this is (a: 1);
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 21),
// (4,21): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 1 out parameters and a void return type.
// _ = this is (a: 1);
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 21)
);
}
[Fact, WorkItem(26613, "https://github.com/dotnet/roslyn/issues/26613")]
public void MissingDeconstruct_02()
{
var source =
@"using System;
public class C {
public void M() {
_ = this is C(a: 1);
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (4,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// _ = this is C(a: 1);
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "(a: 1)").WithArguments("C", "Deconstruct").WithLocation(4, 22),
// (4,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 1 out parameters and a void return type.
// _ = this is C(a: 1);
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(a: 1)").WithArguments("C", "1").WithLocation(4, 22)
);
}
[Fact]
public void PatternTypeInfo_01()
{
var source = @"
public class C
{
void M(T1 t1)
{
if (t1 is T2 (var t3, t4: T4 t4) { V5 : T6 t5 }) {}
}
}
class T1
{
}
class T2 : T1
{
public T5 V5 = null;
public void Deconstruct(out T3 t3, out T4 t4) => throw null;
}
class T3
{
}
class T4
{
}
class T5
{
}
class T6 : T5
{
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray();
Assert.Equal(4, patterns.Length);
Assert.Equal("T2 (var t3, t4: T4 t4) { V5 : T6 t5 }", patterns[0].ToString());
var ti = model.GetTypeInfo(patterns[0]);
Assert.Equal("T1", ti.Type.ToTestDisplayString());
Assert.Equal("T2", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("var t3", patterns[1].ToString());
ti = model.GetTypeInfo(patterns[1]);
Assert.Equal("T3", ti.Type.ToTestDisplayString());
Assert.Equal("T3", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("T4 t4", patterns[2].ToString());
ti = model.GetTypeInfo(patterns[2]);
Assert.Equal("T4", ti.Type.ToTestDisplayString());
Assert.Equal("T4", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("T6 t5", patterns[3].ToString());
ti = model.GetTypeInfo(patterns[3]);
Assert.Equal("T5", ti.Type.ToTestDisplayString());
Assert.Equal("T6", ti.ConvertedType.ToTestDisplayString());
}
[Fact]
public void PatternTypeInfo_02()
{
var source = @"
public class C
{
void M(object o)
{
if (o is Point(3, 4.0)) {}
}
}
class Point
{
public void Deconstruct(out object o1, out System.IComparable o2) => throw null;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray();
Assert.Equal(3, patterns.Length);
Assert.Equal("Point(3, 4.0)", patterns[0].ToString());
var ti = model.GetTypeInfo(patterns[0]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("3", patterns[1].ToString());
ti = model.GetTypeInfo(patterns[1]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("4.0", patterns[2].ToString());
ti = model.GetTypeInfo(patterns[2]);
Assert.Equal("System.IComparable", ti.Type.ToTestDisplayString());
Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString());
}
[Fact]
public void PatternTypeInfo_03()
{
var source = @"
public class C
{
void M(object o)
{
if (o is Point(3, 4.0) { Missing: Xyzzy }) {}
if (o is Q7 t) {}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0246: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?)
// if (o is Point(3, 4.0) { Missing: Xyzzy }) {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Point").WithArguments("Point").WithLocation(6, 18),
// (6,43): error CS0103: The name 'Xyzzy' does not exist in the current context
// if (o is Point(3, 4.0) { Missing: Xyzzy }) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "Xyzzy").WithArguments("Xyzzy").WithLocation(6, 43),
// (7,18): error CS0246: The type or namespace name 'Q7' could not be found (are you missing a using directive or an assembly reference?)
// if (o is Q7 t) {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Q7").WithArguments("Q7").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var patterns = tree.GetRoot().DescendantNodesAndSelf().OfType<PatternSyntax>().ToArray();
Assert.Equal(5, patterns.Length);
Assert.Equal("Point(3, 4.0) { Missing: Xyzzy }", patterns[0].ToString());
var ti = model.GetTypeInfo(patterns[0]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("Point", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("3", patterns[1].ToString());
ti = model.GetTypeInfo(patterns[1]);
Assert.Equal("?", ti.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.Type.TypeKind);
Assert.Equal("System.Int32", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("4.0", patterns[2].ToString());
ti = model.GetTypeInfo(patterns[2]);
Assert.Equal("?", ti.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.Type.TypeKind);
Assert.Equal("System.Double", ti.ConvertedType.ToTestDisplayString());
Assert.Equal("Xyzzy", patterns[3].ToString());
ti = model.GetTypeInfo(patterns[3]);
Assert.Equal("?", ti.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.Type.TypeKind);
Assert.Equal("?", ti.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind);
Assert.Equal("Q7 t", patterns[4].ToString());
ti = model.GetTypeInfo(patterns[4]);
Assert.Equal("System.Object", ti.Type.ToTestDisplayString());
Assert.Equal("Q7", ti.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, ti.ConvertedType.TypeKind);
}
[Fact]
[WorkItem(34678, "https://github.com/dotnet/roslyn/issues/34678")]
public void ConstantPatternVsUnconstrainedTypeParameter05()
{
var source =
@"class C<T>
{
static bool Test1(T t)
{
return t is null; // 1
}
static bool Test2(C<T> t)
{
return t is null; // ok
}
static bool Test3(T t)
{
return t is 1; // 2
}
static bool Test4(T t)
{
return t is ""frog""; // 3
}
}";
CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics();
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(
// (5,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version '8.0' or greater to match an open type with a constant pattern.
// return t is null; // 1
Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "null").WithArguments("T", "<null>", "8.0").WithLocation(5, 21),
// (13,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'int'. Please use language version '8.0' or greater to match an open type with a constant pattern.
// return t is 1; // 2
Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, "1").WithArguments("T", "int", "8.0").WithLocation(13, 21),
// (17,21): error CS8511: An expression of type 'T' cannot be handled by a pattern of type 'string'. Please use language version '8.0' or greater to match an open type with a constant pattern.
// return t is "frog"; // 3
Diagnostic(ErrorCode.ERR_ConstantPatternVsOpenType, @"""frog""").WithArguments("T", "string", "8.0").WithLocation(17, 21));
}
[Fact]
[WorkItem(34905, "https://github.com/dotnet/roslyn/issues/34905")]
public void ConstantPatternVsUnconstrainedTypeParameter06()
{
var source =
@"public class C<T>
{
public enum E
{
V1, V2
}
public void M()
{
switch (default(E))
{
case E.V1:
break;
}
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll).VerifyDiagnostics();
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics();
}
[Fact]
public void WarnUnmatchedIsRelationalPattern()
{
var source =
@"public class C
{
public void M()
{
_ = 1 is < 0; // 1
_ = 1 is < 1; // 2
_ = 1 is < 2; // 3
_ = 1 is <= 0; // 4
_ = 1 is <= 1; // 5
_ = 1 is <= 2; // 6
_ = 1 is > 0; // 7
_ = 1 is > 1; // 8
_ = 1 is > 2; // 9
_ = 1 is >= 0; // 10
_ = 1 is >= 1; // 11
_ = 1 is >= 2; // 12
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (5,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is < 0; // 1
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 0").WithLocation(5, 13),
// (6,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is < 1; // 2
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is < 1").WithLocation(6, 13),
// (7,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is < 2; // 3
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is < 2").WithLocation(7, 13),
// (8,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is <= 0; // 4
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is <= 0").WithLocation(8, 13),
// (9,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is <= 1; // 5
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 1").WithLocation(9, 13),
// (10,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is <= 2; // 6
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is <= 2").WithLocation(10, 13),
// (11,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is > 0; // 7
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is > 0").WithLocation(11, 13),
// (12,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is > 1; // 8
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 1").WithLocation(12, 13),
// (13,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is > 2; // 9
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is > 2").WithLocation(13, 13),
// (14,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is >= 0; // 10
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 0").WithLocation(14, 13),
// (15,13): error CS8793: The given expression always matches the provided pattern.
// _ = 1 is >= 1; // 11
Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesPattern, "1 is >= 1").WithLocation(15, 13),
// (16,13): warning CS8519: The given expression never matches the provided pattern.
// _ = 1 is >= 2; // 12
Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is >= 2").WithLocation(16, 13)
);
}
[Fact]
public void RelationalPatternInSwitchWithConstantControllingExpression()
{
var source =
@"public class C
{
public void M()
{
switch (1)
{
case < 0: break; // 1
case < 1: break; // 2
case < 2: break;
case < 3: break; // 3
}
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (7,23): warning CS0162: Unreachable code detected
// case < 0: break; // 1
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(7, 23),
// (8,23): warning CS0162: Unreachable code detected
// case < 1: break; // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(8, 23),
// (10,23): warning CS0162: Unreachable code detected
// case < 3: break; // 3
Diagnostic(ErrorCode.WRN_UnreachableCode, "break").WithLocation(10, 23)
);
}
[Fact]
public void RelationalPatternInSwitchWithOutOfRangeComparand()
{
var source =
@"public class C
{
public void M(int i)
{
switch (i)
{
case < int.MinValue: break; // 1
case <= int.MinValue: break;
case > int.MaxValue: break; // 2
case >= int.MaxValue: break;
}
}
public void M(uint i)
{
switch (i)
{
case < 0: break; // 3
case <= 0: break;
case > uint.MaxValue: break; // 4
case >= uint.MaxValue: break;
}
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (7,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case < int.MinValue: break; // 1
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< int.MinValue").WithLocation(7, 18),
// (9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case > int.MaxValue: break; // 2
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> int.MaxValue").WithLocation(9, 18),
// (17,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case < 0: break; // 3
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "< 0").WithLocation(17, 18),
// (19,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
// case > uint.MaxValue: break; // 4
Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "> uint.MaxValue").WithLocation(19, 18)
);
}
[Fact]
public void IsRelationalPatternWithOutOfRangeComparand()
{
var source =
@"public class C
{
public void M(int i)
{
_ = i is < int.MinValue; // 1
_ = i is <= int.MinValue;
_ = i is > int.MaxValue; // 2
_ = i is >= int.MaxValue;
}
public void M(uint i)
{
_ = i is < 0; // 3
_ = i is <= 0;
_ = i is > uint.MaxValue; // 4
_ = i is >= uint.MaxValue;
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (5,13): error CS8518: An expression of type 'int' can never match the provided pattern.
// _ = i is < int.MinValue; // 1
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < int.MinValue").WithArguments("int").WithLocation(5, 13),
// (7,13): error CS8518: An expression of type 'int' can never match the provided pattern.
// _ = i is > int.MaxValue; // 2
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > int.MaxValue").WithArguments("int").WithLocation(7, 13),
// (12,13): error CS8518: An expression of type 'uint' can never match the provided pattern.
// _ = i is < 0; // 3
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is < 0").WithArguments("uint").WithLocation(12, 13),
// (14,13): error CS8518: An expression of type 'uint' can never match the provided pattern.
// _ = i is > uint.MaxValue; // 4
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "i is > uint.MaxValue").WithArguments("uint").WithLocation(14, 13)
);
}
[Fact]
public void IsRelationalPatternWithAlwaysMatchingRange()
{
var source =
@"public class C
{
public void M(int i)
{
_ = i is > int.MinValue;
_ = i is >= int.MinValue; // 1
_ = i is < int.MaxValue;
_ = i is <= int.MaxValue; // 2
}
public void M(uint i)
{
_ = i is > 0;
_ = i is >= 0; // 3
_ = i is < uint.MaxValue;
_ = i is <= uint.MaxValue; // 4
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (6,13): warning CS8794: An expression of type 'int' always matches the provided pattern.
// _ = i is >= int.MinValue; // 1
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= int.MinValue").WithArguments("int").WithLocation(6, 13),
// (8,13): warning CS8794: An expression of type 'int' always matches the provided pattern.
// _ = i is <= int.MaxValue; // 2
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= int.MaxValue").WithArguments("int").WithLocation(8, 13),
// (13,13): warning CS8794: An expression of type 'uint' always matches the provided pattern.
// _ = i is >= 0; // 3
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is >= 0").WithArguments("uint").WithLocation(13, 13),
// (15,13): warning CS8794: An expression of type 'uint' always matches the provided pattern.
// _ = i is <= uint.MaxValue; // 4
Diagnostic(ErrorCode.WRN_IsPatternAlways, "i is <= uint.MaxValue").WithArguments("uint").WithLocation(15, 13)
);
}
[Fact]
public void IsImpossiblePatternKinds()
{
var source =
@"public class C
{
public void M(string s)
{
_ = s is (System.Delegate); // impossible parenthesized type pattern
_ = s is not _; // impossible negated pattern
_ = s is ""a"" and ""b""; // impossible conjunctive pattern
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (5,19): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'.
// _ = s is (System.Delegate); // impossible parenthesized type pattern
Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(5, 19),
// (6,13): error CS8518: An expression of type 'string' can never match the provided pattern.
// _ = s is not _; // impossible negated pattern
Diagnostic(ErrorCode.ERR_IsPatternImpossible, "s is not _").WithArguments("string").WithLocation(6, 13),
// (7,13): error CS8518: An expression of type 'string' can never match the provided pattern.
// _ = s is "a" and "b"; // impossible conjunctive pattern
Diagnostic(ErrorCode.ERR_IsPatternImpossible, @"s is ""a"" and ""b""").WithArguments("string").WithLocation(7, 13)
);
}
[Fact]
public void IsNullableReferenceType_01()
{
var source =
@"#nullable enable
public class C {
public void M1(object o) {
var t = o is string? { };
}
public void M2(object o) {
var t = o is (string? { });
}
public void M3(object o) {
var t = o is string?;
}
public void M4(object o) {
var t = o is string? _;
}
public void M5(object o) {
var t = o is (string? _);
}
}";
CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (4,22): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead.
// var t = o is string? { };
Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(4, 22),
// (7,23): error CS8116: It is not legal to use nullable type 'string?' in a pattern; use the underlying type 'string' instead.
// var t = o is (string? { });
Diagnostic(ErrorCode.ERR_PatternNullableType, "string?").WithArguments("string").WithLocation(7, 23),
// (10,22): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead.
// var t = o is string?;
Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(10, 22),
// (13,30): error CS0103: The name '_' does not exist in the current context
// var t = o is string? _;
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 30),
// (13,31): error CS1003: Syntax error, ':' expected
// var t = o is string? _;
Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(13, 31),
// (13,31): error CS1525: Invalid expression term ';'
// var t = o is string? _;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(13, 31),
// (16,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'object', with 2 out parameters and a void return type.
// var t = o is (string? _);
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(string? _)").WithArguments("object", "2").WithLocation(16, 22),
// (16,29): error CS1003: Syntax error, ',' expected
// var t = o is (string? _);
Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(",", "?").WithLocation(16, 29),
// (16,31): error CS1003: Syntax error, ',' expected
// var t = o is (string? _);
Diagnostic(ErrorCode.ERR_SyntaxError, "_").WithArguments(",", "").WithLocation(16, 31)
);
}
[Fact]
public void IsAlwaysPatternKinds()
{
var source =
@"public class C
{
public void M(string s)
{
_ = s is (_); // always parenthesized discard pattern
_ = s is not System.Delegate; // always negated type pattern
_ = s is string or null; // always disjunctive pattern
}
}
";
CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (6,22): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'Delegate'.
// _ = s is not System.Delegate; // always negated type pattern
Diagnostic(ErrorCode.ERR_PatternWrongType, "System.Delegate").WithArguments("string", "System.Delegate").WithLocation(6, 22),
// (7,13): warning CS8794: An expression of type 'string' always matches the provided pattern.
// _ = s is string or null; // always disjunctive pattern
Diagnostic(ErrorCode.WRN_IsPatternAlways, "s is string or null").WithArguments("string").WithLocation(7, 13)
);
}
[Fact]
public void SemanticModelForSwitchExpression()
{
var source =
@"public class C
{
void M(int i)
{
C x0 = i switch // 0
{
0 => new A(),
1 => new B(),
_ => throw null,
};
_ = i switch // 1
{
0 => new A(),
1 => new B(),
_ => throw null,
};
D x2 = i switch // 2
{
0 => new A(),
1 => new B(),
_ => throw null,
};
D x3 = i switch // 3
{
0 => new E(), // 3.1
1 => new F(), // 3.2
_ => throw null,
};
C x4 = i switch // 4
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
};
D x5 = i switch // 5
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
};
D x6 = i switch // 6
{
0 => 1,
1 => 2,
_ => throw null,
};
_ = (C)(i switch // 7
{
0 => new A(),
1 => new B(),
_ => throw null,
});
_ = (D)(i switch // 8
{
0 => new A(),
1 => new B(),
_ => throw null,
});
_ = (D)(i switch // 9
{
0 => new E(), // 9.1
1 => new F(), // 9.2
_ => throw null,
});
_ = (C)(i switch // 10
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
});
_ = (D)(i switch // 11
{
0 => new A(),
1 => new B(),
2 => new C(),
_ => throw null,
});
_ = (D)(i switch // 12
{
0 => 1,
1 => 2,
_ => throw null,
});
}
}
class A : C { }
class B : C { }
class D
{
public static implicit operator D(C c) => throw null;
public static implicit operator D(short s) => throw null;
}
class E
{
public static implicit operator C(E c) => throw null;
}
class F
{
public static implicit operator C(F c) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (11,15): error CS8506: No best type was found for the switch expression.
// _ = i switch // 1
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(11, 15),
// (25,18): error CS0029: Cannot implicitly convert type 'E' to 'D'
// 0 => new E(), // 3.1
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(25, 18),
// (26,18): error CS0029: Cannot implicitly convert type 'F' to 'D'
// 1 => new F(), // 3.2
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(26, 18),
// (63,18): error CS0029: Cannot implicitly convert type 'E' to 'D'
// 0 => new E(), // 9.1
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new E()").WithArguments("E", "D").WithLocation(63, 18),
// (64,18): error CS0029: Cannot implicitly convert type 'F' to 'D'
// 1 => new F(), // 9.2
Diagnostic(ErrorCode.ERR_NoImplicitConv, "new F()").WithArguments("F", "D").WithLocation(64, 18)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
void checkType(ExpressionSyntax expr, string expectedNaturalType, string expectedConvertedType, ConversionKind expectedConversionKind)
{
var typeInfo = model.GetTypeInfo(expr);
var conversion = model.GetConversion(expr);
Assert.Equal(expectedNaturalType, typeInfo.Type?.ToTestDisplayString());
Assert.Equal(expectedConvertedType, typeInfo.ConvertedType?.ToTestDisplayString());
Assert.Equal(expectedConversionKind, conversion.Kind);
}
var switches = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray();
for (int i = 0; i < switches.Length; i++)
{
var expr = switches[i];
switch (i)
{
case 0:
checkType(expr, null, "C", ConversionKind.SwitchExpression);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 1:
checkType(expr, "?", "?", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "?", ConversionKind.NoConversion);
checkType(expr.Arms[1].Expression, "B", "?", ConversionKind.NoConversion);
checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow);
break;
case 2:
checkType(expr, null, "D", ConversionKind.SwitchExpression);
checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
break;
case 3:
checkType(expr, "?", "D", ConversionKind.NoConversion);
checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion);
checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion);
checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow);
break;
case 4:
case 10:
checkType(expr, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 5:
checkType(expr, "C", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 11:
checkType(expr, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, "C", "C", ConversionKind.Identity);
checkType(expr.Arms[3].Expression, null, "C", ConversionKind.ImplicitThrow);
break;
case 6:
checkType(expr, "System.Int32", "D", ConversionKind.SwitchExpression);
checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
break;
case 7:
checkType(expr, null, null, ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[1].Expression, "B", "C", ConversionKind.ImplicitReference);
checkType(expr.Arms[2].Expression, null, "C", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "C", "C", ConversionKind.Identity);
break;
case 8:
checkType(expr, null, null, ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "A", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "B", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity);
break;
case 9:
checkType(expr, "?", "?", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "E", "?", ConversionKind.NoConversion);
checkType(expr.Arms[1].Expression, "F", "?", ConversionKind.NoConversion);
checkType(expr.Arms[2].Expression, null, "?", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity);
break;
case 12:
checkType(expr, "System.Int32", "System.Int32", ConversionKind.Identity);
checkType(expr.Arms[0].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[1].Expression, "System.Int32", "D", ConversionKind.ImplicitUserDefined);
checkType(expr.Arms[2].Expression, null, "D", ConversionKind.ImplicitThrow);
checkType((CastExpressionSyntax)expr.Parent.Parent, "D", "D", ConversionKind.Identity);
break;
default:
Assert.False(true);
break;
}
}
}
[Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")]
public void VoidPattern_01()
{
var source = @"
class C
{
void F(object o)
{
_ = is this.F(1);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,13): error CS1525: Invalid expression term 'is'
// _ = is this.F(1);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "is").WithArguments("is").WithLocation(6, 13)
);
}
[Fact, WorkItem(45946, "https://github.com/dotnet/roslyn/issues/45946")]
public void VoidPattern_02()
{
var source = @"
class C
{
void F(object o)
{
_ = switch { this.F(1) => 1 };
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,13): error CS1525: Invalid expression term 'switch'
// _ = switch { this.F(1) => 1 };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "switch").WithArguments("switch").WithLocation(6, 13),
// (6,13): warning CS8848: Operator 'switch' cannot be used here due to precedence. Use parentheses to disambiguate.
// _ = switch { this.F(1) => 1 };
Diagnostic(ErrorCode.WRN_PrecedenceInversion, "switch").WithArguments("switch").WithLocation(6, 13)
);
}
[Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")]
public void NullableTypePattern()
{
var source = @"
class C
{
void F(object o)
{
_ = o switch { (int?) => 1, _ => 0 };
_ = o switch { int? => 1, _ => 0 };
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,25): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead.
// _ = o switch { (int?) => 1, _ => 0 };
Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(6, 25),
// (7,24): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead.
// _ = o switch { int? => 1, _ => 0 };
Diagnostic(ErrorCode.ERR_PatternNullableType, "int?").WithArguments("int").WithLocation(7, 24)
);
}
[Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")]
public void SharedWhenExpression_SwitchExpression()
{
var source = @"
int count = 0;
foreach (var position in new[] { Position.First, Position.Last })
{
foreach (var wrap in new[] { new Wrap { Sub = new Zero() }, new Wrap { Sub = new One() }, new Wrap { Sub = new Two() }, new Wrap { Sub = new object() } })
{
count++;
if (M(position, wrap) != M2(position, wrap))
throw null;
}
}
System.Console.Write(count);
static string M(Position position, Wrap wrap)
{
return position switch
{
not Position.First when wrap.Sub is Zero => ""Not First and Zero"",
_ when wrap is { Sub: One or Two } => ""One or Two"",
Position.First => ""First"",
_ => ""Other""
};
}
static string M2(Position position, Wrap wrap)
{
if (position is not Position.First && wrap.Sub is Zero)
return ""Not First and Zero"";
if (wrap is { Sub: One or Two })
return ""One or Two"";
if (position is Position.First)
return ""First"";
return ""Other"";
}
enum Position
{
First,
Last,
}
class Zero { }
class One { }
class Two { }
class Wrap
{
public object Sub;
}
";
CompileAndVerify(source, expectedOutput: "8");
}
[Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")]
public void SharedWhenExpression_SwitchStatement()
{
var source = @"
M(Position.Last, new Wrap { Sub = new Zero() });
M(Position.Last, new Wrap { Sub = new One() });
M(Position.Last, new Wrap { Sub = new Two() });
M(Position.First, new Wrap { Sub = new Zero() });
M(Position.Last, new Wrap { Sub = new object() });
static void M(Position position, Wrap wrap)
{
string text;
switch (position)
{
case not Position.First when wrap.Sub is Zero: text = ""Not First and Zero""; break;
case var _ when wrap is { Sub: One or Two }: text = ""One or Two""; break;
case Position.First: text = ""First""; break;
default: text = ""Other""; break;
}
System.Console.WriteLine((position, wrap.Sub, text));
}
enum Position
{
First,
Last,
}
class Zero { }
class One { }
class Two { }
class Wrap
{
public object Sub;
}
";
CompileAndVerify(source, expectedOutput: @"
(Last, Zero, Not First and Zero)
(Last, One, One or Two)
(Last, Two, One or Two)
(First, Zero, First)
(Last, System.Object, Other)");
}
[Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")]
public void SharedWhenExpression_SequencePoints()
{
var source = @"
C.M(0, false, false);
C.M(0, true, false);
C.M(0, false, true);
C.M(1, false, false);
C.M(1, false, true);
C.M(2, false, false);
public class C
{
public static void M(int i, bool b1, bool b2)
{
string text;
switch (i)
{
case not 1 when b1:
text = ""b1"";
break;
case var _ when b2:
text = ""b2"";
break;
case 1:
text = ""1"";
break;
default:
text = ""default"";
break;
}
System.Console.WriteLine((i, b1, b2, text));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"
(0, False, False, default)
(0, True, False, b1)
(0, False, True, b2)
(1, False, False, 1)
(1, False, True, b2)
(2, False, False, default)
");
verifier.VerifyIL("C.M", @"
{
// Code size 73 (0x49)
.maxstack 4
.locals init (string V_0, //text
int V_1)
// sequence point: switch (i)
IL_0000: ldarg.0
// sequence point: <hidden>
IL_0001: ldc.i4.1
IL_0002: beq.s IL_000f
// sequence point: when b1
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0013
// sequence point: text = ""b1"";
IL_0007: ldstr ""b1""
IL_000c: stloc.0
// sequence point: break;
IL_000d: br.s IL_0035
// sequence point: <hidden>
IL_000f: ldc.i4.0
IL_0010: stloc.1
IL_0011: br.s IL_0015
IL_0013: ldc.i4.2
IL_0014: stloc.1
// sequence point: when b2
IL_0015: ldarg.2
IL_0016: brtrue.s IL_001f
// sequence point: <hidden>
IL_0018: ldloc.1
IL_0019: brfalse.s IL_0027
IL_001b: ldloc.1
IL_001c: ldc.i4.2
IL_001d: beq.s IL_002f
// sequence point: text = ""b2"";
IL_001f: ldstr ""b2""
IL_0024: stloc.0
// sequence point: break;
IL_0025: br.s IL_0035
// sequence point: text = ""1"";
IL_0027: ldstr ""1""
IL_002c: stloc.0
// sequence point: break;
IL_002d: br.s IL_0035
// sequence point: text = ""default"";
IL_002f: ldstr ""default""
IL_0034: stloc.0
// sequence point: System.Console.WriteLine((i, b1, b2, text));
IL_0035: ldarg.0
IL_0036: ldarg.1
IL_0037: ldarg.2
IL_0038: ldloc.0
IL_0039: newobj ""System.ValueTuple<int, bool, bool, string>..ctor(int, bool, bool, string)""
IL_003e: box ""System.ValueTuple<int, bool, bool, string>""
IL_0043: call ""void System.Console.WriteLine(object)""
// sequence point: }
IL_0048: ret
}
", source: source, sequencePoints: "C.M");
}
[Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")]
public void SharedWhenExpression_MissingInt32Type()
{
var source = @"
class C
{
static void M(string s, bool b1, bool b2)
{
switch (s)
{
case not ""one"" when b1:
break;
case var _ when b2:
break;
case ""one"":
break;
default:
break;
}
}
}
";
var comp = CreateCompilation(source);
comp.MakeTypeMissing(SpecialType.System_Int32);
comp.VerifyEmitDiagnostics(
// (6,9): error CS0518: Predefined type 'System.Int32' is not defined or imported
// switch (s)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"switch (s)
{
case not ""one"" when b1:
break;
case var _ when b2:
break;
case ""one"":
break;
default:
break;
}").WithArguments("System.Int32").WithLocation(6, 9),
// (6,9): error CS0518: Predefined type 'System.Int32' is not defined or imported
// switch (s)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"switch (s)
{
case not ""one"" when b1:
break;
case var _ when b2:
break;
case ""one"":
break;
default:
break;
}").WithArguments("System.Int32").WithLocation(6, 9),
// (8,13): error CS0518: Predefined type 'System.Int32' is not defined or imported
// case not "one" when b1:
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"case not ""one"" when b1:").WithArguments("System.Int32").WithLocation(8, 13)
);
}
[Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")]
public void SharedWhenExpression_WithBindings()
{
var source = @"
C.M(""Alice"", false, true);
C.M(""Bob"", false, true);
public class C
{
public static void M(string s, bool b1, bool b2)
{
switch (s)
{
case not ""x"" when b1:
throw null;
case { Length: var j and > 2 } when b2:
System.Console.WriteLine((s, b1, b2, j.ToString()));
break;
case ""x"":
throw null;
default:
throw null;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"
(Alice, False, True, 5)
(Bob, False, True, 3)
");
verifier.VerifyIL("C.M", @"
{
// Code size 95 (0x5f)
.maxstack 4
.locals init (int V_0,
int V_1, //j
string V_2)
// sequence point: switch (s)
IL_0000: ldarg.0
IL_0001: stloc.2
// sequence point: <hidden>
IL_0002: ldloc.2
IL_0003: ldstr ""x""
IL_0008: call ""bool string.op_Equality(string, string)""
IL_000d: brfalse.s IL_002c
IL_000f: ldloc.2
IL_0010: callvirt ""int string.Length.get""
IL_0015: stloc.1
// sequence point: <hidden>
IL_0016: ldloc.1
IL_0017: ldc.i4.2
IL_0018: bgt.s IL_0031
IL_001a: br.s IL_005b
IL_001c: ldloc.2
IL_001d: brfalse.s IL_005d
IL_001f: ldloc.2
IL_0020: callvirt ""int string.Length.get""
IL_0025: stloc.1
// sequence point: <hidden>
IL_0026: ldloc.1
IL_0027: ldc.i4.2
IL_0028: bgt.s IL_0035
IL_002a: br.s IL_005d
// sequence point: when b1
IL_002c: ldarg.1
IL_002d: brfalse.s IL_001c
// sequence point: throw null;
IL_002f: ldnull
IL_0030: throw
// sequence point: <hidden>
IL_0031: ldc.i4.0
IL_0032: stloc.0
IL_0033: br.s IL_0037
IL_0035: ldc.i4.2
IL_0036: stloc.0
// sequence point: when b2
IL_0037: ldarg.2
IL_0038: brtrue.s IL_0041
// sequence point: <hidden>
IL_003a: ldloc.0
IL_003b: brfalse.s IL_005b
IL_003d: ldloc.0
IL_003e: ldc.i4.2
IL_003f: beq.s IL_005d
// sequence point: System.Console.WriteLine((s, b1, b2, j.ToString()));
IL_0041: ldarg.0
IL_0042: ldarg.1
IL_0043: ldarg.2
IL_0044: ldloca.s V_1
IL_0046: call ""string int.ToString()""
IL_004b: newobj ""System.ValueTuple<string, bool, bool, string>..ctor(string, bool, bool, string)""
IL_0050: box ""System.ValueTuple<string, bool, bool, string>""
IL_0055: call ""void System.Console.WriteLine(object)""
// sequence point: break;
IL_005a: ret
// sequence point: throw null;
IL_005b: ldnull
IL_005c: throw
// sequence point: throw null;
IL_005d: ldnull
IL_005e: throw
}
", source: source, sequencePoints: "C.M");
}
[Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")]
public void SharedWhenExpression_Multiples()
{
// The `b3` condition ends up in the `when` clause on four leaves in the DAG
// and `b1` ends up in two leaves
var source = @"
int count = 0;
foreach (int i1 in new[] { 0, 1 })
foreach (int i2 in new[] { 0, 1 })
foreach (int i3 in new[] { 0, 1 })
foreach (bool b0 in new[] { false, true })
foreach (bool b1 in new[] { false, true })
foreach (bool b2 in new[] { false, true })
foreach (bool b3 in new[] { false, true })
{
count++;
if (M(i1, i2, i3, b0, b1, b2, b3) != M2(i1, i2, i3, b0, b1, b2, b3))
throw null;
}
System.Console.Write(count);
static string M(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3)
{
object o = null;
switch (i1, i2, i3)
{
case (var x, var y, var z) when f(x, y, z):
throw null;
case (not 0, 0, _) when b0:
return ""b0"";
case (_, not 0, 0) when b1:
return ""b1"";
case (0, _, not 0) when b2:
return ""b2"";
case (_, _, _) when b3:
return ""b3"";
case (0, _, _):
return ""first"";
case (_, 0, _):
return ""second"";
case (_, _, 0):
return ""third"";
}
return ""last"";
}
static string M2(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3)
{
if (i1 is not 0 && i2 is 0 && b0)
return ""b0"";
if (i2 is not 0 && i3 is 0 && b1)
return ""b1"";
if (i3 is not 0 && i1 is 0 && b2)
return ""b2"";
if (b3)
return ""b3"";
if (i1 is 0)
return ""first"";
if (i2 is 0)
return ""second"";
if (i3 is 0)
return ""third"";
return ""last"";
}
static bool f(int i1, int i2, int i3) => false;
";
CompileAndVerify(source, expectedOutput: "128");
}
[Fact, WorkItem(55668, "https://github.com/dotnet/roslyn/issues/55668")]
public void SharedWhenExpression_Multiples_LabelInSharedWhenExpression()
{
var source = @"
int count = 0;
var wrap = new Wrap { value = null };
foreach (int i1 in new[] { 0, 1 })
foreach (int i2 in new[] { 0, 1 })
foreach (int i3 in new[] { 0, 1 })
foreach (bool b0 in new[] { false, true })
foreach (bool b1 in new[] { false, true })
foreach (bool b2 in new[] { false, true })
foreach (bool b3 in new[] { false, true })
{
count++;
if (M(i1, i2, i3, b0, b1, b2, b3) != M2(i1, i2, i3, b0, b1, b2, b3))
throw null;
}
System.Console.Write(count);
string M(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3)
{
switch (i1, i2, i3)
{
case (var x, var y, var z) when f(x, y, z):
throw null;
case (not 0, 0, _) when b0 && wrap is { value: string or string[] }:
throw null;
case (_, not 0, 0) when b1 && wrap is { value: string or string[] }:
throw null;
case (0, _, not 0) when b2 && wrap is { value: string or string[] }:
throw null;
case (_, _, _) when b3:
return ""b3"";
case (0, _, _):
return ""first"";
case (_, 0, _):
return ""second"";
case (_, _, 0):
return ""third"";
}
return ""last"";
}
static string M2(int i1, int i2, int i3, bool b0, bool b1, bool b2, bool b3)
{
if (b3)
return ""b3"";
if (i1 is 0)
return ""first"";
if (i2 is 0)
return ""second"";
if (i3 is 0)
return ""third"";
return ""last"";
}
static bool f(int i1, int i2, int i3) => false;
public class Wrap
{
public object value;
}
";
CompileAndVerify(source, expectedOutput: "128");
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/TreeDumper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// These classes are for debug and testing purposes only. It is frequently handy to be
// able to create a string representation of a complex tree-based data type. The idea
// here is to first transform your tree into a standard "tree dumper node" tree, where
// each node in the tree has a name, some optional data, and a sequence of child nodes.
// Once in a standard format the tree can then be rendered in a variety of ways
// depending on what is most useful to you.
//
// I've started with two string formats. First, a "compact" format in which there is
// exactly one line per node of the tree:
//
// root
// ├─a1
// │ └─a1b1
// ├─a2
// │ ├─a2b1
// │ │ └─a2b1c1
// │ └─a2b2
// │ ├─a2b2c1
// │ │ └─a2b2c1d1
// │ └─a2b2c2
// └─a3
// └─a3b1
//
// And second, an XML format:
//
// <root>
// <children>
// <child>
// value1
// </child>
// <child>
// value2
// </child>
// </children>
// </root>
//
// The XML format is much more verbose, but handy if you want to then pipe it into an XML tree viewer.
/// <summary>
/// This is ONLY used id BoundNode.cs Debug method - Dump()
/// </summary>
internal class TreeDumper
{
private readonly StringBuilder _sb;
protected TreeDumper()
{
_sb = new StringBuilder();
}
public static string DumpCompact(TreeDumperNode root)
{
return new TreeDumper().DoDumpCompact(root);
}
protected string DoDumpCompact(TreeDumperNode root)
{
DoDumpCompact(root, string.Empty);
return _sb.ToString();
}
private void DoDumpCompact(TreeDumperNode node, string indent)
{
RoslynDebug.Assert(node != null);
RoslynDebug.Assert(indent != null);
// Precondition: indentation and prefix has already been output
// Precondition: indent is correct for node's *children*
_sb.Append(node.Text);
if (node.Value != null)
{
_sb.AppendFormat(": {0}", DumperString(node.Value));
}
_sb.AppendLine();
var children = node.Children.ToList();
for (int i = 0; i < children.Count; ++i)
{
var child = children[i];
if (child == null)
{
continue;
}
_sb.Append(indent);
_sb.Append(i == children.Count - 1 ? '\u2514' : '\u251C');
_sb.Append('\u2500');
// First precondition met; now work out the string needed to indent
// the child node's children:
DoDumpCompact(child, indent + (i == children.Count - 1 ? " " : "\u2502 "));
}
}
public static string DumpXML(TreeDumperNode root, string? indent = null)
{
var dumper = new TreeDumper();
dumper.DoDumpXML(root, string.Empty, indent ?? string.Empty);
return dumper._sb.ToString();
}
private void DoDumpXML(TreeDumperNode node, string indent, string relativeIndent)
{
RoslynDebug.Assert(node != null);
if (node.Children.All(child => child == null))
{
_sb.Append(indent);
if (node.Value != null)
{
_sb.AppendFormat("<{0}>{1}</{0}>", node.Text, DumperString(node.Value));
}
else
{
_sb.AppendFormat("<{0} />", node.Text);
}
_sb.AppendLine();
}
else
{
_sb.Append(indent);
_sb.AppendFormat("<{0}>", node.Text);
_sb.AppendLine();
if (node.Value != null)
{
_sb.Append(indent);
_sb.AppendFormat("{0}", DumperString(node.Value));
_sb.AppendLine();
}
var childIndent = indent + relativeIndent;
foreach (var child in node.Children)
{
if (child == null)
{
continue;
}
DoDumpXML(child, childIndent, relativeIndent);
}
_sb.Append(indent);
_sb.AppendFormat("</{0}>", node.Text);
_sb.AppendLine();
}
}
// an (awful) test for a null read-only-array. Is there no better way to do this?
private static bool IsDefaultImmutableArray(Object o)
{
var ti = o.GetType().GetTypeInfo();
if (ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(ImmutableArray<>))
{
var result = ti?.GetDeclaredMethod("get_IsDefault")?.Invoke(o, Array.Empty<object>());
return result is bool b && b;
}
return false;
}
protected virtual string DumperString(object o)
{
if (o == null)
{
return "(null)";
}
var str = o as string;
if (str != null)
{
return str;
}
if (IsDefaultImmutableArray(o))
{
return "(null)";
}
var seq = o as IEnumerable;
if (seq != null)
{
return string.Format("{{{0}}}", string.Join(", ", seq.Cast<object>().Select(DumperString).ToArray()));
}
var symbol = o as ISymbol;
if (symbol != null)
{
return symbol.ToDisplayString(SymbolDisplayFormat.TestFormat);
}
return o.ToString() ?? "";
}
}
/// <summary>
/// This is ONLY used for debugging purpose
/// </summary>
internal sealed class TreeDumperNode
{
public TreeDumperNode(string text, object? value, IEnumerable<TreeDumperNode>? children)
{
this.Text = text;
this.Value = value;
this.Children = children ?? SpecializedCollections.EmptyEnumerable<TreeDumperNode>();
}
public TreeDumperNode(string text) : this(text, null, null) { }
public object? Value { get; }
public string Text { get; }
public IEnumerable<TreeDumperNode> Children { get; }
public TreeDumperNode? this[string child]
{
get
{
return Children.FirstOrDefault(c => c.Text == child);
}
}
// enumerates all edges of the tree yielding (parent, node) pairs. The first yielded value is (null, this).
public IEnumerable<KeyValuePair<TreeDumperNode?, TreeDumperNode>> PreorderTraversal()
{
var stack = new Stack<KeyValuePair<TreeDumperNode?, TreeDumperNode>>();
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(null, this));
while (stack.Count != 0)
{
var currentEdge = stack.Pop();
yield return currentEdge;
var currentNode = currentEdge.Value;
foreach (var child in currentNode.Children.Where(x => x != null).Reverse())
{
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(currentNode, child));
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// These classes are for debug and testing purposes only. It is frequently handy to be
// able to create a string representation of a complex tree-based data type. The idea
// here is to first transform your tree into a standard "tree dumper node" tree, where
// each node in the tree has a name, some optional data, and a sequence of child nodes.
// Once in a standard format the tree can then be rendered in a variety of ways
// depending on what is most useful to you.
//
// I've started with two string formats. First, a "compact" format in which there is
// exactly one line per node of the tree:
//
// root
// ├─a1
// │ └─a1b1
// ├─a2
// │ ├─a2b1
// │ │ └─a2b1c1
// │ └─a2b2
// │ ├─a2b2c1
// │ │ └─a2b2c1d1
// │ └─a2b2c2
// └─a3
// └─a3b1
//
// And second, an XML format:
//
// <root>
// <children>
// <child>
// value1
// </child>
// <child>
// value2
// </child>
// </children>
// </root>
//
// The XML format is much more verbose, but handy if you want to then pipe it into an XML tree viewer.
/// <summary>
/// This is ONLY used id BoundNode.cs Debug method - Dump()
/// </summary>
internal class TreeDumper
{
private readonly StringBuilder _sb;
protected TreeDumper()
{
_sb = new StringBuilder();
}
public static string DumpCompact(TreeDumperNode root)
{
return new TreeDumper().DoDumpCompact(root);
}
protected string DoDumpCompact(TreeDumperNode root)
{
DoDumpCompact(root, string.Empty);
return _sb.ToString();
}
private void DoDumpCompact(TreeDumperNode node, string indent)
{
RoslynDebug.Assert(node != null);
RoslynDebug.Assert(indent != null);
// Precondition: indentation and prefix has already been output
// Precondition: indent is correct for node's *children*
_sb.Append(node.Text);
if (node.Value != null)
{
_sb.AppendFormat(": {0}", DumperString(node.Value));
}
_sb.AppendLine();
var children = node.Children.Where(c => !skip(c)).ToList();
for (int i = 0; i < children.Count; ++i)
{
var child = children[i];
_sb.Append(indent);
_sb.Append(i == children.Count - 1 ? '\u2514' : '\u251C');
_sb.Append('\u2500');
// First precondition met; now work out the string needed to indent
// the child node's children:
DoDumpCompact(child, indent + (i == children.Count - 1 ? " " : "\u2502 "));
}
static bool skip(TreeDumperNode node)
{
if (node is null)
{
return true;
}
if (node.Text is "locals" or "localFunctions"
&& node.Value is IList { Count: 0 })
{
return true;
}
if (node.Text is "hasErrors" or "isSuppressed" or "isRef"
&& node.Value is false)
{
return true;
}
return false;
}
}
public static string DumpXML(TreeDumperNode root, string? indent = null)
{
var dumper = new TreeDumper();
dumper.DoDumpXML(root, string.Empty, indent ?? string.Empty);
return dumper._sb.ToString();
}
private void DoDumpXML(TreeDumperNode node, string indent, string relativeIndent)
{
RoslynDebug.Assert(node != null);
if (node.Children.All(child => child == null))
{
_sb.Append(indent);
if (node.Value != null)
{
_sb.AppendFormat("<{0}>{1}</{0}>", node.Text, DumperString(node.Value));
}
else
{
_sb.AppendFormat("<{0} />", node.Text);
}
_sb.AppendLine();
}
else
{
_sb.Append(indent);
_sb.AppendFormat("<{0}>", node.Text);
_sb.AppendLine();
if (node.Value != null)
{
_sb.Append(indent);
_sb.AppendFormat("{0}", DumperString(node.Value));
_sb.AppendLine();
}
var childIndent = indent + relativeIndent;
foreach (var child in node.Children)
{
if (child == null)
{
continue;
}
DoDumpXML(child, childIndent, relativeIndent);
}
_sb.Append(indent);
_sb.AppendFormat("</{0}>", node.Text);
_sb.AppendLine();
}
}
// an (awful) test for a null read-only-array. Is there no better way to do this?
private static bool IsDefaultImmutableArray(Object o)
{
var ti = o.GetType().GetTypeInfo();
if (ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(ImmutableArray<>))
{
var result = ti?.GetDeclaredMethod("get_IsDefault")?.Invoke(o, Array.Empty<object>());
return result is bool b && b;
}
return false;
}
protected virtual string DumperString(object o)
{
if (o == null)
{
return "(null)";
}
var str = o as string;
if (str != null)
{
return str;
}
if (IsDefaultImmutableArray(o))
{
return "(null)";
}
var seq = o as IEnumerable;
if (seq != null)
{
return string.Format("{{{0}}}", string.Join(", ", seq.Cast<object>().Select(DumperString).ToArray()));
}
var symbol = o as ISymbol;
if (symbol != null)
{
return symbol.ToDisplayString(SymbolDisplayFormat.TestFormat);
}
return o.ToString() ?? "";
}
}
/// <summary>
/// This is ONLY used for debugging purpose
/// </summary>
internal sealed class TreeDumperNode
{
public TreeDumperNode(string text, object? value, IEnumerable<TreeDumperNode>? children)
{
this.Text = text;
this.Value = value;
this.Children = children ?? SpecializedCollections.EmptyEnumerable<TreeDumperNode>();
}
public TreeDumperNode(string text) : this(text, null, null) { }
public object? Value { get; }
public string Text { get; }
public IEnumerable<TreeDumperNode> Children { get; }
public TreeDumperNode? this[string child]
{
get
{
return Children.FirstOrDefault(c => c.Text == child);
}
}
// enumerates all edges of the tree yielding (parent, node) pairs. The first yielded value is (null, this).
public IEnumerable<KeyValuePair<TreeDumperNode?, TreeDumperNode>> PreorderTraversal()
{
var stack = new Stack<KeyValuePair<TreeDumperNode?, TreeDumperNode>>();
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(null, this));
while (stack.Count != 0)
{
var currentEdge = stack.Pop();
yield return currentEdge;
var currentNode = currentEdge.Value;
foreach (var child in currentNode.Children.Where(x => x != null).Reverse())
{
stack.Push(new KeyValuePair<TreeDumperNode?, TreeDumperNode>(currentNode, child));
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/ILogger.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
namespace Microsoft.CodeAnalysis.Internal.Log
{
/// <summary>
/// logger interface actual logger should implements
/// </summary>
internal interface ILogger
{
/// <summary>
/// answer whether it is enabled or not for the specific function id
/// </summary>
bool IsEnabled(FunctionId functionId);
/// <summary>
/// log a specific event with context message
/// </summary>
void Log(FunctionId functionId, LogMessage logMessage);
/// <summary>
/// log a start event with context message
/// </summary>
void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken);
/// <summary>
/// log an end event
/// </summary>
void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
namespace Microsoft.CodeAnalysis.Internal.Log
{
/// <summary>
/// logger interface actual logger should implements
/// </summary>
internal interface ILogger
{
/// <summary>
/// answer whether it is enabled or not for the specific function id
/// </summary>
bool IsEnabled(FunctionId functionId);
/// <summary>
/// log a specific event with context message
/// </summary>
void Log(FunctionId functionId, LogMessage logMessage);
/// <summary>
/// log a start event with context message
/// </summary>
void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken);
/// <summary>
/// log an end event
/// </summary>
void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage_Helpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using static System.FormattableString;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
internal partial class SQLitePersistentStorage
{
private static string GetProjectIdString(int projectPathId, int projectNameId)
=> Invariant($"{projectPathId}-{projectNameId}");
private static string GetDocumentIdString(int projectId, int documentPathId, int documentNameId)
=> Invariant($"{projectId}-{documentPathId}-{documentNameId}");
private static long CombineInt32ValuesToInt64(int v1, int v2)
=> ((long)v1 << 32) | (long)v2;
private static (byte[] bytes, int length, bool fromPool) GetBytes(Stream stream)
{
// Attempt to copy into a pooled byte[] if the stream length is known and it's
// less than 128k. This accounts for 99%+ of all of our streams while keeping
// a generally small pool around (<10 items) when I've debugged VS.
if (stream.CanSeek)
{
if (stream.Length >= 0 && stream.Length <= int.MaxValue)
{
var length = (int)stream.Length;
byte[] bytes;
bool fromPool;
if (length <= MaxPooledByteArrayLength)
{
// use a pooled byte[] to store our data in.
bytes = GetPooledBytes();
fromPool = true;
}
else
{
// We knew the length, but it was large. Copy the stream into that
// array, but don't pool it so we don't hold onto huge arrays forever.
bytes = new byte[length];
fromPool = false;
}
CopyTo(stream, bytes, length);
return (bytes, length, fromPool);
}
}
// Not something we could get the length of. Just copy the bytes out of the stream entirely.
using (var tempStream = new MemoryStream())
{
stream.CopyTo(tempStream);
var bytes = tempStream.ToArray();
return (bytes, bytes.Length, fromPool: false);
}
}
private static void CopyTo(Stream stream, byte[] bytes, int length)
{
var index = 0;
int read;
while (length > 0 && (read = stream.Read(bytes, index, length)) != 0)
{
index += read;
length -= read;
}
}
/// <summary>
/// Amount of time to wait between flushing writes to disk. 500ms means we can flush
/// writes to disk two times a second.
/// </summary>
private const int FlushAllDelayMS = 500;
/// <summary>
/// We use a pool to cache reads/writes that are less than 4k. Testing with Roslyn,
/// 99% of all writes (48.5k out of 49.5k) are less than that size. So this helps
/// ensure that we can pool as much as possible, without caching excessively large
/// arrays (for example, Roslyn does write out nearly 50 chunks that are larger than
/// 100k each).
/// </summary>
internal const long MaxPooledByteArrayLength = 4 * 1024;
/// <summary>
/// The max amount of byte[]s we cache. This caps our cache at 4MB while allowing
/// us to massively speed up writing (by batching writes). Because we can write to
/// disk two times a second. That means a total of 8MB/s that can be written to disk
/// using only our cache. Given that Roslyn itself only writes about 50MB to disk
/// after several minutes of analysis, this amount of bandwidth is more than sufficient.
/// </summary>
private const int MaxPooledByteArrays = 1024;
private static readonly Stack<byte[]> s_byteArrayPool = new();
internal static byte[] GetPooledBytes()
{
byte[] bytes;
lock (s_byteArrayPool)
{
if (s_byteArrayPool.Count > 0)
{
bytes = s_byteArrayPool.Pop();
}
else
{
bytes = new byte[MaxPooledByteArrayLength];
}
}
Array.Clear(bytes, 0, bytes.Length);
return bytes;
}
internal static void ReturnPooledBytes(byte[] bytes)
{
lock (s_byteArrayPool)
{
if (s_byteArrayPool.Count < MaxPooledByteArrays)
{
s_byteArrayPool.Push(bytes);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using static System.FormattableString;
namespace Microsoft.CodeAnalysis.SQLite.v2
{
internal partial class SQLitePersistentStorage
{
private static string GetProjectIdString(int projectPathId, int projectNameId)
=> Invariant($"{projectPathId}-{projectNameId}");
private static string GetDocumentIdString(int projectId, int documentPathId, int documentNameId)
=> Invariant($"{projectId}-{documentPathId}-{documentNameId}");
private static long CombineInt32ValuesToInt64(int v1, int v2)
=> ((long)v1 << 32) | (long)v2;
private static (byte[] bytes, int length, bool fromPool) GetBytes(Stream stream)
{
// Attempt to copy into a pooled byte[] if the stream length is known and it's
// less than 128k. This accounts for 99%+ of all of our streams while keeping
// a generally small pool around (<10 items) when I've debugged VS.
if (stream.CanSeek)
{
if (stream.Length >= 0 && stream.Length <= int.MaxValue)
{
var length = (int)stream.Length;
byte[] bytes;
bool fromPool;
if (length <= MaxPooledByteArrayLength)
{
// use a pooled byte[] to store our data in.
bytes = GetPooledBytes();
fromPool = true;
}
else
{
// We knew the length, but it was large. Copy the stream into that
// array, but don't pool it so we don't hold onto huge arrays forever.
bytes = new byte[length];
fromPool = false;
}
CopyTo(stream, bytes, length);
return (bytes, length, fromPool);
}
}
// Not something we could get the length of. Just copy the bytes out of the stream entirely.
using (var tempStream = new MemoryStream())
{
stream.CopyTo(tempStream);
var bytes = tempStream.ToArray();
return (bytes, bytes.Length, fromPool: false);
}
}
private static void CopyTo(Stream stream, byte[] bytes, int length)
{
var index = 0;
int read;
while (length > 0 && (read = stream.Read(bytes, index, length)) != 0)
{
index += read;
length -= read;
}
}
/// <summary>
/// Amount of time to wait between flushing writes to disk. 500ms means we can flush
/// writes to disk two times a second.
/// </summary>
private const int FlushAllDelayMS = 500;
/// <summary>
/// We use a pool to cache reads/writes that are less than 4k. Testing with Roslyn,
/// 99% of all writes (48.5k out of 49.5k) are less than that size. So this helps
/// ensure that we can pool as much as possible, without caching excessively large
/// arrays (for example, Roslyn does write out nearly 50 chunks that are larger than
/// 100k each).
/// </summary>
internal const long MaxPooledByteArrayLength = 4 * 1024;
/// <summary>
/// The max amount of byte[]s we cache. This caps our cache at 4MB while allowing
/// us to massively speed up writing (by batching writes). Because we can write to
/// disk two times a second. That means a total of 8MB/s that can be written to disk
/// using only our cache. Given that Roslyn itself only writes about 50MB to disk
/// after several minutes of analysis, this amount of bandwidth is more than sufficient.
/// </summary>
private const int MaxPooledByteArrays = 1024;
private static readonly Stack<byte[]> s_byteArrayPool = new();
internal static byte[] GetPooledBytes()
{
byte[] bytes;
lock (s_byteArrayPool)
{
if (s_byteArrayPool.Count > 0)
{
bytes = s_byteArrayPool.Pop();
}
else
{
bytes = new byte[MaxPooledByteArrayLength];
}
}
Array.Clear(bytes, 0, bytes.Length);
return bytes;
}
internal static void ReturnPooledBytes(byte[] bytes)
{
lock (s_byteArrayPool)
{
if (s_byteArrayPool.Count < MaxPooledByteArrays)
{
s_byteArrayPool.Push(bytes);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.PragmaHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal partial class AbstractSuppressionCodeFixProvider
{
/// <summary>
/// Helper methods for pragma based suppression code actions.
/// </summary>
private static class PragmaHelpers
{
internal static async Task<Document> GetChangeDocumentWithPragmaAdjustedAsync(
Document document,
TextSpan diagnosticSpan,
SuppressionTargetInfo suppressionTargetInfo,
Func<SyntaxToken, TextSpan, SyntaxToken> getNewStartToken,
Func<SyntaxToken, TextSpan, SyntaxToken> getNewEndToken,
CancellationToken cancellationToken)
{
var startToken = suppressionTargetInfo.StartToken;
var endToken = suppressionTargetInfo.EndToken;
var nodeWithTokens = suppressionTargetInfo.NodeWithTokens;
var root = await nodeWithTokens.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var startAndEndTokenAreTheSame = startToken == endToken;
var newStartToken = getNewStartToken(startToken, diagnosticSpan);
var newEndToken = endToken;
if (startAndEndTokenAreTheSame)
{
var annotation = new SyntaxAnnotation();
newEndToken = root.ReplaceToken(startToken, newStartToken.WithAdditionalAnnotations(annotation)).GetAnnotatedTokens(annotation).Single();
var spanChange = newStartToken.LeadingTrivia.FullSpan.Length - startToken.LeadingTrivia.FullSpan.Length;
diagnosticSpan = new TextSpan(diagnosticSpan.Start + spanChange, diagnosticSpan.Length);
}
newEndToken = getNewEndToken(newEndToken, diagnosticSpan);
SyntaxNode newNode;
if (startAndEndTokenAreTheSame)
{
newNode = nodeWithTokens.ReplaceToken(startToken, newEndToken);
}
else
{
newNode = nodeWithTokens.ReplaceTokens(new[] { startToken, endToken }, (o, n) => o == startToken ? newStartToken : newEndToken);
}
var newRoot = root.ReplaceNode(nodeWithTokens, newNode);
return document.WithSyntaxRoot(newRoot);
}
private static int GetPositionForPragmaInsertion(ImmutableArray<SyntaxTrivia> triviaList, TextSpan currentDiagnosticSpan, AbstractSuppressionCodeFixProvider fixer, bool isStartToken, out SyntaxTrivia triviaAtIndex)
{
// Start token: Insert the #pragma disable directive just **before** the first end of line trivia prior to diagnostic location.
// End token: Insert the #pragma disable directive just **after** the first end of line trivia after diagnostic location.
int getNextIndex(int cur) => isStartToken ? cur - 1 : cur + 1;
bool shouldConsiderTrivia(SyntaxTrivia trivia) =>
isStartToken ?
trivia.FullSpan.End <= currentDiagnosticSpan.Start :
trivia.FullSpan.Start >= currentDiagnosticSpan.End;
var walkedPastDiagnosticSpan = false;
var seenEndOfLineTrivia = false;
var index = isStartToken ? triviaList.Length - 1 : 0;
while (index >= 0 && index < triviaList.Length)
{
var trivia = triviaList[index];
walkedPastDiagnosticSpan = walkedPastDiagnosticSpan || shouldConsiderTrivia(trivia);
seenEndOfLineTrivia = seenEndOfLineTrivia ||
IsEndOfLineOrContainsEndOfLine(trivia, fixer);
if (walkedPastDiagnosticSpan && seenEndOfLineTrivia)
{
break;
}
index = getNextIndex(index);
}
triviaAtIndex = index >= 0 && index < triviaList.Length ?
triviaList[index] :
default;
return index;
}
internal static SyntaxToken GetNewStartTokenWithAddedPragma(
SyntaxToken startToken,
TextSpan currentDiagnosticSpan,
Diagnostic diagnostic,
AbstractSuppressionCodeFixProvider fixer,
Func<SyntaxNode, SyntaxNode> formatNode,
bool isRemoveSuppression = false)
{
var trivia = startToken.LeadingTrivia.ToImmutableArray();
var index = GetPositionForPragmaInsertion(trivia, currentDiagnosticSpan, fixer, isStartToken: true, triviaAtIndex: out var insertAfterTrivia);
index++;
bool needsLeadingEOL;
if (index > 0)
{
needsLeadingEOL = !IsEndOfLineOrHasTrailingEndOfLine(insertAfterTrivia, fixer);
}
else if (startToken.FullSpan.Start == 0)
{
needsLeadingEOL = false;
}
else
{
needsLeadingEOL = true;
}
var pragmaTrivia = !isRemoveSuppression
? fixer.CreatePragmaDisableDirectiveTrivia(diagnostic, formatNode, needsLeadingEOL, needsTrailingEndOfLine: true)
: fixer.CreatePragmaRestoreDirectiveTrivia(diagnostic, formatNode, needsLeadingEOL, needsTrailingEndOfLine: true);
return startToken.WithLeadingTrivia(trivia.InsertRange(index, pragmaTrivia));
}
private static bool IsEndOfLineOrHasLeadingEndOfLine(SyntaxTrivia trivia, AbstractSuppressionCodeFixProvider fixer)
{
return fixer.IsEndOfLine(trivia) ||
(trivia.HasStructure && fixer.IsEndOfLine(trivia.GetStructure().DescendantTrivia().FirstOrDefault()));
}
private static bool IsEndOfLineOrHasTrailingEndOfLine(SyntaxTrivia trivia, AbstractSuppressionCodeFixProvider fixer)
{
return fixer.IsEndOfLine(trivia) ||
(trivia.HasStructure && fixer.IsEndOfLine(trivia.GetStructure().DescendantTrivia().LastOrDefault()));
}
private static bool IsEndOfLineOrContainsEndOfLine(SyntaxTrivia trivia, AbstractSuppressionCodeFixProvider fixer)
{
return fixer.IsEndOfLine(trivia) ||
(trivia.HasStructure && trivia.GetStructure().DescendantTrivia().Any(t => fixer.IsEndOfLine(t)));
}
internal static SyntaxToken GetNewEndTokenWithAddedPragma(
SyntaxToken endToken,
TextSpan currentDiagnosticSpan,
Diagnostic diagnostic,
AbstractSuppressionCodeFixProvider fixer,
Func<SyntaxNode, SyntaxNode> formatNode,
bool isRemoveSuppression = false)
{
ImmutableArray<SyntaxTrivia> trivia;
var isEOF = fixer.IsEndOfFileToken(endToken);
if (isEOF)
{
trivia = endToken.LeadingTrivia.ToImmutableArray();
}
else
{
trivia = endToken.TrailingTrivia.ToImmutableArray();
}
var index = GetPositionForPragmaInsertion(trivia, currentDiagnosticSpan, fixer, isStartToken: false, triviaAtIndex: out var insertBeforeTrivia);
bool needsTrailingEOL;
if (index < trivia.Length)
{
needsTrailingEOL = !IsEndOfLineOrHasLeadingEndOfLine(insertBeforeTrivia, fixer);
}
else if (isEOF)
{
needsTrailingEOL = false;
}
else
{
needsTrailingEOL = true;
}
var pragmaTrivia = !isRemoveSuppression
? fixer.CreatePragmaRestoreDirectiveTrivia(diagnostic, formatNode, needsLeadingEndOfLine: true, needsTrailingEndOfLine: needsTrailingEOL)
: fixer.CreatePragmaDisableDirectiveTrivia(diagnostic, formatNode, needsLeadingEndOfLine: true, needsTrailingEndOfLine: needsTrailingEOL);
if (isEOF)
{
return endToken.WithLeadingTrivia(trivia.InsertRange(index, pragmaTrivia));
}
else
{
return endToken.WithTrailingTrivia(trivia.InsertRange(index, pragmaTrivia));
}
}
internal static void NormalizeTriviaOnTokens(AbstractSuppressionCodeFixProvider fixer, ref Document document, ref SuppressionTargetInfo suppressionTargetInfo)
{
// For pragma suppression fixes, we need to normalize the leading trivia on start token to account for
// the trailing trivia on its previous token (and similarly normalize trailing trivia for end token).
var startToken = suppressionTargetInfo.StartToken;
var endToken = suppressionTargetInfo.EndToken;
var nodeWithTokens = suppressionTargetInfo.NodeWithTokens;
var startAndEndTokensAreSame = startToken == endToken;
var isEndTokenEOF = fixer.IsEndOfFileToken(endToken);
var previousOfStart = startToken.GetPreviousToken(includeZeroWidth: true);
var nextOfEnd = !isEndTokenEOF ? endToken.GetNextToken(includeZeroWidth: true) : default;
if (!previousOfStart.HasTrailingTrivia && !nextOfEnd.HasLeadingTrivia)
{
return;
}
var root = nodeWithTokens.SyntaxTree.GetRoot();
var spanEnd = !isEndTokenEOF ? nextOfEnd.FullSpan.End : endToken.FullSpan.End;
var subtreeRoot = root.FindNode(new TextSpan(previousOfStart.FullSpan.Start, spanEnd - previousOfStart.FullSpan.Start));
var currentStartToken = startToken;
var currentEndToken = endToken;
var newStartToken = startToken.WithLeadingTrivia(previousOfStart.TrailingTrivia.Concat(startToken.LeadingTrivia));
var newEndToken = currentEndToken;
if (startAndEndTokensAreSame)
{
newEndToken = newStartToken;
}
newEndToken = newEndToken.WithTrailingTrivia(endToken.TrailingTrivia.Concat(nextOfEnd.LeadingTrivia));
var newPreviousOfStart = previousOfStart.WithTrailingTrivia();
var newNextOfEnd = nextOfEnd.WithLeadingTrivia();
var newSubtreeRoot = subtreeRoot.ReplaceTokens(new[] { startToken, previousOfStart, endToken, nextOfEnd },
(o, n) =>
{
if (o == currentStartToken)
{
return startAndEndTokensAreSame ? newEndToken : newStartToken;
}
else if (o == previousOfStart)
{
return newPreviousOfStart;
}
else if (o == currentEndToken)
{
return newEndToken;
}
else if (o == nextOfEnd)
{
return newNextOfEnd;
}
else
{
return n;
}
});
root = root.ReplaceNode(subtreeRoot, newSubtreeRoot);
document = document.WithSyntaxRoot(root);
suppressionTargetInfo.StartToken = root.FindToken(startToken.SpanStart);
suppressionTargetInfo.EndToken = root.FindToken(endToken.SpanStart);
suppressionTargetInfo.NodeWithTokens = fixer.GetNodeWithTokens(suppressionTargetInfo.StartToken, suppressionTargetInfo.EndToken, root);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal partial class AbstractSuppressionCodeFixProvider
{
/// <summary>
/// Helper methods for pragma based suppression code actions.
/// </summary>
private static class PragmaHelpers
{
internal static async Task<Document> GetChangeDocumentWithPragmaAdjustedAsync(
Document document,
TextSpan diagnosticSpan,
SuppressionTargetInfo suppressionTargetInfo,
Func<SyntaxToken, TextSpan, SyntaxToken> getNewStartToken,
Func<SyntaxToken, TextSpan, SyntaxToken> getNewEndToken,
CancellationToken cancellationToken)
{
var startToken = suppressionTargetInfo.StartToken;
var endToken = suppressionTargetInfo.EndToken;
var nodeWithTokens = suppressionTargetInfo.NodeWithTokens;
var root = await nodeWithTokens.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var startAndEndTokenAreTheSame = startToken == endToken;
var newStartToken = getNewStartToken(startToken, diagnosticSpan);
var newEndToken = endToken;
if (startAndEndTokenAreTheSame)
{
var annotation = new SyntaxAnnotation();
newEndToken = root.ReplaceToken(startToken, newStartToken.WithAdditionalAnnotations(annotation)).GetAnnotatedTokens(annotation).Single();
var spanChange = newStartToken.LeadingTrivia.FullSpan.Length - startToken.LeadingTrivia.FullSpan.Length;
diagnosticSpan = new TextSpan(diagnosticSpan.Start + spanChange, diagnosticSpan.Length);
}
newEndToken = getNewEndToken(newEndToken, diagnosticSpan);
SyntaxNode newNode;
if (startAndEndTokenAreTheSame)
{
newNode = nodeWithTokens.ReplaceToken(startToken, newEndToken);
}
else
{
newNode = nodeWithTokens.ReplaceTokens(new[] { startToken, endToken }, (o, n) => o == startToken ? newStartToken : newEndToken);
}
var newRoot = root.ReplaceNode(nodeWithTokens, newNode);
return document.WithSyntaxRoot(newRoot);
}
private static int GetPositionForPragmaInsertion(ImmutableArray<SyntaxTrivia> triviaList, TextSpan currentDiagnosticSpan, AbstractSuppressionCodeFixProvider fixer, bool isStartToken, out SyntaxTrivia triviaAtIndex)
{
// Start token: Insert the #pragma disable directive just **before** the first end of line trivia prior to diagnostic location.
// End token: Insert the #pragma disable directive just **after** the first end of line trivia after diagnostic location.
int getNextIndex(int cur) => isStartToken ? cur - 1 : cur + 1;
bool shouldConsiderTrivia(SyntaxTrivia trivia) =>
isStartToken ?
trivia.FullSpan.End <= currentDiagnosticSpan.Start :
trivia.FullSpan.Start >= currentDiagnosticSpan.End;
var walkedPastDiagnosticSpan = false;
var seenEndOfLineTrivia = false;
var index = isStartToken ? triviaList.Length - 1 : 0;
while (index >= 0 && index < triviaList.Length)
{
var trivia = triviaList[index];
walkedPastDiagnosticSpan = walkedPastDiagnosticSpan || shouldConsiderTrivia(trivia);
seenEndOfLineTrivia = seenEndOfLineTrivia ||
IsEndOfLineOrContainsEndOfLine(trivia, fixer);
if (walkedPastDiagnosticSpan && seenEndOfLineTrivia)
{
break;
}
index = getNextIndex(index);
}
triviaAtIndex = index >= 0 && index < triviaList.Length ?
triviaList[index] :
default;
return index;
}
internal static SyntaxToken GetNewStartTokenWithAddedPragma(
SyntaxToken startToken,
TextSpan currentDiagnosticSpan,
Diagnostic diagnostic,
AbstractSuppressionCodeFixProvider fixer,
Func<SyntaxNode, SyntaxNode> formatNode,
bool isRemoveSuppression = false)
{
var trivia = startToken.LeadingTrivia.ToImmutableArray();
var index = GetPositionForPragmaInsertion(trivia, currentDiagnosticSpan, fixer, isStartToken: true, triviaAtIndex: out var insertAfterTrivia);
index++;
bool needsLeadingEOL;
if (index > 0)
{
needsLeadingEOL = !IsEndOfLineOrHasTrailingEndOfLine(insertAfterTrivia, fixer);
}
else if (startToken.FullSpan.Start == 0)
{
needsLeadingEOL = false;
}
else
{
needsLeadingEOL = true;
}
var pragmaTrivia = !isRemoveSuppression
? fixer.CreatePragmaDisableDirectiveTrivia(diagnostic, formatNode, needsLeadingEOL, needsTrailingEndOfLine: true)
: fixer.CreatePragmaRestoreDirectiveTrivia(diagnostic, formatNode, needsLeadingEOL, needsTrailingEndOfLine: true);
return startToken.WithLeadingTrivia(trivia.InsertRange(index, pragmaTrivia));
}
private static bool IsEndOfLineOrHasLeadingEndOfLine(SyntaxTrivia trivia, AbstractSuppressionCodeFixProvider fixer)
{
return fixer.IsEndOfLine(trivia) ||
(trivia.HasStructure && fixer.IsEndOfLine(trivia.GetStructure().DescendantTrivia().FirstOrDefault()));
}
private static bool IsEndOfLineOrHasTrailingEndOfLine(SyntaxTrivia trivia, AbstractSuppressionCodeFixProvider fixer)
{
return fixer.IsEndOfLine(trivia) ||
(trivia.HasStructure && fixer.IsEndOfLine(trivia.GetStructure().DescendantTrivia().LastOrDefault()));
}
private static bool IsEndOfLineOrContainsEndOfLine(SyntaxTrivia trivia, AbstractSuppressionCodeFixProvider fixer)
{
return fixer.IsEndOfLine(trivia) ||
(trivia.HasStructure && trivia.GetStructure().DescendantTrivia().Any(t => fixer.IsEndOfLine(t)));
}
internal static SyntaxToken GetNewEndTokenWithAddedPragma(
SyntaxToken endToken,
TextSpan currentDiagnosticSpan,
Diagnostic diagnostic,
AbstractSuppressionCodeFixProvider fixer,
Func<SyntaxNode, SyntaxNode> formatNode,
bool isRemoveSuppression = false)
{
ImmutableArray<SyntaxTrivia> trivia;
var isEOF = fixer.IsEndOfFileToken(endToken);
if (isEOF)
{
trivia = endToken.LeadingTrivia.ToImmutableArray();
}
else
{
trivia = endToken.TrailingTrivia.ToImmutableArray();
}
var index = GetPositionForPragmaInsertion(trivia, currentDiagnosticSpan, fixer, isStartToken: false, triviaAtIndex: out var insertBeforeTrivia);
bool needsTrailingEOL;
if (index < trivia.Length)
{
needsTrailingEOL = !IsEndOfLineOrHasLeadingEndOfLine(insertBeforeTrivia, fixer);
}
else if (isEOF)
{
needsTrailingEOL = false;
}
else
{
needsTrailingEOL = true;
}
var pragmaTrivia = !isRemoveSuppression
? fixer.CreatePragmaRestoreDirectiveTrivia(diagnostic, formatNode, needsLeadingEndOfLine: true, needsTrailingEndOfLine: needsTrailingEOL)
: fixer.CreatePragmaDisableDirectiveTrivia(diagnostic, formatNode, needsLeadingEndOfLine: true, needsTrailingEndOfLine: needsTrailingEOL);
if (isEOF)
{
return endToken.WithLeadingTrivia(trivia.InsertRange(index, pragmaTrivia));
}
else
{
return endToken.WithTrailingTrivia(trivia.InsertRange(index, pragmaTrivia));
}
}
internal static void NormalizeTriviaOnTokens(AbstractSuppressionCodeFixProvider fixer, ref Document document, ref SuppressionTargetInfo suppressionTargetInfo)
{
// For pragma suppression fixes, we need to normalize the leading trivia on start token to account for
// the trailing trivia on its previous token (and similarly normalize trailing trivia for end token).
var startToken = suppressionTargetInfo.StartToken;
var endToken = suppressionTargetInfo.EndToken;
var nodeWithTokens = suppressionTargetInfo.NodeWithTokens;
var startAndEndTokensAreSame = startToken == endToken;
var isEndTokenEOF = fixer.IsEndOfFileToken(endToken);
var previousOfStart = startToken.GetPreviousToken(includeZeroWidth: true);
var nextOfEnd = !isEndTokenEOF ? endToken.GetNextToken(includeZeroWidth: true) : default;
if (!previousOfStart.HasTrailingTrivia && !nextOfEnd.HasLeadingTrivia)
{
return;
}
var root = nodeWithTokens.SyntaxTree.GetRoot();
var spanEnd = !isEndTokenEOF ? nextOfEnd.FullSpan.End : endToken.FullSpan.End;
var subtreeRoot = root.FindNode(new TextSpan(previousOfStart.FullSpan.Start, spanEnd - previousOfStart.FullSpan.Start));
var currentStartToken = startToken;
var currentEndToken = endToken;
var newStartToken = startToken.WithLeadingTrivia(previousOfStart.TrailingTrivia.Concat(startToken.LeadingTrivia));
var newEndToken = currentEndToken;
if (startAndEndTokensAreSame)
{
newEndToken = newStartToken;
}
newEndToken = newEndToken.WithTrailingTrivia(endToken.TrailingTrivia.Concat(nextOfEnd.LeadingTrivia));
var newPreviousOfStart = previousOfStart.WithTrailingTrivia();
var newNextOfEnd = nextOfEnd.WithLeadingTrivia();
var newSubtreeRoot = subtreeRoot.ReplaceTokens(new[] { startToken, previousOfStart, endToken, nextOfEnd },
(o, n) =>
{
if (o == currentStartToken)
{
return startAndEndTokensAreSame ? newEndToken : newStartToken;
}
else if (o == previousOfStart)
{
return newPreviousOfStart;
}
else if (o == currentEndToken)
{
return newEndToken;
}
else if (o == nextOfEnd)
{
return newNextOfEnd;
}
else
{
return n;
}
});
root = root.ReplaceNode(subtreeRoot, newSubtreeRoot);
document = document.WithSyntaxRoot(root);
suppressionTargetInfo.StartToken = root.FindToken(startToken.SpanStart);
suppressionTargetInfo.EndToken = root.FindToken(endToken.SpanStart);
suppressionTargetInfo.NodeWithTokens = fixer.GetNodeWithTokens(suppressionTargetInfo.StartToken, suppressionTargetInfo.EndToken, root);
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.PooledObjects;
using Roslyn.Utilities;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedType : Cci.INamespaceTypeDefinition
{
public readonly TEmbeddedTypesManager TypeManager;
public readonly TNamedTypeSymbol UnderlyingNamedType;
private ImmutableArray<Cci.IFieldDefinition> _lazyFields;
private ImmutableArray<Cci.IMethodDefinition> _lazyMethods;
private ImmutableArray<Cci.IPropertyDefinition> _lazyProperties;
private ImmutableArray<Cci.IEventDefinition> _lazyEvents;
private ImmutableArray<TAttributeData> _lazyAttributes;
private int _lazyAssemblyRefIndex = -1;
protected CommonEmbeddedType(TEmbeddedTypesManager typeManager, TNamedTypeSymbol underlyingNamedType)
{
this.TypeManager = typeManager;
this.UnderlyingNamedType = underlyingNamedType;
}
protected abstract int GetAssemblyRefIndex();
protected abstract IEnumerable<TFieldSymbol> GetFieldsToEmit();
protected abstract IEnumerable<TMethodSymbol> GetMethodsToEmit();
protected abstract IEnumerable<TEventSymbol> GetEventsToEmit();
protected abstract IEnumerable<TPropertySymbol> GetPropertiesToEmit();
protected abstract bool IsPublic { get; }
protected abstract bool IsAbstract { get; }
protected abstract Cci.ITypeReference GetBaseClass(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract IEnumerable<Cci.TypeReferenceWithAttributes> GetInterfaces(EmitContext context);
protected abstract bool IsBeforeFieldInit { get; }
protected abstract bool IsComImport { get; }
protected abstract bool IsInterface { get; }
protected abstract bool IsDelegate { get; }
protected abstract bool IsSerializable { get; }
protected abstract bool IsSpecialName { get; }
protected abstract bool IsWindowsRuntimeImport { get; }
protected abstract bool IsSealed { get; }
protected abstract TypeLayout? GetTypeLayoutIfStruct();
protected abstract System.Runtime.InteropServices.CharSet StringFormat { get; }
protected abstract TAttributeData CreateTypeIdentifierAttribute(bool hasGuid, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract void EmbedDefaultMembers(string defaultMember, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder);
protected abstract void ReportMissingAttribute(AttributeDescription description, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description)
{
return TypeManager.IsTargetAttribute(UnderlyingNamedType, attrData, description);
}
private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var builder = ArrayBuilder<TAttributeData>.GetInstance();
// Put the CompilerGenerated attribute on the NoPIA types we define so that
// static analysis tools (e.g. fxcop) know that they can be skipped
builder.AddOptional(TypeManager.CreateCompilerGeneratedAttribute());
// Copy some of the attributes.
bool hasGuid = false;
bool hasComEventInterfaceAttribute = false;
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder))
{
if (IsTargetAttribute(attrData, AttributeDescription.GuidAttribute))
{
string guidString;
if (attrData.TryGetGuidAttributeValue(out guidString))
{
// If this type has a GuidAttribute, we should emit it.
hasGuid = true;
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_GuidAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.ComEventInterfaceAttribute))
{
if (attrData.CommonConstructorArguments.Length == 2)
{
hasComEventInterfaceAttribute = true;
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else
{
int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingNamedType, attrData, AttributeDescription.InterfaceTypeAttribute);
if (signatureIndex != -1)
{
Debug.Assert(signatureIndex == 0 || signatureIndex == 1);
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(signatureIndex == 0 ? WellKnownMember.System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 :
WellKnownMember.System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType,
attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.BestFitMappingAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_BestFitMappingAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.CoClassAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_CoClassAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.FlagsAttribute))
{
if (attrData.CommonConstructorArguments.Length == 0 && UnderlyingNamedType.IsEnum)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_FlagsAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.DefaultMemberAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
// Embed members matching default member name.
string defaultMember = attrData.CommonConstructorArguments[0].ValueInternal as string;
if (defaultMember != null)
{
EmbedDefaultMembers(defaultMember, syntaxNodeOpt, diagnostics);
}
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.UnmanagedFunctionPointerAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
}
}
// We must emit a TypeIdentifier attribute which connects this local type with the canonical type.
// Interfaces usually have a guid attribute, in which case the TypeIdentifier attribute we emit will
// not need any additional parameters. For interfaces which lack a guid and all other types, we must
// emit a TypeIdentifier that has parameters identifying the scope and name of the original type. We
// will use the Assembly GUID as the scope identifier.
if (IsInterface && !hasComEventInterfaceAttribute)
{
if (!IsComImport)
{
// If we have an interface not marked ComImport, but the assembly is linked, then
// we need to give an error. We allow event interfaces to not have ComImport marked on them.
// ERRID_NoPIAAttributeMissing2/ERR_InteropTypeMissingAttribute
ReportMissingAttribute(AttributeDescription.ComImportAttribute, syntaxNodeOpt, diagnostics);
}
else if (!hasGuid)
{
// Interfaces used with No-PIA ought to have a guid attribute, or the CLR cannot do type unification.
// This interface lacks a guid, so unification probably won't work. We allow event interfaces to not have a Guid.
// ERRID_NoPIAAttributeMissing2/ERR_InteropTypeMissingAttribute
ReportMissingAttribute(AttributeDescription.GuidAttribute, syntaxNodeOpt, diagnostics);
}
}
// Note, this logic should match the one in RetargetingSymbolTranslator.RetargetNoPiaLocalType
// when we try to predict what attributes we will emit on embedded type, which corresponds the
// type we are retargeting.
builder.AddOptional(CreateTypeIdentifierAttribute(hasGuid && IsInterface, syntaxNodeOpt, diagnostics));
return builder.ToImmutableAndFree();
}
public int AssemblyRefIndex
{
get
{
if (_lazyAssemblyRefIndex == -1)
{
_lazyAssemblyRefIndex = GetAssemblyRefIndex();
Debug.Assert(_lazyAssemblyRefIndex >= 0);
}
return _lazyAssemblyRefIndex;
}
}
bool Cci.INamespaceTypeDefinition.IsPublic
{
get
{
return IsPublic;
}
}
Cci.ITypeReference Cci.ITypeDefinition.GetBaseClass(EmitContext context)
{
return GetBaseClass((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics);
}
IEnumerable<Cci.IEventDefinition> Cci.ITypeDefinition.GetEvents(EmitContext context)
{
if (_lazyEvents.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IEventDefinition>.GetInstance();
foreach (var e in GetEventsToEmit())
{
TEmbeddedEvent embedded;
if (TypeManager.EmbeddedEventsMap.TryGetValue(e, out embedded))
{
builder.Add(embedded);
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyEvents, builder.ToImmutableAndFree());
}
return _lazyEvents;
}
IEnumerable<Cci.MethodImplementation> Cci.ITypeDefinition.GetExplicitImplementationOverrides(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.MethodImplementation>();
}
IEnumerable<Cci.IFieldDefinition> Cci.ITypeDefinition.GetFields(EmitContext context)
{
if (_lazyFields.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IFieldDefinition>.GetInstance();
foreach (var f in GetFieldsToEmit())
{
TEmbeddedField embedded;
if (TypeManager.EmbeddedFieldsMap.TryGetValue(f, out embedded))
{
builder.Add(embedded);
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyFields, builder.ToImmutableAndFree());
}
return _lazyFields;
}
IEnumerable<Cci.IGenericTypeParameter> Cci.ITypeDefinition.GenericParameters
{
get
{
return SpecializedCollections.EmptyEnumerable<Cci.IGenericTypeParameter>();
}
}
ushort Cci.ITypeDefinition.GenericParameterCount
{
get
{
return 0;
}
}
bool Cci.ITypeDefinition.HasDeclarativeSecurity
{
get
{
// None of the transferrable attributes are security attributes.
return false;
}
}
IEnumerable<Cci.TypeReferenceWithAttributes> Cci.ITypeDefinition.Interfaces(EmitContext context)
{
return GetInterfaces(context);
}
bool Cci.ITypeDefinition.IsAbstract
{
get
{
return IsAbstract;
}
}
bool Cci.ITypeDefinition.IsBeforeFieldInit
{
get
{
return IsBeforeFieldInit;
}
}
bool Cci.ITypeDefinition.IsComObject
{
get
{
return IsInterface || IsComImport;
}
}
bool Cci.ITypeDefinition.IsGeneric
{
get
{
return false;
}
}
bool Cci.ITypeDefinition.IsInterface
{
get
{
return IsInterface;
}
}
bool Cci.ITypeDefinition.IsDelegate
{
get
{
return IsDelegate;
}
}
bool Cci.ITypeDefinition.IsRuntimeSpecial
{
get
{
return false;
}
}
bool Cci.ITypeDefinition.IsSerializable
{
get
{
return IsSerializable;
}
}
bool Cci.ITypeDefinition.IsSpecialName
{
get
{
return IsSpecialName;
}
}
bool Cci.ITypeDefinition.IsWindowsRuntimeImport
{
get
{
return IsWindowsRuntimeImport;
}
}
bool Cci.ITypeDefinition.IsSealed
{
get
{
return IsSealed;
}
}
System.Runtime.InteropServices.LayoutKind Cci.ITypeDefinition.Layout
{
get
{
var layout = GetTypeLayoutIfStruct();
return layout?.Kind ?? System.Runtime.InteropServices.LayoutKind.Auto;
}
}
ushort Cci.ITypeDefinition.Alignment
{
get
{
var layout = GetTypeLayoutIfStruct();
return (ushort)(layout?.Alignment ?? 0);
}
}
uint Cci.ITypeDefinition.SizeOf
{
get
{
var layout = GetTypeLayoutIfStruct();
return (uint)(layout?.Size ?? 0);
}
}
IEnumerable<Cci.IMethodDefinition> Cci.ITypeDefinition.GetMethods(EmitContext context)
{
if (_lazyMethods.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IMethodDefinition>.GetInstance();
int gapIndex = 1;
int gapSize = 0;
foreach (var method in GetMethodsToEmit())
{
if ((object)method != null)
{
TEmbeddedMethod embedded;
if (TypeManager.EmbeddedMethodsMap.TryGetValue(method, out embedded))
{
if (gapSize > 0)
{
builder.Add(new VtblGap(this, ModuleExtensions.GetVTableGapName(gapIndex, gapSize)));
gapIndex++;
gapSize = 0;
}
builder.Add(embedded);
}
else
{
gapSize++;
}
}
else
{
gapSize++;
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyMethods, builder.ToImmutableAndFree());
}
return _lazyMethods;
}
IEnumerable<Cci.INestedTypeDefinition> Cci.ITypeDefinition.GetNestedTypes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.INestedTypeDefinition>();
}
IEnumerable<Cci.IPropertyDefinition> Cci.ITypeDefinition.GetProperties(EmitContext context)
{
if (_lazyProperties.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IPropertyDefinition>.GetInstance();
foreach (var p in GetPropertiesToEmit())
{
TEmbeddedProperty embedded;
if (TypeManager.EmbeddedPropertiesMap.TryGetValue(p, out embedded))
{
builder.Add(embedded);
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyProperties, builder.ToImmutableAndFree());
}
return _lazyProperties;
}
IEnumerable<Cci.SecurityAttribute> Cci.ITypeDefinition.SecurityAttributes
{
get
{
// None of the transferrable attributes are security attributes.
return SpecializedCollections.EmptyEnumerable<Cci.SecurityAttribute>();
}
}
System.Runtime.InteropServices.CharSet Cci.ITypeDefinition.StringFormat
{
get
{
return StringFormat;
}
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
if (_lazyAttributes.IsDefault)
{
var diagnostics = DiagnosticBag.GetInstance();
var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes))
{
// Save any diagnostics that we encountered.
context.Diagnostics.AddRange(diagnostics);
}
diagnostics.Free();
}
return _lazyAttributes;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
bool Cci.ITypeReference.IsEnum
{
get
{
return UnderlyingNamedType.IsEnum;
}
}
bool Cci.ITypeReference.IsValueType
{
get
{
return UnderlyingNamedType.IsValueType;
}
}
Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context)
{
return this;
}
Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode
{
get
{
return Cci.PrimitiveTypeCode.NotPrimitive;
}
}
TypeDefinitionHandle Cci.ITypeReference.TypeDef
{
get
{
return default(TypeDefinitionHandle);
}
}
Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference
{
get
{
return null;
}
}
Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference
{
get
{
return null;
}
}
Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference
{
get
{
return null;
}
}
Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context)
{
return this;
}
Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference
{
get
{
return this;
}
}
Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context)
{
return null;
}
Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference
{
get
{
return null;
}
}
Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference
{
get
{
return null;
}
}
Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context)
{
return this;
}
ushort Cci.INamedTypeReference.GenericParameterCount
{
get
{
return 0;
}
}
bool Cci.INamedTypeReference.MangleName
{
get
{
return UnderlyingNamedType.MangleName;
}
}
string Cci.INamedEntity.Name
{
get
{
return UnderlyingNamedType.Name;
}
}
Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context)
{
return TypeManager.ModuleBeingBuilt;
}
string Cci.INamespaceTypeReference.NamespaceName
{
get
{
return UnderlyingNamedType.NamespaceName;
}
}
/// <remarks>
/// This is only used for testing.
/// </remarks>
public override string ToString()
{
return UnderlyingNamedType.GetInternalSymbol().GetISymbol().ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat);
}
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.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedType : Cci.INamespaceTypeDefinition
{
public readonly TEmbeddedTypesManager TypeManager;
public readonly TNamedTypeSymbol UnderlyingNamedType;
private ImmutableArray<Cci.IFieldDefinition> _lazyFields;
private ImmutableArray<Cci.IMethodDefinition> _lazyMethods;
private ImmutableArray<Cci.IPropertyDefinition> _lazyProperties;
private ImmutableArray<Cci.IEventDefinition> _lazyEvents;
private ImmutableArray<TAttributeData> _lazyAttributes;
private int _lazyAssemblyRefIndex = -1;
protected CommonEmbeddedType(TEmbeddedTypesManager typeManager, TNamedTypeSymbol underlyingNamedType)
{
this.TypeManager = typeManager;
this.UnderlyingNamedType = underlyingNamedType;
}
protected abstract int GetAssemblyRefIndex();
protected abstract IEnumerable<TFieldSymbol> GetFieldsToEmit();
protected abstract IEnumerable<TMethodSymbol> GetMethodsToEmit();
protected abstract IEnumerable<TEventSymbol> GetEventsToEmit();
protected abstract IEnumerable<TPropertySymbol> GetPropertiesToEmit();
protected abstract bool IsPublic { get; }
protected abstract bool IsAbstract { get; }
protected abstract Cci.ITypeReference GetBaseClass(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract IEnumerable<Cci.TypeReferenceWithAttributes> GetInterfaces(EmitContext context);
protected abstract bool IsBeforeFieldInit { get; }
protected abstract bool IsComImport { get; }
protected abstract bool IsInterface { get; }
protected abstract bool IsDelegate { get; }
protected abstract bool IsSerializable { get; }
protected abstract bool IsSpecialName { get; }
protected abstract bool IsWindowsRuntimeImport { get; }
protected abstract bool IsSealed { get; }
protected abstract TypeLayout? GetTypeLayoutIfStruct();
protected abstract System.Runtime.InteropServices.CharSet StringFormat { get; }
protected abstract TAttributeData CreateTypeIdentifierAttribute(bool hasGuid, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract void EmbedDefaultMembers(string defaultMember, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder);
protected abstract void ReportMissingAttribute(AttributeDescription description, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description)
{
return TypeManager.IsTargetAttribute(UnderlyingNamedType, attrData, description);
}
private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var builder = ArrayBuilder<TAttributeData>.GetInstance();
// Put the CompilerGenerated attribute on the NoPIA types we define so that
// static analysis tools (e.g. fxcop) know that they can be skipped
builder.AddOptional(TypeManager.CreateCompilerGeneratedAttribute());
// Copy some of the attributes.
bool hasGuid = false;
bool hasComEventInterfaceAttribute = false;
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder))
{
if (IsTargetAttribute(attrData, AttributeDescription.GuidAttribute))
{
string guidString;
if (attrData.TryGetGuidAttributeValue(out guidString))
{
// If this type has a GuidAttribute, we should emit it.
hasGuid = true;
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_GuidAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.ComEventInterfaceAttribute))
{
if (attrData.CommonConstructorArguments.Length == 2)
{
hasComEventInterfaceAttribute = true;
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else
{
int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingNamedType, attrData, AttributeDescription.InterfaceTypeAttribute);
if (signatureIndex != -1)
{
Debug.Assert(signatureIndex == 0 || signatureIndex == 1);
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(signatureIndex == 0 ? WellKnownMember.System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 :
WellKnownMember.System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType,
attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.BestFitMappingAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_BestFitMappingAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.CoClassAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_CoClassAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.FlagsAttribute))
{
if (attrData.CommonConstructorArguments.Length == 0 && UnderlyingNamedType.IsEnum)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_FlagsAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.DefaultMemberAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
// Embed members matching default member name.
string defaultMember = attrData.CommonConstructorArguments[0].ValueInternal as string;
if (defaultMember != null)
{
EmbedDefaultMembers(defaultMember, syntaxNodeOpt, diagnostics);
}
}
}
else if (IsTargetAttribute(attrData, AttributeDescription.UnmanagedFunctionPointerAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
}
}
// We must emit a TypeIdentifier attribute which connects this local type with the canonical type.
// Interfaces usually have a guid attribute, in which case the TypeIdentifier attribute we emit will
// not need any additional parameters. For interfaces which lack a guid and all other types, we must
// emit a TypeIdentifier that has parameters identifying the scope and name of the original type. We
// will use the Assembly GUID as the scope identifier.
if (IsInterface && !hasComEventInterfaceAttribute)
{
if (!IsComImport)
{
// If we have an interface not marked ComImport, but the assembly is linked, then
// we need to give an error. We allow event interfaces to not have ComImport marked on them.
// ERRID_NoPIAAttributeMissing2/ERR_InteropTypeMissingAttribute
ReportMissingAttribute(AttributeDescription.ComImportAttribute, syntaxNodeOpt, diagnostics);
}
else if (!hasGuid)
{
// Interfaces used with No-PIA ought to have a guid attribute, or the CLR cannot do type unification.
// This interface lacks a guid, so unification probably won't work. We allow event interfaces to not have a Guid.
// ERRID_NoPIAAttributeMissing2/ERR_InteropTypeMissingAttribute
ReportMissingAttribute(AttributeDescription.GuidAttribute, syntaxNodeOpt, diagnostics);
}
}
// Note, this logic should match the one in RetargetingSymbolTranslator.RetargetNoPiaLocalType
// when we try to predict what attributes we will emit on embedded type, which corresponds the
// type we are retargeting.
builder.AddOptional(CreateTypeIdentifierAttribute(hasGuid && IsInterface, syntaxNodeOpt, diagnostics));
return builder.ToImmutableAndFree();
}
public int AssemblyRefIndex
{
get
{
if (_lazyAssemblyRefIndex == -1)
{
_lazyAssemblyRefIndex = GetAssemblyRefIndex();
Debug.Assert(_lazyAssemblyRefIndex >= 0);
}
return _lazyAssemblyRefIndex;
}
}
bool Cci.INamespaceTypeDefinition.IsPublic
{
get
{
return IsPublic;
}
}
Cci.ITypeReference Cci.ITypeDefinition.GetBaseClass(EmitContext context)
{
return GetBaseClass((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics);
}
IEnumerable<Cci.IEventDefinition> Cci.ITypeDefinition.GetEvents(EmitContext context)
{
if (_lazyEvents.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IEventDefinition>.GetInstance();
foreach (var e in GetEventsToEmit())
{
TEmbeddedEvent embedded;
if (TypeManager.EmbeddedEventsMap.TryGetValue(e, out embedded))
{
builder.Add(embedded);
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyEvents, builder.ToImmutableAndFree());
}
return _lazyEvents;
}
IEnumerable<Cci.MethodImplementation> Cci.ITypeDefinition.GetExplicitImplementationOverrides(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.MethodImplementation>();
}
IEnumerable<Cci.IFieldDefinition> Cci.ITypeDefinition.GetFields(EmitContext context)
{
if (_lazyFields.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IFieldDefinition>.GetInstance();
foreach (var f in GetFieldsToEmit())
{
TEmbeddedField embedded;
if (TypeManager.EmbeddedFieldsMap.TryGetValue(f, out embedded))
{
builder.Add(embedded);
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyFields, builder.ToImmutableAndFree());
}
return _lazyFields;
}
IEnumerable<Cci.IGenericTypeParameter> Cci.ITypeDefinition.GenericParameters
{
get
{
return SpecializedCollections.EmptyEnumerable<Cci.IGenericTypeParameter>();
}
}
ushort Cci.ITypeDefinition.GenericParameterCount
{
get
{
return 0;
}
}
bool Cci.ITypeDefinition.HasDeclarativeSecurity
{
get
{
// None of the transferrable attributes are security attributes.
return false;
}
}
IEnumerable<Cci.TypeReferenceWithAttributes> Cci.ITypeDefinition.Interfaces(EmitContext context)
{
return GetInterfaces(context);
}
bool Cci.ITypeDefinition.IsAbstract
{
get
{
return IsAbstract;
}
}
bool Cci.ITypeDefinition.IsBeforeFieldInit
{
get
{
return IsBeforeFieldInit;
}
}
bool Cci.ITypeDefinition.IsComObject
{
get
{
return IsInterface || IsComImport;
}
}
bool Cci.ITypeDefinition.IsGeneric
{
get
{
return false;
}
}
bool Cci.ITypeDefinition.IsInterface
{
get
{
return IsInterface;
}
}
bool Cci.ITypeDefinition.IsDelegate
{
get
{
return IsDelegate;
}
}
bool Cci.ITypeDefinition.IsRuntimeSpecial
{
get
{
return false;
}
}
bool Cci.ITypeDefinition.IsSerializable
{
get
{
return IsSerializable;
}
}
bool Cci.ITypeDefinition.IsSpecialName
{
get
{
return IsSpecialName;
}
}
bool Cci.ITypeDefinition.IsWindowsRuntimeImport
{
get
{
return IsWindowsRuntimeImport;
}
}
bool Cci.ITypeDefinition.IsSealed
{
get
{
return IsSealed;
}
}
System.Runtime.InteropServices.LayoutKind Cci.ITypeDefinition.Layout
{
get
{
var layout = GetTypeLayoutIfStruct();
return layout?.Kind ?? System.Runtime.InteropServices.LayoutKind.Auto;
}
}
ushort Cci.ITypeDefinition.Alignment
{
get
{
var layout = GetTypeLayoutIfStruct();
return (ushort)(layout?.Alignment ?? 0);
}
}
uint Cci.ITypeDefinition.SizeOf
{
get
{
var layout = GetTypeLayoutIfStruct();
return (uint)(layout?.Size ?? 0);
}
}
IEnumerable<Cci.IMethodDefinition> Cci.ITypeDefinition.GetMethods(EmitContext context)
{
if (_lazyMethods.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IMethodDefinition>.GetInstance();
int gapIndex = 1;
int gapSize = 0;
foreach (var method in GetMethodsToEmit())
{
if ((object)method != null)
{
TEmbeddedMethod embedded;
if (TypeManager.EmbeddedMethodsMap.TryGetValue(method, out embedded))
{
if (gapSize > 0)
{
builder.Add(new VtblGap(this, ModuleExtensions.GetVTableGapName(gapIndex, gapSize)));
gapIndex++;
gapSize = 0;
}
builder.Add(embedded);
}
else
{
gapSize++;
}
}
else
{
gapSize++;
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyMethods, builder.ToImmutableAndFree());
}
return _lazyMethods;
}
IEnumerable<Cci.INestedTypeDefinition> Cci.ITypeDefinition.GetNestedTypes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.INestedTypeDefinition>();
}
IEnumerable<Cci.IPropertyDefinition> Cci.ITypeDefinition.GetProperties(EmitContext context)
{
if (_lazyProperties.IsDefault)
{
Debug.Assert(TypeManager.IsFrozen);
var builder = ArrayBuilder<Cci.IPropertyDefinition>.GetInstance();
foreach (var p in GetPropertiesToEmit())
{
TEmbeddedProperty embedded;
if (TypeManager.EmbeddedPropertiesMap.TryGetValue(p, out embedded))
{
builder.Add(embedded);
}
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyProperties, builder.ToImmutableAndFree());
}
return _lazyProperties;
}
IEnumerable<Cci.SecurityAttribute> Cci.ITypeDefinition.SecurityAttributes
{
get
{
// None of the transferrable attributes are security attributes.
return SpecializedCollections.EmptyEnumerable<Cci.SecurityAttribute>();
}
}
System.Runtime.InteropServices.CharSet Cci.ITypeDefinition.StringFormat
{
get
{
return StringFormat;
}
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
if (_lazyAttributes.IsDefault)
{
var diagnostics = DiagnosticBag.GetInstance();
var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes))
{
// Save any diagnostics that we encountered.
context.Diagnostics.AddRange(diagnostics);
}
diagnostics.Free();
}
return _lazyAttributes;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
bool Cci.ITypeReference.IsEnum
{
get
{
return UnderlyingNamedType.IsEnum;
}
}
bool Cci.ITypeReference.IsValueType
{
get
{
return UnderlyingNamedType.IsValueType;
}
}
Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context)
{
return this;
}
Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode
{
get
{
return Cci.PrimitiveTypeCode.NotPrimitive;
}
}
TypeDefinitionHandle Cci.ITypeReference.TypeDef
{
get
{
return default(TypeDefinitionHandle);
}
}
Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference
{
get
{
return null;
}
}
Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference
{
get
{
return null;
}
}
Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference
{
get
{
return null;
}
}
Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context)
{
return this;
}
Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference
{
get
{
return this;
}
}
Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context)
{
return null;
}
Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference
{
get
{
return null;
}
}
Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference
{
get
{
return null;
}
}
Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context)
{
return this;
}
ushort Cci.INamedTypeReference.GenericParameterCount
{
get
{
return 0;
}
}
bool Cci.INamedTypeReference.MangleName
{
get
{
return UnderlyingNamedType.MangleName;
}
}
string Cci.INamedEntity.Name
{
get
{
return UnderlyingNamedType.Name;
}
}
Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context)
{
return TypeManager.ModuleBeingBuilt;
}
string Cci.INamespaceTypeReference.NamespaceName
{
get
{
return UnderlyingNamedType.NamespaceName;
}
}
/// <remarks>
/// This is only used for testing.
/// </remarks>
public override string ToString()
{
return UnderlyingNamedType.GetInternalSymbol().GetISymbol().ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat);
}
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 | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal static class ActiveStatementTestHelpers
{
public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp(
string[] markedSources,
string[]? filePaths = null,
int[]? methodRowIds = null,
Guid[]? modules = null,
int[]? methodVersions = null,
int[]? ilOffsets = null,
ActiveStatementFlags[]? flags = null)
{
return ActiveStatementsDescription.GetActiveStatementDebugInfos(
(source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path),
markedSources,
filePaths,
extension: ".cs",
methodRowIds,
modules,
methodVersions,
ilOffsets,
flags);
}
public static string Delete(string src, string marker)
{
while (true)
{
var startStr = "/*delete" + marker;
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length;
src = src.Substring(0, start) + src.Substring(end);
}
}
/// <summary>
/// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/.
/// </summary>
public static string InsertNewLines(string src, string marker)
{
while (true)
{
var startStr = "/*insert" + marker + "[";
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var startOfLineCount = start + startStr.Length;
var endOfLineCount = src.IndexOf(']', startOfLineCount);
var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount));
var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length;
src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end);
}
}
public static string Update(string src, string marker)
=> InsertNewLines(Delete(src, marker), marker);
public static string InspectActiveStatement(ActiveStatement statement)
=> $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]";
public static string InspectActiveStatementAndInstruction(ActiveStatement statement)
=> InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay();
public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text)
=> InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'";
public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update)
=> $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}";
public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions)
=> regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}");
public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r)
=> $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}";
public static string GetFirstLineText(LinePositionSpan span, SourceText text)
=> text.Lines[span.Start.Line].ToString().Trim();
public static string InspectSequencePointUpdates(SequencePointUpdates updates)
=> $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]";
public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates)
=> updates.Select(InspectSequencePointUpdates);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal static class ActiveStatementTestHelpers
{
public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp(
string[] markedSources,
string[]? filePaths = null,
int[]? methodRowIds = null,
Guid[]? modules = null,
int[]? methodVersions = null,
int[]? ilOffsets = null,
ActiveStatementFlags[]? flags = null)
{
return ActiveStatementsDescription.GetActiveStatementDebugInfos(
(source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path),
markedSources,
filePaths,
extension: ".cs",
methodRowIds,
modules,
methodVersions,
ilOffsets,
flags);
}
public static string Delete(string src, string marker)
{
while (true)
{
var startStr = "/*delete" + marker;
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length;
src = src.Substring(0, start) + src.Substring(end);
}
}
/// <summary>
/// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/.
/// </summary>
public static string InsertNewLines(string src, string marker)
{
while (true)
{
var startStr = "/*insert" + marker + "[";
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var startOfLineCount = start + startStr.Length;
var endOfLineCount = src.IndexOf(']', startOfLineCount);
var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount));
var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length;
src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end);
}
}
public static string Update(string src, string marker)
=> InsertNewLines(Delete(src, marker), marker);
public static string InspectActiveStatement(ActiveStatement statement)
=> $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]";
public static string InspectActiveStatementAndInstruction(ActiveStatement statement)
=> InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay();
public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text)
=> InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'";
public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update)
=> $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}";
public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions)
=> regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}");
public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r)
=> $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}";
public static string GetFirstLineText(LinePositionSpan span, SourceText text)
=> text.Lines[span.Start.Line].ToString().Trim();
public static string InspectSequencePointUpdates(SequencePointUpdates updates)
=> $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]";
public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates)
=> updates.Select(InspectSequencePointUpdates);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/GenerateMember/GenerateVariable/AbstractGenerateVariableService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddParameter;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable
{
internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> :
AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>, IGenerateVariableService
where TService : AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax>
where TSimpleNameSyntax : TExpressionSyntax
where TExpressionSyntax : SyntaxNode
{
protected AbstractGenerateVariableService()
{
}
protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node);
protected abstract bool IsIdentifierNameGeneration(SyntaxNode node);
protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeIdentifierNameState(SemanticDocument document, TSimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isinConditionalAccessExpression);
protected abstract bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxNode newRoot);
public async Task<ImmutableArray<CodeAction>> GenerateVariableAsync(
Document document,
SyntaxNode node,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateVariable, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return ImmutableArray<CodeAction>.Empty;
}
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions);
var canGenerateMember = CodeGenerator.CanAdd(document.Project.Solution, state.TypeToGenerateIn, cancellationToken);
if (canGenerateMember && state.CanGeneratePropertyOrField())
{
// prefer fields over properties (and vice versa) depending on the casing of the member.
// lowercase -> fields. title case -> properties.
var name = state.IdentifierToken.ValueText;
if (char.IsUpper(name.ToCharArray().FirstOrDefault()))
{
AddPropertyCodeActions(actions, semanticDocument, state);
AddFieldCodeActions(actions, semanticDocument, state);
}
else
{
AddFieldCodeActions(actions, semanticDocument, state);
AddPropertyCodeActions(actions, semanticDocument, state);
}
}
AddLocalCodeActions(actions, document, state);
AddParameterCodeActions(actions, document, state);
if (actions.Count > 1)
{
// Wrap the generate variable actions into a single top level suggestion
// so as to not clutter the list.
return ImmutableArray.Create<CodeAction>(new MyCodeAction(
string.Format(FeaturesResources.Generate_variable_0, state.IdentifierToken.ValueText),
actions.ToImmutable()));
}
return actions.ToImmutable();
}
}
protected virtual bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
=> false;
private static void AddPropertyCodeActions(
ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
if (state.IsInOutContext)
{
return;
}
if (state.IsConstant)
{
return;
}
if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface && state.IsStatic)
{
return;
}
var isOnlyReadAndIsInInterface = state.TypeToGenerateIn.TypeKind == TypeKind.Interface && !state.IsWrittenTo;
if (isOnlyReadAndIsInInterface || state.IsInConstructor)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: true, isReadonly: true, isConstant: false,
refKind: GetRefKindFromContext(state)));
}
GenerateWritableProperty(result, document, state);
}
private static void GenerateWritableProperty(ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: true, isReadonly: false, isConstant: false,
refKind: GetRefKindFromContext(state)));
}
private static void AddFieldCodeActions(ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
if (state.TypeToGenerateIn.TypeKind != TypeKind.Interface)
{
if (state.IsConstant)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: false, isReadonly: false, isConstant: true, refKind: RefKind.None));
}
else
{
if (!state.OfferReadOnlyFieldFirst)
{
GenerateWriteableField(result, document, state);
}
// If we haven't written to the field, or we're in the constructor for the type
// we're writing into, then we can generate this field read-only.
if (!state.IsWrittenTo || state.IsInConstructor)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: false, isReadonly: true, isConstant: false, refKind: RefKind.None));
}
if (state.OfferReadOnlyFieldFirst)
{
GenerateWriteableField(result, document, state);
}
}
}
}
private static void GenerateWriteableField(ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: false, isReadonly: false, isConstant: false, refKind: RefKind.None));
}
private void AddLocalCodeActions(ArrayBuilder<CodeAction> result, Document document, State state)
{
if (state.CanGenerateLocal())
{
result.Add(new GenerateLocalCodeAction((TService)this, document, state));
}
}
private static void AddParameterCodeActions(ArrayBuilder<CodeAction> result, Document document, State state)
{
if (state.CanGenerateParameter())
{
result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: false));
if (AddParameterService.Instance.HasCascadingDeclarations(state.ContainingMethod))
result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: true));
}
}
private static RefKind GetRefKindFromContext(State state)
{
if (state.IsInRefContext)
{
return RefKind.Ref;
}
else if (state.IsInInContext)
{
return RefKind.RefReadOnly;
}
else
{
return RefKind.None;
}
}
private class MyCodeAction : CodeAction.CodeActionWithNestedActions
{
public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions)
: base(title, nestedActions, isInlinable: 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.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddParameter;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable
{
internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> :
AbstractGenerateMemberService<TSimpleNameSyntax, TExpressionSyntax>, IGenerateVariableService
where TService : AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax>
where TSimpleNameSyntax : TExpressionSyntax
where TExpressionSyntax : SyntaxNode
{
protected AbstractGenerateVariableService()
{
}
protected abstract bool IsExplicitInterfaceGeneration(SyntaxNode node);
protected abstract bool IsIdentifierNameGeneration(SyntaxNode node);
protected abstract bool TryInitializeExplicitInterfaceState(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken identifierToken, out IPropertySymbol propertySymbol, out INamedTypeSymbol typeToGenerateIn);
protected abstract bool TryInitializeIdentifierNameState(SemanticDocument document, TSimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out TExpressionSyntax simpleNameOrMemberAccessExpression, out bool isInExecutableBlock, out bool isinConditionalAccessExpression);
protected abstract bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, OptionSet options, SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxNode newRoot);
public async Task<ImmutableArray<CodeAction>> GenerateVariableAsync(
Document document,
SyntaxNode node,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateVariable, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return ImmutableArray<CodeAction>.Empty;
}
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions);
var canGenerateMember = CodeGenerator.CanAdd(document.Project.Solution, state.TypeToGenerateIn, cancellationToken);
if (canGenerateMember && state.CanGeneratePropertyOrField())
{
// prefer fields over properties (and vice versa) depending on the casing of the member.
// lowercase -> fields. title case -> properties.
var name = state.IdentifierToken.ValueText;
if (char.IsUpper(name.ToCharArray().FirstOrDefault()))
{
AddPropertyCodeActions(actions, semanticDocument, state);
AddFieldCodeActions(actions, semanticDocument, state);
}
else
{
AddFieldCodeActions(actions, semanticDocument, state);
AddPropertyCodeActions(actions, semanticDocument, state);
}
}
AddLocalCodeActions(actions, document, state);
AddParameterCodeActions(actions, document, state);
if (actions.Count > 1)
{
// Wrap the generate variable actions into a single top level suggestion
// so as to not clutter the list.
return ImmutableArray.Create<CodeAction>(new MyCodeAction(
string.Format(FeaturesResources.Generate_variable_0, state.IdentifierToken.ValueText),
actions.ToImmutable()));
}
return actions.ToImmutable();
}
}
protected virtual bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType)
=> false;
private static void AddPropertyCodeActions(
ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
if (state.IsInOutContext)
{
return;
}
if (state.IsConstant)
{
return;
}
if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface && state.IsStatic)
{
return;
}
var isOnlyReadAndIsInInterface = state.TypeToGenerateIn.TypeKind == TypeKind.Interface && !state.IsWrittenTo;
if (isOnlyReadAndIsInInterface || state.IsInConstructor)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: true, isReadonly: true, isConstant: false,
refKind: GetRefKindFromContext(state)));
}
GenerateWritableProperty(result, document, state);
}
private static void GenerateWritableProperty(ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: true, isReadonly: false, isConstant: false,
refKind: GetRefKindFromContext(state)));
}
private static void AddFieldCodeActions(ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
if (state.TypeToGenerateIn.TypeKind != TypeKind.Interface)
{
if (state.IsConstant)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: false, isReadonly: false, isConstant: true, refKind: RefKind.None));
}
else
{
if (!state.OfferReadOnlyFieldFirst)
{
GenerateWriteableField(result, document, state);
}
// If we haven't written to the field, or we're in the constructor for the type
// we're writing into, then we can generate this field read-only.
if (!state.IsWrittenTo || state.IsInConstructor)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: false, isReadonly: true, isConstant: false, refKind: RefKind.None));
}
if (state.OfferReadOnlyFieldFirst)
{
GenerateWriteableField(result, document, state);
}
}
}
}
private static void GenerateWriteableField(ArrayBuilder<CodeAction> result, SemanticDocument document, State state)
{
result.Add(new GenerateVariableCodeAction(
document, state, generateProperty: false, isReadonly: false, isConstant: false, refKind: RefKind.None));
}
private void AddLocalCodeActions(ArrayBuilder<CodeAction> result, Document document, State state)
{
if (state.CanGenerateLocal())
{
result.Add(new GenerateLocalCodeAction((TService)this, document, state));
}
}
private static void AddParameterCodeActions(ArrayBuilder<CodeAction> result, Document document, State state)
{
if (state.CanGenerateParameter())
{
result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: false));
if (AddParameterService.Instance.HasCascadingDeclarations(state.ContainingMethod))
result.Add(new GenerateParameterCodeAction(document, state, includeOverridesAndImplementations: true));
}
}
private static RefKind GetRefKindFromContext(State state)
{
if (state.IsInRefContext)
{
return RefKind.Ref;
}
else if (state.IsInInContext)
{
return RefKind.RefReadOnly;
}
else
{
return RefKind.None;
}
}
private class MyCodeAction : CodeAction.CodeActionWithNestedActions
{
public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions)
: base(title, nestedActions, isInlinable: true)
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/InternalUtilities/IsExternalInit.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Copied from:
// https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Copied from:
// https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Features/Core/Portable/EditAndContinue/UnmappedActiveStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal readonly struct UnmappedActiveStatement
{
/// <summary>
/// Unmapped span of the active statement
/// (span within the file that contains #line directive that has an effect on the active statement, if there is any).
/// </summary>
public TextSpan UnmappedSpan { get; }
/// <summary>
/// Active statement - its <see cref="ActiveStatement.FileSpan"/> is mapped.
/// </summary>
public ActiveStatement Statement { get; }
/// <summary>
/// Mapped exception regions around the active statement.
/// </summary>
public ActiveStatementExceptionRegions ExceptionRegions { get; }
public UnmappedActiveStatement(TextSpan unmappedSpan, ActiveStatement statement, ActiveStatementExceptionRegions exceptionRegions)
{
UnmappedSpan = unmappedSpan;
Statement = statement;
ExceptionRegions = exceptionRegions;
}
public void Deconstruct(out TextSpan unmappedSpan, out ActiveStatement statement, out ActiveStatementExceptionRegions exceptionRegions)
{
unmappedSpan = UnmappedSpan;
statement = Statement;
exceptionRegions = ExceptionRegions;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal readonly struct UnmappedActiveStatement
{
/// <summary>
/// Unmapped span of the active statement
/// (span within the file that contains #line directive that has an effect on the active statement, if there is any).
/// </summary>
public TextSpan UnmappedSpan { get; }
/// <summary>
/// Active statement - its <see cref="ActiveStatement.FileSpan"/> is mapped.
/// </summary>
public ActiveStatement Statement { get; }
/// <summary>
/// Mapped exception regions around the active statement.
/// </summary>
public ActiveStatementExceptionRegions ExceptionRegions { get; }
public UnmappedActiveStatement(TextSpan unmappedSpan, ActiveStatement statement, ActiveStatementExceptionRegions exceptionRegions)
{
UnmappedSpan = unmappedSpan;
Statement = statement;
ExceptionRegions = exceptionRegions;
}
public void Deconstruct(out TextSpan unmappedSpan, out ActiveStatement statement, out ActiveStatementExceptionRegions exceptionRegions)
{
unmappedSpan = UnmappedSpan;
statement = Statement;
exceptionRegions = ExceptionRegions;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle
{
public abstract partial class BooleanCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest
{
protected internal override string GetLanguage() => LanguageNames.CSharp;
protected override ParseOptions GetScriptOptions() => Options.Script;
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider());
}
public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 0;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = false:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = true:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
public class FalseConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 1;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = true:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = false:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle
{
public abstract partial class BooleanCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest
{
protected internal override string GetLanguage() => LanguageNames.CSharp;
protected override ParseOptions GetScriptOptions() => Options.Script;
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider());
}
public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 0;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = false:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = true:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
public class FalseConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 1;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = true:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = false:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Test/Resources/Core/SymbolsTests/ExplicitInterfaceImplementation/CSharpExplicitInterfaceImplementationEvents.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//csc /target:library
using System;
interface Interface
{
event Action<int> Event;
}
class Class : Interface
{
event Action<int> Interface.Event { add { } remove { } }
}
interface IGeneric<T>
{
event Action<T> Event;
}
class Generic<S> : IGeneric<S>
{
event Action<S> IGeneric<S>.Event { add { } remove { } }
}
class Constructed : IGeneric<int>
{
event Action<int> IGeneric<int>.Event { add { } remove { } }
}
interface IGenericInterface<T> : Interface
{
}
//we'll see a type def for this class, a type ref for IGenericInterface<int>,
//and then a type def for Interface (i.e. back and forth)
class IndirectImplementation : IGenericInterface<int>
{
event Action<int> Interface.Event { add { } remove { } }
}
interface IGeneric2<T>
{
event Action<T> Event;
}
class Outer<T>
{
public interface IInner<U>
{
event Action<U> Event;
}
public class Inner1<A> : IGeneric2<A> //outer interface, inner type param
{
event Action<A> IGeneric2<A>.Event { add { } remove { } }
}
public class Inner2<B> : IGeneric2<T> //outer interface, outer type param
{
event Action<T> IGeneric2<T>.Event { add { } remove { } }
}
internal class Inner3<C> : IInner<C> //inner interface, inner type param
{
event Action<C> IInner<C>.Event { add { } remove { } }
}
protected class Inner4<D> : IInner<T> //inner interface, outer type param
{
event Action<T> IInner<T>.Event { add { } remove { } }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//csc /target:library
using System;
interface Interface
{
event Action<int> Event;
}
class Class : Interface
{
event Action<int> Interface.Event { add { } remove { } }
}
interface IGeneric<T>
{
event Action<T> Event;
}
class Generic<S> : IGeneric<S>
{
event Action<S> IGeneric<S>.Event { add { } remove { } }
}
class Constructed : IGeneric<int>
{
event Action<int> IGeneric<int>.Event { add { } remove { } }
}
interface IGenericInterface<T> : Interface
{
}
//we'll see a type def for this class, a type ref for IGenericInterface<int>,
//and then a type def for Interface (i.e. back and forth)
class IndirectImplementation : IGenericInterface<int>
{
event Action<int> Interface.Event { add { } remove { } }
}
interface IGeneric2<T>
{
event Action<T> Event;
}
class Outer<T>
{
public interface IInner<U>
{
event Action<U> Event;
}
public class Inner1<A> : IGeneric2<A> //outer interface, inner type param
{
event Action<A> IGeneric2<A>.Event { add { } remove { } }
}
public class Inner2<B> : IGeneric2<T> //outer interface, outer type param
{
event Action<T> IGeneric2<T>.Event { add { } remove { } }
}
internal class Inner3<C> : IInner<C> //inner interface, inner type param
{
event Action<C> IInner<C>.Event { add { } remove { } }
}
protected class Inner4<D> : IInner<T> //inner interface, outer type param
{
event Action<T> IInner<T>.Event { add { } remove { } }
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BidirectionalMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Roslyn.Utilities
{
internal class BidirectionalMap<TKey, TValue> : IBidirectionalMap<TKey, TValue>
where TKey : notnull
where TValue : notnull
{
public static readonly IBidirectionalMap<TKey, TValue> Empty =
new BidirectionalMap<TKey, TValue>(ImmutableDictionary.Create<TKey, TValue>(), ImmutableDictionary.Create<TValue, TKey>());
private readonly ImmutableDictionary<TKey, TValue> _forwardMap;
private readonly ImmutableDictionary<TValue, TKey> _backwardMap;
public BidirectionalMap(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
_forwardMap = ImmutableDictionary.CreateRange<TKey, TValue>(pairs);
_backwardMap = ImmutableDictionary.CreateRange<TValue, TKey>(pairs.Select(p => KeyValuePairUtil.Create(p.Value, p.Key)));
}
private BidirectionalMap(ImmutableDictionary<TKey, TValue> forwardMap, ImmutableDictionary<TValue, TKey> backwardMap)
{
_forwardMap = forwardMap;
_backwardMap = backwardMap;
}
public bool TryGetValue(TKey key, [NotNullWhen(true)] out TValue? value)
=> _forwardMap.TryGetValue(key, out value);
public bool TryGetKey(TValue value, [NotNullWhen(true)] out TKey? key)
=> _backwardMap.TryGetValue(value, out key);
public bool ContainsKey(TKey key)
=> _forwardMap.ContainsKey(key);
public bool ContainsValue(TValue value)
=> _backwardMap.ContainsKey(value);
public IBidirectionalMap<TKey, TValue> RemoveKey(TKey key)
{
if (!_forwardMap.TryGetValue(key, out var value))
{
return this;
}
return new BidirectionalMap<TKey, TValue>(
_forwardMap.Remove(key),
_backwardMap.Remove(value));
}
public IBidirectionalMap<TKey, TValue> RemoveValue(TValue value)
{
if (!_backwardMap.TryGetValue(value, out var key))
{
return this;
}
return new BidirectionalMap<TKey, TValue>(
_forwardMap.Remove(key),
_backwardMap.Remove(value));
}
public IBidirectionalMap<TKey, TValue> Add(TKey key, TValue value)
{
return new BidirectionalMap<TKey, TValue>(
_forwardMap.Add(key, value),
_backwardMap.Add(value, key));
}
public IEnumerable<TKey> Keys => _forwardMap.Keys;
public IEnumerable<TValue> Values => _backwardMap.Keys;
public bool IsEmpty
{
get
{
return _backwardMap.Count == 0;
}
}
public int Count
{
get
{
Debug.Assert(_forwardMap.Count == _backwardMap.Count);
return _backwardMap.Count;
}
}
public TValue? GetValueOrDefault(TKey key)
{
if (TryGetValue(key, out var result))
{
return result;
}
return default;
}
public TKey? GetKeyOrDefault(TValue value)
{
if (TryGetKey(value, out var result))
{
return result;
}
return default;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Roslyn.Utilities
{
internal class BidirectionalMap<TKey, TValue> : IBidirectionalMap<TKey, TValue>
where TKey : notnull
where TValue : notnull
{
public static readonly IBidirectionalMap<TKey, TValue> Empty =
new BidirectionalMap<TKey, TValue>(ImmutableDictionary.Create<TKey, TValue>(), ImmutableDictionary.Create<TValue, TKey>());
private readonly ImmutableDictionary<TKey, TValue> _forwardMap;
private readonly ImmutableDictionary<TValue, TKey> _backwardMap;
public BidirectionalMap(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
_forwardMap = ImmutableDictionary.CreateRange<TKey, TValue>(pairs);
_backwardMap = ImmutableDictionary.CreateRange<TValue, TKey>(pairs.Select(p => KeyValuePairUtil.Create(p.Value, p.Key)));
}
private BidirectionalMap(ImmutableDictionary<TKey, TValue> forwardMap, ImmutableDictionary<TValue, TKey> backwardMap)
{
_forwardMap = forwardMap;
_backwardMap = backwardMap;
}
public bool TryGetValue(TKey key, [NotNullWhen(true)] out TValue? value)
=> _forwardMap.TryGetValue(key, out value);
public bool TryGetKey(TValue value, [NotNullWhen(true)] out TKey? key)
=> _backwardMap.TryGetValue(value, out key);
public bool ContainsKey(TKey key)
=> _forwardMap.ContainsKey(key);
public bool ContainsValue(TValue value)
=> _backwardMap.ContainsKey(value);
public IBidirectionalMap<TKey, TValue> RemoveKey(TKey key)
{
if (!_forwardMap.TryGetValue(key, out var value))
{
return this;
}
return new BidirectionalMap<TKey, TValue>(
_forwardMap.Remove(key),
_backwardMap.Remove(value));
}
public IBidirectionalMap<TKey, TValue> RemoveValue(TValue value)
{
if (!_backwardMap.TryGetValue(value, out var key))
{
return this;
}
return new BidirectionalMap<TKey, TValue>(
_forwardMap.Remove(key),
_backwardMap.Remove(value));
}
public IBidirectionalMap<TKey, TValue> Add(TKey key, TValue value)
{
return new BidirectionalMap<TKey, TValue>(
_forwardMap.Add(key, value),
_backwardMap.Add(value, key));
}
public IEnumerable<TKey> Keys => _forwardMap.Keys;
public IEnumerable<TValue> Values => _backwardMap.Keys;
public bool IsEmpty
{
get
{
return _backwardMap.Count == 0;
}
}
public int Count
{
get
{
Debug.Assert(_forwardMap.Count == _backwardMap.Count);
return _backwardMap.Count;
}
}
public TValue? GetValueOrDefault(TKey key)
{
if (TryGetValue(key, out var result))
{
return result;
}
return default;
}
public TKey? GetKeyOrDefault(TValue value)
{
if (TryGetKey(value, out var result))
{
return result;
}
return default;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Test/Core/Traits/CompilerFeature.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Test.Utilities
{
public enum CompilerFeature
{
Async,
Dynamic,
ExpressionBody,
Determinism,
Iterator,
LocalFunctions,
Params,
Var,
Tuples,
RefLocalsReturns,
ReadOnlyReferences,
OutVar,
Patterns,
DefaultLiteral,
AsyncMain,
IOperation,
Dataflow,
NonTrailingNamedArgs,
PrivateProtected,
PEVerifyCompat,
RefConditionalOperator,
TupleEquality,
StackAllocInitializer,
NullCoalescingAssignment,
AsyncStreams,
NullableReferenceTypes,
DefaultInterfaceImplementation,
LambdaDiscardParameters,
StatementAttributes,
TopLevelStatements,
InitOnlySetters,
AnonymousFunctions,
ModuleInitializers,
FunctionPointers,
RecordStructs,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Test.Utilities
{
public enum CompilerFeature
{
Async,
Dynamic,
ExpressionBody,
Determinism,
Iterator,
LocalFunctions,
Params,
Var,
Tuples,
RefLocalsReturns,
ReadOnlyReferences,
OutVar,
Patterns,
DefaultLiteral,
AsyncMain,
IOperation,
Dataflow,
NonTrailingNamedArgs,
PrivateProtected,
PEVerifyCompat,
RefConditionalOperator,
TupleEquality,
StackAllocInitializer,
NullCoalescingAssignment,
AsyncStreams,
NullableReferenceTypes,
DefaultInterfaceImplementation,
LambdaDiscardParameters,
StatementAttributes,
TopLevelStatements,
InitOnlySetters,
AnonymousFunctions,
ModuleInitializers,
FunctionPointers,
RecordStructs,
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationTypeParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationTypeParameterSymbol : CodeGenerationTypeSymbol, ITypeParameterSymbol
{
public VarianceKind Variance { get; }
public ImmutableArray<ITypeSymbol> ConstraintTypes { get; internal set; }
public bool HasConstructorConstraint { get; }
public bool HasReferenceTypeConstraint { get; }
public bool HasValueTypeConstraint { get; }
public bool HasUnmanagedTypeConstraint { get; }
public bool HasNotNullConstraint { get; }
public int Ordinal { get; }
public CodeGenerationTypeParameterSymbol(
INamedTypeSymbol containingType,
ImmutableArray<AttributeData> attributes,
VarianceKind varianceKind,
string name,
NullableAnnotation nullableAnnotation,
ImmutableArray<ITypeSymbol> constraintTypes,
bool hasConstructorConstraint,
bool hasReferenceConstraint,
bool hasValueConstraint,
bool hasUnmanagedConstraint,
bool hasNotNullConstraint,
int ordinal)
: base(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, default, name, SpecialType.None, nullableAnnotation)
{
this.Variance = varianceKind;
this.ConstraintTypes = constraintTypes;
this.Ordinal = ordinal;
this.HasConstructorConstraint = hasConstructorConstraint;
this.HasReferenceTypeConstraint = hasReferenceConstraint;
this.HasValueTypeConstraint = hasValueConstraint;
this.HasUnmanagedTypeConstraint = hasUnmanagedConstraint;
this.HasNotNullConstraint = hasNotNullConstraint;
}
protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation)
{
return new CodeGenerationTypeParameterSymbol(
this.ContainingType, this.GetAttributes(), this.Variance, this.Name, nullableAnnotation,
this.ConstraintTypes, this.HasConstructorConstraint, this.HasReferenceTypeConstraint,
this.HasValueTypeConstraint, this.HasUnmanagedTypeConstraint, this.HasNotNullConstraint, this.Ordinal);
}
public new ITypeParameterSymbol OriginalDefinition => this;
public ITypeParameterSymbol ReducedFrom => null;
public override SymbolKind Kind => SymbolKind.TypeParameter;
public override void Accept(SymbolVisitor visitor)
=> visitor.VisitTypeParameter(this);
public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
=> visitor.VisitTypeParameter(this);
public override TypeKind TypeKind => TypeKind.TypeParameter;
public TypeParameterKind TypeParameterKind
{
get
{
return this.DeclaringMethod != null
? TypeParameterKind.Method
: TypeParameterKind.Type;
}
}
public IMethodSymbol DeclaringMethod
{
get
{
return this.ContainingSymbol as IMethodSymbol;
}
}
public INamedTypeSymbol DeclaringType
{
get
{
return this.ContainingSymbol as INamedTypeSymbol;
}
}
public NullableAnnotation ReferenceTypeConstraintNullableAnnotation => throw new System.NotImplementedException();
public ImmutableArray<NullableAnnotation> ConstraintNullableAnnotations => ConstraintTypes.SelectAsArray(t => t.NullableAnnotation);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationTypeParameterSymbol : CodeGenerationTypeSymbol, ITypeParameterSymbol
{
public VarianceKind Variance { get; }
public ImmutableArray<ITypeSymbol> ConstraintTypes { get; internal set; }
public bool HasConstructorConstraint { get; }
public bool HasReferenceTypeConstraint { get; }
public bool HasValueTypeConstraint { get; }
public bool HasUnmanagedTypeConstraint { get; }
public bool HasNotNullConstraint { get; }
public int Ordinal { get; }
public CodeGenerationTypeParameterSymbol(
INamedTypeSymbol containingType,
ImmutableArray<AttributeData> attributes,
VarianceKind varianceKind,
string name,
NullableAnnotation nullableAnnotation,
ImmutableArray<ITypeSymbol> constraintTypes,
bool hasConstructorConstraint,
bool hasReferenceConstraint,
bool hasValueConstraint,
bool hasUnmanagedConstraint,
bool hasNotNullConstraint,
int ordinal)
: base(containingType?.ContainingAssembly, containingType, attributes, Accessibility.NotApplicable, default, name, SpecialType.None, nullableAnnotation)
{
this.Variance = varianceKind;
this.ConstraintTypes = constraintTypes;
this.Ordinal = ordinal;
this.HasConstructorConstraint = hasConstructorConstraint;
this.HasReferenceTypeConstraint = hasReferenceConstraint;
this.HasValueTypeConstraint = hasValueConstraint;
this.HasUnmanagedTypeConstraint = hasUnmanagedConstraint;
this.HasNotNullConstraint = hasNotNullConstraint;
}
protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation)
{
return new CodeGenerationTypeParameterSymbol(
this.ContainingType, this.GetAttributes(), this.Variance, this.Name, nullableAnnotation,
this.ConstraintTypes, this.HasConstructorConstraint, this.HasReferenceTypeConstraint,
this.HasValueTypeConstraint, this.HasUnmanagedTypeConstraint, this.HasNotNullConstraint, this.Ordinal);
}
public new ITypeParameterSymbol OriginalDefinition => this;
public ITypeParameterSymbol ReducedFrom => null;
public override SymbolKind Kind => SymbolKind.TypeParameter;
public override void Accept(SymbolVisitor visitor)
=> visitor.VisitTypeParameter(this);
public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
=> visitor.VisitTypeParameter(this);
public override TypeKind TypeKind => TypeKind.TypeParameter;
public TypeParameterKind TypeParameterKind
{
get
{
return this.DeclaringMethod != null
? TypeParameterKind.Method
: TypeParameterKind.Type;
}
}
public IMethodSymbol DeclaringMethod
{
get
{
return this.ContainingSymbol as IMethodSymbol;
}
}
public INamedTypeSymbol DeclaringType
{
get
{
return this.ContainingSymbol as INamedTypeSymbol;
}
}
public NullableAnnotation ReferenceTypeConstraintNullableAnnotation => throw new System.NotImplementedException();
public ImmutableArray<NullableAnnotation> ConstraintNullableAnnotations => ConstraintTypes.SelectAsArray(t => t.NullableAnnotation);
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Compilers/Core/Portable/Diagnostic/NoLocation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A class that represents no location at all. Useful for errors in command line options, for example.
/// </summary>
/// <remarks></remarks>
internal sealed class NoLocation : Location
{
public static readonly Location Singleton = new NoLocation();
private NoLocation()
{
}
public override LocationKind Kind
{
get { return LocationKind.None; }
}
public override bool Equals(object? obj)
{
return (object)this == obj;
}
public override int GetHashCode()
{
// arbitrary number, since all NoLocation's are equal
return 0x16487756;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A class that represents no location at all. Useful for errors in command line options, for example.
/// </summary>
/// <remarks></remarks>
internal sealed class NoLocation : Location
{
public static readonly Location Singleton = new NoLocation();
private NoLocation()
{
}
public override LocationKind Kind
{
get { return LocationKind.None; }
}
public override bool Equals(object? obj)
{
return (object)this == obj;
}
public override int GetHashCode()
{
// arbitrary number, since all NoLocation's are equal
return 0x16487756;
}
}
}
| -1 |
dotnet/roslyn | 55,981 | Share 'when' expressions in DAGs when needed | Fixes https://github.com/dotnet/roslyn/issues/55668 | jcouv | "2021-08-27T23:18:23Z" | "2021-08-31T15:57:39Z" | ddd74827b476144bc72ed2c88e85880540dc4e55 | 5e3ecf0550c428d4204c9716f3401c0d54021344 | Share 'when' expressions in DAGs when needed. Fixes https://github.com/dotnet/roslyn/issues/55668 | ./src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForConstructorsHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForConstructorsHelper :
UseExpressionBodyHelper<ConstructorDeclarationSyntax>
{
public static readonly UseExpressionBodyForConstructorsHelper Instance = new();
private UseExpressionBodyForConstructorsHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForConstructorsDiagnosticId,
EnforceOnBuildValues.UseExpressionBodyForConstructors,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_constructors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_constructors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedConstructors,
ImmutableArray.Create(SyntaxKind.ConstructorDeclaration))
{
}
protected override BlockSyntax GetBody(ConstructorDeclarationSyntax declaration)
=> declaration.Body;
protected override ArrowExpressionClauseSyntax GetExpressionBody(ConstructorDeclarationSyntax declaration)
=> declaration.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(ConstructorDeclarationSyntax declaration)
=> declaration.SemicolonToken;
protected override ConstructorDeclarationSyntax WithSemicolonToken(ConstructorDeclarationSyntax declaration, SyntaxToken token)
=> declaration.WithSemicolonToken(token);
protected override ConstructorDeclarationSyntax WithExpressionBody(ConstructorDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody)
=> declaration.WithExpressionBody(expressionBody);
protected override ConstructorDeclarationSyntax WithBody(ConstructorDeclarationSyntax declaration, BlockSyntax body)
=> declaration.WithBody(body);
protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, ConstructorDeclarationSyntax declaration) => false;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForConstructorsHelper :
UseExpressionBodyHelper<ConstructorDeclarationSyntax>
{
public static readonly UseExpressionBodyForConstructorsHelper Instance = new();
private UseExpressionBodyForConstructorsHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForConstructorsDiagnosticId,
EnforceOnBuildValues.UseExpressionBodyForConstructors,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_constructors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_constructors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedConstructors,
ImmutableArray.Create(SyntaxKind.ConstructorDeclaration))
{
}
protected override BlockSyntax GetBody(ConstructorDeclarationSyntax declaration)
=> declaration.Body;
protected override ArrowExpressionClauseSyntax GetExpressionBody(ConstructorDeclarationSyntax declaration)
=> declaration.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(ConstructorDeclarationSyntax declaration)
=> declaration.SemicolonToken;
protected override ConstructorDeclarationSyntax WithSemicolonToken(ConstructorDeclarationSyntax declaration, SyntaxToken token)
=> declaration.WithSemicolonToken(token);
protected override ConstructorDeclarationSyntax WithExpressionBody(ConstructorDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody)
=> declaration.WithExpressionBody(expressionBody);
protected override ConstructorDeclarationSyntax WithBody(ConstructorDeclarationSyntax declaration, BlockSyntax body)
=> declaration.WithBody(body);
protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, ConstructorDeclarationSyntax declaration) => false;
}
}
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.